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 PackIndex ///< Index of a pack indexing expression or specifier.
852};
853
854/// Enums for the diagnostics of target, target_version and target_clones.
855namespace DiagAttrParams {
856enum DiagType { Unsupported, Duplicate, Unknown };
857enum Specifier { None, CPU, Tune };
858enum AttrName { Target, TargetClones, TargetVersion };
859} // end namespace DiagAttrParams
860
861void inferNoReturnAttr(Sema &S, Decl *D);
862
863#ifdef __GNUC__
864#pragma GCC diagnostic push
865#pragma GCC diagnostic ignored "-Wattributes"
866#endif
867/// Sema - This implements semantic analysis and AST building for C.
868/// \nosubgrouping
869class Sema final : public SemaBase {
870#ifdef __GNUC__
871#pragma GCC diagnostic pop
872#endif
873 // Table of Contents
874 // -----------------
875 // 1. Semantic Analysis (Sema.cpp)
876 // 2. API Notes (SemaAPINotes.cpp)
877 // 3. C++ Access Control (SemaAccess.cpp)
878 // 4. Attributes (SemaAttr.cpp)
879 // 5. Availability Attribute Handling (SemaAvailability.cpp)
880 // 6. Bounds Safety (SemaBoundsSafety.cpp)
881 // 7. Casts (SemaCast.cpp)
882 // 8. Extra Semantic Checking (SemaChecking.cpp)
883 // 9. C++ Coroutines (SemaCoroutine.cpp)
884 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
885 // 11. Declarations (SemaDecl.cpp)
886 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
887 // 13. C++ Declarations (SemaDeclCXX.cpp)
888 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
889 // 15. Expressions (SemaExpr.cpp)
890 // 16. C++ Expressions (SemaExprCXX.cpp)
891 // 17. Member Access Expressions (SemaExprMember.cpp)
892 // 18. Initializers (SemaInit.cpp)
893 // 19. C++ Lambda Expressions (SemaLambda.cpp)
894 // 20. Name Lookup (SemaLookup.cpp)
895 // 21. Modules (SemaModule.cpp)
896 // 22. C++ Overloading (SemaOverload.cpp)
897 // 23. Statements (SemaStmt.cpp)
898 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
899 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
900 // 26. C++ Templates (SemaTemplate.cpp)
901 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
902 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
903 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
904 // 30. C++ Template Declaration Instantiation
905 // (SemaTemplateInstantiateDecl.cpp)
906 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
907 // 32. Constraints and Concepts (SemaConcept.cpp)
908 // 33. Types (SemaType.cpp)
909 // 34. FixIt Helpers (SemaFixItUtils.cpp)
910 // 35. Function Effects (SemaFunctionEffects.cpp)
911 // 36. C++ Expansion Statements (SemaExpand.cpp)
912
913 /// \name Semantic Analysis
914 /// Implementations are in Sema.cpp
915 ///@{
916
917public:
918 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
919 TranslationUnitKind TUKind = TU_Complete,
920 CodeCompleteConsumer *CompletionConsumer = nullptr);
921 ~Sema();
922
923 /// Perform initialization that occurs after the parser has been
924 /// initialized but before it parses anything.
925 void Initialize();
926
927 /// This virtual key function only exists to limit the emission of debug info
928 /// describing the Sema class. GCC and Clang only emit debug info for a class
929 /// with a vtable when the vtable is emitted. Sema is final and not
930 /// polymorphic, but the debug info size savings are so significant that it is
931 /// worth adding a vtable just to take advantage of this optimization.
932 LLVM_DECLARE_VIRTUAL_ANCHOR_FUNCTION();
933
934 const LangOptions &getLangOpts() const { return LangOpts; }
935 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
936 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
937
938 DiagnosticsEngine &getDiagnostics() const { return Diags; }
939 SourceManager &getSourceManager() const { return SourceMgr; }
940 Preprocessor &getPreprocessor() const { return PP; }
941 ASTContext &getASTContext() const { return Context; }
942 ASTConsumer &getASTConsumer() const { return Consumer; }
943 ASTMutationListener *getASTMutationListener() const;
944 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
945
946 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
947 StringRef Platform);
948 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
949
950 /// Registers an external source. If an external source already exists,
951 /// creates a multiplex external source and appends to it.
952 ///
953 ///\param[in] E - A non-null external sema source.
954 ///
955 void addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E);
956
957 /// Print out statistics about the semantic analysis.
958 void PrintStats() const;
959
960 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
961 /// guaranteed). Produces a warning if we're low on stack space and allocates
962 /// more in that case. Use this in code that may recurse deeply (for example,
963 /// in template instantiation) to avoid stack overflow.
964 void runWithSufficientStackSpace(SourceLocation Loc,
965 llvm::function_ref<void()> Fn);
966
967 /// Returns default addr space for method qualifiers.
968 LangAS getDefaultCXXMethodAddrSpace() const;
969
970 /// Load weak undeclared identifiers from the external source.
971 void LoadExternalWeakUndeclaredIdentifiers();
972
973 /// Load #pragma redefine_extname'd undeclared identifiers from the external
974 /// source.
975 void LoadExternalExtnameUndeclaredIdentifiers();
976
977 /// Determine if VD, which must be a variable or function, is an external
978 /// symbol that nonetheless can't be referenced from outside this translation
979 /// unit because its type has no linkage and it's not extern "C".
980 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
981
982 /// Determines whether the given source location is in the main file
983 /// and we're in a context where we should warn about unused entities.
984 bool isMainFileLoc(SourceLocation Loc) const;
985
986 /// Obtain a sorted list of functions that are undefined but ODR-used.
987 void getUndefinedButUsed(
988 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
989
990 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
991 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
992 /// Retrieves list of suspicious delete-expressions that will be checked at
993 /// the end of translation unit.
994 const llvm::MapVector<FieldDecl *, DeleteLocs> &
995 getMismatchingDeleteExpressions() const;
996
997 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
998 /// This is closely coupled to the SemaDiagnosticBuilder class and
999 /// should not be used elsewhere.
1000 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
1001
1002 void addImplicitTypedef(StringRef Name, QualType T);
1003
1004 /// Whether uncompilable error has occurred. This includes error happens
1005 /// in deferred diagnostics.
1006 bool hasUncompilableErrorOccurred() const;
1007
1008 /// Looks through the macro-expansion chain for the given
1009 /// location, looking for a macro expansion with the given name.
1010 /// If one is found, returns true and sets the location to that
1011 /// expansion loc.
1012 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1013
1014 /// Calls \c Lexer::getLocForEndOfToken()
1015 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1016
1017 /// Calls \c Lexer::findNextToken() to find the next token, and if the
1018 /// locations of both ends of the token can be resolved it return that
1019 /// range; Otherwise it returns an invalid SourceRange.
1020 SourceRange getRangeForNextToken(
1021 SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
1022 std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
1023
1024 /// Retrieve the module loader associated with the preprocessor.
1025 ModuleLoader &getModuleLoader() const;
1026
1027 /// Invent a new identifier for parameters of abbreviated templates.
1028 IdentifierInfo *
1029 InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName,
1030 unsigned Index);
1031
1032 void emitAndClearUnusedLocalTypedefWarnings();
1033
1034 // Emit all deferred diagnostics.
1035 void emitDeferredDiags();
1036
1037 /// This is called before the very first declaration in the translation unit
1038 /// is parsed. Note that the ASTContext may have already injected some
1039 /// declarations.
1040 void ActOnStartOfTranslationUnit();
1041 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1042 /// translation unit when EOF is reached and all but the top-level scope is
1043 /// popped.
1044 void ActOnEndOfTranslationUnit();
1045 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1046
1047 /// Determines the active Scope associated with the given declaration
1048 /// context.
1049 ///
1050 /// This routine maps a declaration context to the active Scope object that
1051 /// represents that declaration context in the parser. It is typically used
1052 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1053 /// declarations) that injects a name for name-lookup purposes and, therefore,
1054 /// must update the Scope.
1055 ///
1056 /// \returns The scope corresponding to the given declaraion context, or NULL
1057 /// if no such scope is open.
1058 Scope *getScopeForContext(DeclContext *Ctx);
1059
1060 void PushFunctionScope();
1061 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1062 sema::LambdaScopeInfo *PushLambdaScope();
1063
1064 /// This is used to inform Sema what the current TemplateParameterDepth
1065 /// is during Parsing. Currently it is used to pass on the depth
1066 /// when parsing generic lambda 'auto' parameters.
1067 void RecordParsingTemplateParameterDepth(unsigned Depth);
1068
1069 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1070 RecordDecl *RD, CapturedRegionKind K,
1071 unsigned OpenMPCaptureLevel = 0);
1072
1073 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1074 /// time after they've been popped.
1075 class PoppedFunctionScopeDeleter {
1076 Sema *Self;
1077
1078 public:
1079 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1080 void operator()(sema::FunctionScopeInfo *Scope) const;
1081 };
1082
1083 using PoppedFunctionScopePtr =
1084 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1085
1086 /// Pop a function (or block or lambda or captured region) scope from the
1087 /// stack.
1088 ///
1089 /// \param WP The warning policy to use for CFG-based warnings, or null if
1090 /// such warnings should not be produced.
1091 /// \param D The declaration corresponding to this function scope, if
1092 /// producing CFG-based warnings.
1093 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1094 PoppedFunctionScopePtr
1095 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1096 Decl *D = nullptr, QualType BlockType = QualType());
1097
1098 sema::FunctionScopeInfo *getEnclosingFunction() const;
1099
1100 void setFunctionHasBranchIntoScope();
1101 void setFunctionHasBranchProtectedScope();
1102 void setFunctionHasIndirectGoto();
1103 void setFunctionHasMustTail();
1104
1105 void PushCompoundScope(bool IsStmtExpr);
1106 void PopCompoundScope();
1107
1108 /// Determine whether any errors occurred within this function/method/
1109 /// block.
1110 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1111
1112 /// Retrieve the current block, if any.
1113 sema::BlockScopeInfo *getCurBlock();
1114
1115 /// Get the innermost lambda or block enclosing the current location, if any.
1116 /// This looks through intervening non-lambda, non-block scopes such as local
1117 /// functions.
1118 sema::CapturingScopeInfo *getEnclosingLambdaOrBlock() const;
1119
1120 /// Retrieve the current lambda scope info, if any.
1121 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1122 /// lambda scope info ignoring all inner capturing scopes that are not
1123 /// lambda scopes.
1124 sema::LambdaScopeInfo *
1125 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1126
1127 /// Retrieve the current generic lambda info, if any.
1128 sema::LambdaScopeInfo *getCurGenericLambda();
1129
1130 /// Retrieve the current captured region, if any.
1131 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1132
1133 void ActOnComment(SourceRange Comment);
1134
1135 /// Retrieve the parser's current scope.
1136 ///
1137 /// This routine must only be used when it is certain that semantic analysis
1138 /// and the parser are in precisely the same context, which is not the case
1139 /// when, e.g., we are performing any kind of template instantiation.
1140 /// Therefore, the only safe places to use this scope are in the parser
1141 /// itself and in routines directly invoked from the parser and *never* from
1142 /// template substitution or instantiation.
1143 Scope *getCurScope() const { return CurScope; }
1144
1145 IdentifierInfo *getSuperIdentifier() const;
1146
1147 DeclContext *getCurLexicalContext() const {
1148 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
1149 }
1150
1151 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1152 const FunctionDecl *FD = nullptr);
1153 SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
1154 const PartialDiagnostic &PD,
1155 const FunctionDecl *FD = nullptr) {
1156 return targetDiag(Loc, DiagID: PD.getDiagID(), FD) << PD;
1157 }
1158
1159 /// Check if the type is allowed to be used for the current target.
1160 void checkTypeSupport(QualType Ty, SourceLocation Loc,
1161 ValueDecl *D = nullptr);
1162
1163 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1164 /// cast. If there is already an implicit cast, merge into the existing one.
1165 /// If isLvalue, the result of the cast is an lvalue.
1166 ExprResult ImpCastExprToType(
1167 Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue,
1168 const CXXCastPath *BasePath = nullptr,
1169 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
1170
1171 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1172 /// to the conversion from scalar type ScalarTy to the Boolean type.
1173 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
1174
1175 /// If \p AllowLambda is true, treat lambda as function.
1176 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1177
1178 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1179 /// current context is not inside a function. If \p AllowLambda is true,
1180 /// this can return the call operator of an enclosing lambda, otherwise
1181 /// lambdas are skipped when looking for an enclosing function.
1182 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1183
1184 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1185 /// the method decl for the method being parsed. If we're currently
1186 /// in a 'block', this returns the containing context.
1187 ObjCMethodDecl *getCurMethodDecl();
1188
1189 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1190 /// or C function we're in, otherwise return null. If we're currently
1191 /// in a 'block', this returns the containing context.
1192 NamedDecl *getCurFunctionOrMethodDecl() const;
1193
1194 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1195 /// _Nonnull one.
1196 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
1197 SourceLocation Loc);
1198
1199 /// Warn when implicitly casting 0 to nullptr.
1200 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1201
1202 /// Warn when implicitly changing function effects.
1203 void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType,
1204 SourceLocation Loc);
1205
1206 /// makeUnavailableInSystemHeader - There is an error in the current
1207 /// context. If we're still in a system header, and we can plausibly
1208 /// make the relevant declaration unavailable instead of erroring, do
1209 /// so and return true.
1210 bool makeUnavailableInSystemHeader(SourceLocation loc,
1211 UnavailableAttr::ImplicitReason reason);
1212
1213 /// Retrieve a suitable printing policy for diagnostics.
1214 PrintingPolicy getPrintingPolicy() const {
1215 return getPrintingPolicy(Ctx: Context, PP);
1216 }
1217
1218 /// Retrieve a suitable printing policy for diagnostics.
1219 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1220 const Preprocessor &PP);
1221
1222 /// Scope actions.
1223 void ActOnTranslationUnitScope(Scope *S);
1224
1225 /// Determine whether \param D is function like (function or function
1226 /// template) for parsing.
1227 bool isDeclaratorFunctionLike(Declarator &D);
1228
1229 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1230 /// because that allows us not to duplicate the constants in clang code,
1231 /// which we must to since we can't directly use the llvm constants.
1232 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1233 ///
1234 /// This is the greatest alignment value supported by load, store, and alloca
1235 /// instructions, and global values.
1236 static const unsigned MaxAlignmentExponent = 32;
1237 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1238
1239 /// Flag indicating whether or not to collect detailed statistics.
1240 bool CollectStats;
1241
1242 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1243
1244 /// Stack containing information about each of the nested
1245 /// function, block, and method scopes that are currently active.
1246 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
1247
1248 /// The index of the first FunctionScope that corresponds to the current
1249 /// context.
1250 unsigned FunctionScopesStart = 0;
1251
1252 /// Track the number of currently active capturing scopes.
1253 unsigned CapturingFunctionScopes = 0;
1254
1255 llvm::BumpPtrAllocator BumpAlloc;
1256
1257 /// The kind of translation unit we are processing.
1258 ///
1259 /// When we're processing a complete translation unit, Sema will perform
1260 /// end-of-translation-unit semantic tasks (such as creating
1261 /// initializers for tentative definitions in C) once parsing has
1262 /// completed. Modules and precompiled headers perform different kinds of
1263 /// checks.
1264 const TranslationUnitKind TUKind;
1265
1266 /// Translation Unit Scope - useful to Objective-C actions that need
1267 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1268 /// For example, user-defined classes, built-in "id" type, etc.
1269 Scope *TUScope;
1270
1271 void incrementMSManglingNumber() const {
1272 return CurScope->incrementMSManglingNumber();
1273 }
1274
1275 /// Try to recover by turning the given expression into a
1276 /// call. Returns true if recovery was attempted or an error was
1277 /// emitted; this may also leave the ExprResult invalid.
1278 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1279 bool ForceComplain = false,
1280 bool (*IsPlausibleResult)(QualType) = nullptr);
1281
1282 // Adds implicit lifetime bound attribute for implicit this to its
1283 // TypeSourceInfo.
1284 void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD);
1285
1286 /// Figure out if an expression could be turned into a call.
1287 ///
1288 /// Use this when trying to recover from an error where the programmer may
1289 /// have written just the name of a function instead of actually calling it.
1290 ///
1291 /// \param E - The expression to examine.
1292 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1293 /// with no arguments, this parameter is set to the type returned by such a
1294 /// call; otherwise, it is set to an empty QualType.
1295 /// \param OverloadSet - If the expression is an overloaded function
1296 /// name, this parameter is populated with the decls of the various
1297 /// overloads.
1298 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1299 UnresolvedSetImpl &NonTemplateOverloads);
1300
1301 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
1302 typedef OpaquePtr<TemplateName> TemplateTy;
1303 typedef OpaquePtr<QualType> TypeTy;
1304
1305 OpenCLOptions OpenCLFeatures;
1306 FPOptions CurFPFeatures;
1307
1308 const LangOptions &LangOpts;
1309 Preprocessor &PP;
1310 ASTContext &Context;
1311 ASTConsumer &Consumer;
1312 DiagnosticsEngine &Diags;
1313 SourceManager &SourceMgr;
1314 api_notes::APINotesManager APINotes;
1315
1316 /// A RAII object to enter scope of a compound statement.
1317 class CompoundScopeRAII {
1318 public:
1319 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1320 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1321 }
1322
1323 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1324 CompoundScopeRAII(const CompoundScopeRAII &) = delete;
1325 CompoundScopeRAII &operator=(const CompoundScopeRAII &) = delete;
1326
1327 private:
1328 Sema &S;
1329 };
1330
1331 /// An RAII helper that pops function a function scope on exit.
1332 struct FunctionScopeRAII {
1333 Sema &S;
1334 bool Active;
1335 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
1336 ~FunctionScopeRAII() {
1337 if (Active)
1338 S.PopFunctionScopeInfo();
1339 }
1340 void disable() { Active = false; }
1341 };
1342
1343 sema::FunctionScopeInfo *getCurFunction() const {
1344 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1345 }
1346
1347 /// Worker object for performing CFG-based warnings.
1348 sema::AnalysisBasedWarnings AnalysisWarnings;
1349 threadSafety::BeforeSet *ThreadSafetyDeclCache;
1350
1351 /// Callback to the parser to parse templated functions when needed.
1352 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1353 LateTemplateParserCB *LateTemplateParser;
1354 void *OpaqueParser;
1355
1356 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
1357 LateTemplateParser = LTP;
1358 OpaqueParser = P;
1359 }
1360
1361 /// Callback to the parser to parse a type expressed as a string.
1362 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1363 ParseTypeFromStringCallback;
1364
1365 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1366 /// This is used as part of a hack to omit that class from ADL results.
1367 DeclarationName VAListTagName;
1368
1369 /// Is the last error level diagnostic immediate. This is used to determined
1370 /// whether the next info diagnostic should be immediate.
1371 bool IsLastErrorImmediate = true;
1372
1373 /// Track if we're currently analyzing overflow behavior types in assignment
1374 /// context.
1375 bool InOverflowBehaviorAssignmentContext = false;
1376
1377 class DelayedDiagnostics;
1378
1379 class DelayedDiagnosticsState {
1380 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1381 friend class Sema::DelayedDiagnostics;
1382 };
1383 typedef DelayedDiagnosticsState ParsingDeclState;
1384 typedef DelayedDiagnosticsState ProcessingContextState;
1385
1386 /// A class which encapsulates the logic for delaying diagnostics
1387 /// during parsing and other processing.
1388 class DelayedDiagnostics {
1389 /// The current pool of diagnostics into which delayed
1390 /// diagnostics should go.
1391 sema::DelayedDiagnosticPool *CurPool = nullptr;
1392
1393 public:
1394 DelayedDiagnostics() = default;
1395
1396 /// Adds a delayed diagnostic.
1397 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1398
1399 /// Determines whether diagnostics should be delayed.
1400 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1401
1402 /// Returns the current delayed-diagnostics pool.
1403 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1404
1405 /// Enter a new scope. Access and deprecation diagnostics will be
1406 /// collected in this pool.
1407 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
1408 DelayedDiagnosticsState state;
1409 state.SavedPool = CurPool;
1410 CurPool = &pool;
1411 return state;
1412 }
1413
1414 /// Leave a delayed-diagnostic state that was previously pushed.
1415 /// Do not emit any of the diagnostics. This is performed as part
1416 /// of the bookkeeping of popping a pool "properly".
1417 void popWithoutEmitting(DelayedDiagnosticsState state) {
1418 CurPool = state.SavedPool;
1419 }
1420
1421 /// Enter a new scope where access and deprecation diagnostics are
1422 /// not delayed.
1423 DelayedDiagnosticsState pushUndelayed() {
1424 DelayedDiagnosticsState state;
1425 state.SavedPool = CurPool;
1426 CurPool = nullptr;
1427 return state;
1428 }
1429
1430 /// Undo a previous pushUndelayed().
1431 void popUndelayed(DelayedDiagnosticsState state) {
1432 assert(CurPool == nullptr);
1433 CurPool = state.SavedPool;
1434 }
1435 } DelayedDiagnostics;
1436
1437 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
1438 return DelayedDiagnostics.push(pool);
1439 }
1440
1441 /// Diagnostics that are emitted only if we discover that the given function
1442 /// must be codegen'ed. Because handling these correctly adds overhead to
1443 /// compilation, this is currently only used for offload languages like CUDA,
1444 /// OpenMP, and SYCL.
1445 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1446
1447 /// CurContext - This is the current declaration context of parsing.
1448 DeclContext *CurContext;
1449
1450 SemaAMDGPU &AMDGPU() {
1451 assert(AMDGPUPtr);
1452 return *AMDGPUPtr;
1453 }
1454
1455 SemaARM &ARM() {
1456 assert(ARMPtr);
1457 return *ARMPtr;
1458 }
1459
1460 SemaAVR &AVR() {
1461 assert(AVRPtr);
1462 return *AVRPtr;
1463 }
1464
1465 SemaBPF &BPF() {
1466 assert(BPFPtr);
1467 return *BPFPtr;
1468 }
1469
1470 SemaCodeCompletion &CodeCompletion() {
1471 assert(CodeCompletionPtr);
1472 return *CodeCompletionPtr;
1473 }
1474
1475 SemaCUDA &CUDA() {
1476 assert(CUDAPtr);
1477 return *CUDAPtr;
1478 }
1479
1480 SemaDirectX &DirectX() {
1481 assert(DirectXPtr);
1482 return *DirectXPtr;
1483 }
1484
1485 SemaHLSL &HLSL() {
1486 assert(HLSLPtr);
1487 return *HLSLPtr;
1488 }
1489
1490 SemaHexagon &Hexagon() {
1491 assert(HexagonPtr);
1492 return *HexagonPtr;
1493 }
1494
1495 SemaLoongArch &LoongArch() {
1496 assert(LoongArchPtr);
1497 return *LoongArchPtr;
1498 }
1499
1500 SemaM68k &M68k() {
1501 assert(M68kPtr);
1502 return *M68kPtr;
1503 }
1504
1505 SemaMIPS &MIPS() {
1506 assert(MIPSPtr);
1507 return *MIPSPtr;
1508 }
1509
1510 SemaMSP430 &MSP430() {
1511 assert(MSP430Ptr);
1512 return *MSP430Ptr;
1513 }
1514
1515 SemaNVPTX &NVPTX() {
1516 assert(NVPTXPtr);
1517 return *NVPTXPtr;
1518 }
1519
1520 SemaObjC &ObjC() {
1521 assert(ObjCPtr);
1522 return *ObjCPtr;
1523 }
1524
1525 SemaOpenACC &OpenACC() {
1526 assert(OpenACCPtr);
1527 return *OpenACCPtr;
1528 }
1529
1530 SemaOpenCL &OpenCL() {
1531 assert(OpenCLPtr);
1532 return *OpenCLPtr;
1533 }
1534
1535 SemaOpenMP &OpenMP() {
1536 assert(OpenMPPtr && "SemaOpenMP is dead");
1537 return *OpenMPPtr;
1538 }
1539
1540 SemaPPC &PPC() {
1541 assert(PPCPtr);
1542 return *PPCPtr;
1543 }
1544
1545 SemaPseudoObject &PseudoObject() {
1546 assert(PseudoObjectPtr);
1547 return *PseudoObjectPtr;
1548 }
1549
1550 SemaRISCV &RISCV() {
1551 assert(RISCVPtr);
1552 return *RISCVPtr;
1553 }
1554
1555 SemaSPIRV &SPIRV() {
1556 assert(SPIRVPtr);
1557 return *SPIRVPtr;
1558 }
1559
1560 SemaSYCL &SYCL() {
1561 assert(SYCLPtr);
1562 return *SYCLPtr;
1563 }
1564
1565 SemaSwift &Swift() {
1566 assert(SwiftPtr);
1567 return *SwiftPtr;
1568 }
1569
1570 SemaSystemZ &SystemZ() {
1571 assert(SystemZPtr);
1572 return *SystemZPtr;
1573 }
1574
1575 SemaWasm &Wasm() {
1576 assert(WasmPtr);
1577 return *WasmPtr;
1578 }
1579
1580 SemaX86 &X86() {
1581 assert(X86Ptr);
1582 return *X86Ptr;
1583 }
1584
1585 /// Source of additional semantic information.
1586 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
1587
1588protected:
1589 friend class Parser;
1590 friend class InitializationSequence;
1591 friend class ASTReader;
1592 friend class ASTDeclReader;
1593 friend class ASTWriter;
1594
1595private:
1596 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1597 bool WarnedDarwinSDKInfoMissing = false;
1598
1599 StackExhaustionHandler StackHandler;
1600
1601 Sema(const Sema &) = delete;
1602 void operator=(const Sema &) = delete;
1603
1604 /// The handler for the FileChanged preprocessor events.
1605 ///
1606 /// Used for diagnostics that implement custom semantic analysis for #include
1607 /// directives, like -Wpragma-pack.
1608 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1609
1610 /// The parser's current scope.
1611 ///
1612 /// The parser maintains this state here.
1613 Scope *CurScope;
1614
1615 mutable IdentifierInfo *Ident_super;
1616
1617 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1618 std::unique_ptr<SemaARM> ARMPtr;
1619 std::unique_ptr<SemaAVR> AVRPtr;
1620 std::unique_ptr<SemaBPF> BPFPtr;
1621 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1622 std::unique_ptr<SemaCUDA> CUDAPtr;
1623 std::unique_ptr<SemaDirectX> DirectXPtr;
1624 std::unique_ptr<SemaHLSL> HLSLPtr;
1625 std::unique_ptr<SemaHexagon> HexagonPtr;
1626 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1627 std::unique_ptr<SemaM68k> M68kPtr;
1628 std::unique_ptr<SemaMIPS> MIPSPtr;
1629 std::unique_ptr<SemaMSP430> MSP430Ptr;
1630 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1631 std::unique_ptr<SemaObjC> ObjCPtr;
1632 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1633 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1634 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1635 std::unique_ptr<SemaPPC> PPCPtr;
1636 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1637 std::unique_ptr<SemaRISCV> RISCVPtr;
1638 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1639 std::unique_ptr<SemaSYCL> SYCLPtr;
1640 std::unique_ptr<SemaSwift> SwiftPtr;
1641 std::unique_ptr<SemaSystemZ> SystemZPtr;
1642 std::unique_ptr<SemaWasm> WasmPtr;
1643 std::unique_ptr<SemaX86> X86Ptr;
1644
1645 ///@}
1646
1647 //
1648 //
1649 // -------------------------------------------------------------------------
1650 //
1651 //
1652
1653 /// \name API Notes
1654 /// Implementations are in SemaAPINotes.cpp
1655 ///@{
1656
1657public:
1658 /// Map any API notes provided for this declaration to attributes on the
1659 /// declaration.
1660 ///
1661 /// Triggered by declaration-attribute processing.
1662 void ProcessAPINotes(Decl *D);
1663 /// Apply the 'Nullability:' annotation to the specified declaration
1664 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1665 /// Apply the 'Type:' annotation to the specified declaration
1666 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1667
1668 /// Whether APINotes should be gathered for all applicable Swift language
1669 /// versions, without being applied. Leaving clients of the current module
1670 /// to select and apply the correct version.
1671 bool captureSwiftVersionIndependentAPINotes() {
1672 return APINotes.captureVersionIndependentSwift();
1673 }
1674 ///@}
1675
1676 //
1677 //
1678 // -------------------------------------------------------------------------
1679 //
1680 //
1681
1682 /// \name C++ Access Control
1683 /// Implementations are in SemaAccess.cpp
1684 ///@{
1685
1686public:
1687 enum AccessResult {
1688 AR_accessible,
1689 AR_inaccessible,
1690 AR_dependent,
1691 AR_delayed
1692 };
1693
1694 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1695 /// Returns true on error (when the previous member decl access specifier
1696 /// is different from the new member decl access specifier).
1697 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1698 NamedDecl *PrevMemberDecl,
1699 AccessSpecifier LexicalAS);
1700
1701 /// Perform access-control checking on a previously-unresolved member
1702 /// access which has now been resolved to a member.
1703 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
1704 DeclAccessPair FoundDecl);
1705 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
1706 DeclAccessPair FoundDecl);
1707
1708 /// Checks access to an overloaded operator new or delete.
1709 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
1710 SourceRange PlacementRange,
1711 CXXRecordDecl *NamingClass,
1712 DeclAccessPair FoundDecl,
1713 bool Diagnose = true);
1714
1715 /// Checks access to a constructor.
1716 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1717 DeclAccessPair FoundDecl,
1718 const InitializedEntity &Entity,
1719 bool IsCopyBindingRefToTemp = false);
1720
1721 /// Checks access to a constructor.
1722 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1723 DeclAccessPair FoundDecl,
1724 const InitializedEntity &Entity,
1725 const PartialDiagnostic &PDiag);
1726 AccessResult CheckDestructorAccess(SourceLocation Loc,
1727 CXXDestructorDecl *Dtor,
1728 const PartialDiagnostic &PDiag,
1729 QualType objectType = QualType());
1730
1731 /// Checks access to the target of a friend declaration.
1732 AccessResult CheckFriendAccess(NamedDecl *D);
1733
1734 /// Checks access to a member.
1735 AccessResult CheckMemberAccess(SourceLocation UseLoc,
1736 CXXRecordDecl *NamingClass,
1737 DeclAccessPair Found);
1738
1739 /// Checks implicit access to a member in a structured binding.
1740 AccessResult
1741 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1742 CXXRecordDecl *DecomposedClass,
1743 DeclAccessPair Field);
1744 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1745 const SourceRange &,
1746 DeclAccessPair FoundDecl);
1747
1748 /// Checks access to an overloaded member operator, including
1749 /// conversion operators.
1750 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1751 Expr *ArgExpr,
1752 DeclAccessPair FoundDecl);
1753 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1754 ArrayRef<Expr *> ArgExprs,
1755 DeclAccessPair FoundDecl);
1756 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
1757 DeclAccessPair FoundDecl);
1758
1759 /// Checks access for a hierarchy conversion.
1760 ///
1761 /// \param ForceCheck true if this check should be performed even if access
1762 /// control is disabled; some things rely on this for semantics
1763 /// \param ForceUnprivileged true if this check should proceed as if the
1764 /// context had no special privileges
1765 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base,
1766 QualType Derived, const CXXBasePath &Path,
1767 unsigned DiagID, bool ForceCheck = false,
1768 bool ForceUnprivileged = false);
1769
1770 AccessResult CheckBaseClassAccess(
1771 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1772 const CXXBasePath &Path, unsigned DiagID,
1773 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1774 bool ForceCheck = false, bool ForceUnprivileged = false);
1775
1776 /// Checks access to all the declarations in the given result set.
1777 void CheckLookupAccess(const LookupResult &R);
1778
1779 /// Checks access to Target from the given class. The check will take access
1780 /// specifiers into account, but no member access expressions and such.
1781 ///
1782 /// \param Target the declaration to check if it can be accessed
1783 /// \param NamingClass the class in which the lookup was started.
1784 /// \param BaseType type of the left side of member access expression.
1785 /// \p BaseType and \p NamingClass are used for C++ access control.
1786 /// Depending on the lookup case, they should be set to the following:
1787 /// - lhs.target (member access without a qualifier):
1788 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1789 /// - lhs.X::target (member access with a qualifier):
1790 /// BaseType is the type of 'lhs', NamingClass is 'X'
1791 /// - X::target (qualified lookup without member access):
1792 /// BaseType is null, NamingClass is 'X'.
1793 /// - target (unqualified lookup).
1794 /// BaseType is null, NamingClass is the parent class of 'target'.
1795 /// \return true if the Target is accessible from the Class, false otherwise.
1796 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1797 QualType BaseType);
1798
1799 /// Is the given member accessible for the purposes of deciding whether to
1800 /// define a special member function as deleted?
1801 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1802 DeclAccessPair Found, QualType ObjectType,
1803 SourceLocation Loc,
1804 const PartialDiagnostic &Diag);
1805 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1806 DeclAccessPair Found,
1807 QualType ObjectType) {
1808 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1809 Loc: SourceLocation(), Diag: PDiag());
1810 }
1811
1812 void HandleDependentAccessCheck(
1813 const DependentDiagnostic &DD,
1814 const MultiLevelTemplateArgumentList &TemplateArgs);
1815 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
1816
1817 ///@}
1818
1819 //
1820 //
1821 // -------------------------------------------------------------------------
1822 //
1823 //
1824
1825 /// \name Attributes
1826 /// Implementations are in SemaAttr.cpp
1827 ///@{
1828
1829public:
1830 /// Controls member pointer representation format under the MS ABI.
1831 LangOptions::PragmaMSPointersToMembersKind
1832 MSPointerToMemberRepresentationMethod;
1833
1834 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1835
1836 /// Source location for newly created implicit MSInheritanceAttrs
1837 SourceLocation ImplicitMSInheritanceAttrLoc;
1838
1839 struct PragmaClangSection {
1840 std::string SectionName;
1841 bool Valid = false;
1842 SourceLocation PragmaLocation;
1843 };
1844
1845 PragmaClangSection PragmaClangBSSSection;
1846 PragmaClangSection PragmaClangDataSection;
1847 PragmaClangSection PragmaClangRodataSection;
1848 PragmaClangSection PragmaClangRelroSection;
1849 PragmaClangSection PragmaClangTextSection;
1850
1851 enum PragmaMsStackAction {
1852 PSK_Reset = 0x0, // #pragma ()
1853 PSK_Set = 0x1, // #pragma (value)
1854 PSK_Push = 0x2, // #pragma (push[, id])
1855 PSK_Pop = 0x4, // #pragma (pop[, id])
1856 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1857 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1858 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1859 };
1860
1861 struct PragmaPackInfo {
1862 PragmaMsStackAction Action;
1863 StringRef SlotLabel;
1864 Token Alignment;
1865 };
1866
1867 // #pragma pack and align.
1868 class AlignPackInfo {
1869 public:
1870 // `Native` represents default align mode, which may vary based on the
1871 // platform.
1872 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1873
1874 // #pragma pack info constructor
1875 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1876 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1877 assert(Num == PackNumber && "The pack number has been truncated.");
1878 }
1879
1880 // #pragma align info constructor
1881 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
1882 : PackAttr(false), AlignMode(M),
1883 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1884
1885 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1886
1887 AlignPackInfo() : AlignPackInfo(Native, false) {}
1888
1889 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1890 // integer encoding for it. This should only be passed to
1891 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1892 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1893 std::uint32_t Encoding{};
1894 if (Info.IsXLStack())
1895 Encoding |= IsXLMask;
1896
1897 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1898
1899 if (Info.IsPackAttr())
1900 Encoding |= PackAttrMask;
1901
1902 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1903
1904 return Encoding;
1905 }
1906
1907 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1908 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1909 AlignPackInfo::Mode M =
1910 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1911 int PackNumber = (Encoding & PackNumMask) >> 4;
1912
1913 if (Encoding & PackAttrMask)
1914 return AlignPackInfo(M, PackNumber, IsXL);
1915
1916 return AlignPackInfo(M, IsXL);
1917 }
1918
1919 bool IsPackAttr() const { return PackAttr; }
1920
1921 bool IsAlignAttr() const { return !PackAttr; }
1922
1923 Mode getAlignMode() const { return AlignMode; }
1924
1925 unsigned getPackNumber() const { return PackNumber; }
1926
1927 bool IsPackSet() const {
1928 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1929 // attriute on a decl.
1930 return PackNumber != UninitPackVal && PackNumber != 0;
1931 }
1932
1933 bool IsXLStack() const { return XLStack; }
1934
1935 bool operator==(const AlignPackInfo &Info) const {
1936 return std::tie(args: AlignMode, args: PackNumber, args: PackAttr, args: XLStack) ==
1937 std::tie(args: Info.AlignMode, args: Info.PackNumber, args: Info.PackAttr,
1938 args: Info.XLStack);
1939 }
1940
1941 bool operator!=(const AlignPackInfo &Info) const {
1942 return !(*this == Info);
1943 }
1944
1945 private:
1946 /// \brief True if this is a pragma pack attribute,
1947 /// not a pragma align attribute.
1948 bool PackAttr;
1949
1950 /// \brief The alignment mode that is in effect.
1951 Mode AlignMode;
1952
1953 /// \brief The pack number of the stack.
1954 unsigned char PackNumber;
1955
1956 /// \brief True if it is a XL #pragma align/pack stack.
1957 bool XLStack;
1958
1959 /// \brief Uninitialized pack value.
1960 static constexpr unsigned char UninitPackVal = -1;
1961
1962 // Masks to encode and decode an AlignPackInfo.
1963 static constexpr uint32_t IsXLMask{0x0000'0001};
1964 static constexpr uint32_t AlignModeMask{0x0000'0006};
1965 static constexpr uint32_t PackAttrMask{0x00000'0008};
1966 static constexpr uint32_t PackNumMask{0x0000'01F0};
1967 };
1968
1969 template <typename ValueType> struct PragmaStack {
1970 struct Slot {
1971 llvm::StringRef StackSlotLabel;
1972 ValueType Value;
1973 SourceLocation PragmaLocation;
1974 SourceLocation PragmaPushLocation;
1975 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
1976 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
1977 : StackSlotLabel(StackSlotLabel), Value(Value),
1978 PragmaLocation(PragmaLocation),
1979 PragmaPushLocation(PragmaPushLocation) {}
1980 };
1981
1982 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1983 llvm::StringRef StackSlotLabel, ValueType Value) {
1984 if (Action == PSK_Reset) {
1985 CurrentValue = DefaultValue;
1986 CurrentPragmaLocation = PragmaLocation;
1987 return;
1988 }
1989 if (Action & PSK_Push)
1990 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1991 PragmaLocation);
1992 else if (Action & PSK_Pop) {
1993 if (!StackSlotLabel.empty()) {
1994 // If we've got a label, try to find it and jump there.
1995 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
1996 return x.StackSlotLabel == StackSlotLabel;
1997 });
1998 // If we found the label so pop from there.
1999 if (I != Stack.rend()) {
2000 CurrentValue = I->Value;
2001 CurrentPragmaLocation = I->PragmaLocation;
2002 Stack.erase(std::prev(I.base()), Stack.end());
2003 }
2004 } else if (!Stack.empty()) {
2005 // We do not have a label, just pop the last entry.
2006 CurrentValue = Stack.back().Value;
2007 CurrentPragmaLocation = Stack.back().PragmaLocation;
2008 Stack.pop_back();
2009 }
2010 }
2011 if (Action & PSK_Set) {
2012 CurrentValue = Value;
2013 CurrentPragmaLocation = PragmaLocation;
2014 }
2015 }
2016
2017 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
2018 // method body to restore the stacks on exit, so it works like this:
2019 //
2020 // struct S {
2021 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
2022 // void Method {}
2023 // #pragma <name>(pop, InternalPragmaSlot)
2024 // };
2025 //
2026 // It works even with #pragma vtordisp, although MSVC doesn't support
2027 // #pragma vtordisp(push [, id], n)
2028 // syntax.
2029 //
2030 // Push / pop a named sentinel slot.
2031 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
2032 assert((Action == PSK_Push || Action == PSK_Pop) &&
2033 "Can only push / pop #pragma stack sentinels!");
2034 Act(PragmaLocation: CurrentPragmaLocation, Action, StackSlotLabel: Label, Value: CurrentValue);
2035 }
2036
2037 // Constructors.
2038 explicit PragmaStack(const ValueType &Default)
2039 : DefaultValue(Default), CurrentValue(Default) {}
2040
2041 bool hasValue() const { return CurrentValue != DefaultValue; }
2042
2043 SmallVector<Slot, 2> Stack;
2044 ValueType DefaultValue; // Value used for PSK_Reset action.
2045 ValueType CurrentValue;
2046 SourceLocation CurrentPragmaLocation;
2047 };
2048 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2049 // we shouldn't do so if they're in a module).
2050
2051 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2052 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2053 ///
2054 /// 0: Suppress all vtordisps
2055 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2056 /// structors
2057 /// 2: Always insert vtordisps to support RTTI on partially constructed
2058 /// objects
2059 PragmaStack<MSVtorDispMode> VtorDispStack;
2060 PragmaStack<AlignPackInfo> AlignPackStack;
2061 // The current #pragma align/pack values and locations at each #include.
2062 struct AlignPackIncludeState {
2063 AlignPackInfo CurrentValue;
2064 SourceLocation CurrentPragmaLocation;
2065 bool HasNonDefaultValue, ShouldWarnOnInclude;
2066 };
2067 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
2068 // Segment #pragmas.
2069 PragmaStack<StringLiteral *> DataSegStack;
2070 PragmaStack<StringLiteral *> BSSSegStack;
2071 PragmaStack<StringLiteral *> ConstSegStack;
2072 PragmaStack<StringLiteral *> CodeSegStack;
2073
2074 // #pragma strict_gs_check.
2075 PragmaStack<bool> StrictGuardStackCheckStack;
2076
2077 // This stack tracks the current state of Sema.CurFPFeatures.
2078 PragmaStack<FPOptionsOverride> FpPragmaStack;
2079 FPOptionsOverride CurFPFeatureOverrides() {
2080 FPOptionsOverride result;
2081 if (!FpPragmaStack.hasValue()) {
2082 result = FPOptionsOverride();
2083 } else {
2084 result = FpPragmaStack.CurrentValue;
2085 }
2086 return result;
2087 }
2088
2089 enum PragmaSectionKind {
2090 PSK_DataSeg,
2091 PSK_BSSSeg,
2092 PSK_ConstSeg,
2093 PSK_CodeSeg,
2094 };
2095
2096 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2097 // Actions should be performed only if we enter / exit a C++ method body.
2098 class PragmaStackSentinelRAII {
2099 public:
2100 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2101 ~PragmaStackSentinelRAII();
2102 PragmaStackSentinelRAII(const PragmaStackSentinelRAII &) = delete;
2103 PragmaStackSentinelRAII &
2104 operator=(const PragmaStackSentinelRAII &) = delete;
2105
2106 private:
2107 Sema &S;
2108 StringRef SlotLabel;
2109 bool ShouldAct;
2110 };
2111
2112 /// Last section used with #pragma init_seg.
2113 StringLiteral *CurInitSeg;
2114 SourceLocation CurInitSegLoc;
2115
2116 /// Sections used with #pragma alloc_text.
2117 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2118
2119 /// VisContext - Manages the stack for \#pragma GCC visibility.
2120 void *VisContext; // Really a "PragmaVisStack*"
2121
2122 /// This an attribute introduced by \#pragma clang attribute.
2123 struct PragmaAttributeEntry {
2124 SourceLocation Loc;
2125 ParsedAttr *Attribute;
2126 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
2127 bool IsUsed;
2128 };
2129
2130 /// A push'd group of PragmaAttributeEntries.
2131 struct PragmaAttributeGroup {
2132 /// The location of the push attribute.
2133 SourceLocation Loc;
2134 /// The namespace of this push group.
2135 const IdentifierInfo *Namespace;
2136 SmallVector<PragmaAttributeEntry, 2> Entries;
2137 };
2138
2139 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
2140
2141 /// The declaration that is currently receiving an attribute from the
2142 /// #pragma attribute stack.
2143 const Decl *PragmaAttributeCurrentTargetDecl;
2144
2145 /// This represents the last location of a "#pragma clang optimize off"
2146 /// directive if such a directive has not been closed by an "on" yet. If
2147 /// optimizations are currently "on", this is set to an invalid location.
2148 SourceLocation OptimizeOffPragmaLocation;
2149
2150 /// Get the location for the currently active "\#pragma clang optimize
2151 /// off". If this location is invalid, then the state of the pragma is "on".
2152 SourceLocation getOptimizeOffPragmaLocation() const {
2153 return OptimizeOffPragmaLocation;
2154 }
2155
2156 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2157 /// whether the optimizations in the list passed to the pragma should be
2158 /// turned off or on. This boolean is true by default because command line
2159 /// options are honored when `#pragma optimize("", on)`.
2160 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2161 bool MSPragmaOptimizeIsOn = true;
2162
2163 /// Set of no-builtin functions listed by \#pragma function.
2164 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
2165
2166 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2167 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2168 void AddAlignmentAttributesForRecord(RecordDecl *RD);
2169
2170 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2171 void AddMsStructLayoutForRecord(RecordDecl *RD);
2172
2173 /// Add gsl::Pointer attribute to std::container::iterator
2174 /// \param ND The declaration that introduces the name
2175 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2176 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2177
2178 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2179 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
2180
2181 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2182 void inferLifetimeBoundAttribute(FunctionDecl *FD);
2183
2184 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2185 void inferLifetimeCaptureByAttribute(FunctionDecl *FD);
2186
2187 /// Add [[gsl::Pointer]] attributes for std:: types.
2188 void inferGslPointerAttribute(TypedefNameDecl *TD);
2189
2190 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2191 StringRef ParamName);
2192 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2193 // can be the name of a function parameter, we need to parse the function
2194 // declaration and rest of the parameters before processesing 'X'. Therefore
2195 // do this lazily instead of processing while parsing the annotation itself.
2196 void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD);
2197
2198 /// Add _Nullable attributes for std:: types.
2199 void inferNullableClassAttribute(CXXRecordDecl *CRD);
2200
2201 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2202 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
2203 PragmaClangSectionAction Action,
2204 PragmaClangSectionKind SecKind,
2205 StringRef SecName);
2206
2207 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2208 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
2209 SourceLocation PragmaLoc);
2210
2211 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2212 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2213 StringRef SlotLabel, Expr *Alignment);
2214
2215 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2216 /// (unless they are value dependent or type dependent). Returns false
2217 /// and emits a diagnostic if one or more of the arguments could not be
2218 /// folded into a constant.
2219 bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
2220 MutableArrayRef<Expr *> Args);
2221
2222 enum class PragmaAlignPackDiagnoseKind {
2223 NonDefaultStateAtInclude,
2224 ChangedStateAtExit
2225 };
2226
2227 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
2228 SourceLocation IncludeLoc);
2229 void DiagnoseUnterminatedPragmaAlignPack();
2230
2231 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2232 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
2233
2234 /// ActOnPragmaMSComment - Called on well formed
2235 /// \#pragma comment(kind, "arg").
2236 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
2237 StringRef Arg);
2238
2239 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2240 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2241 StringRef Value);
2242
2243 /// Are precise floating point semantics currently enabled?
2244 bool isPreciseFPEnabled() {
2245 return !CurFPFeatures.getAllowFPReassociate() &&
2246 !CurFPFeatures.getNoSignedZero() &&
2247 !CurFPFeatures.getAllowReciprocal() &&
2248 !CurFPFeatures.getAllowApproxFunc();
2249 }
2250
2251 void ActOnPragmaFPEvalMethod(SourceLocation Loc,
2252 LangOptions::FPEvalMethodKind Value);
2253
2254 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2255 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2256 PragmaFloatControlKind Value);
2257
2258 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2259 /// pointers_to_members(representation method[, general purpose
2260 /// representation]).
2261 void ActOnPragmaMSPointersToMembers(
2262 LangOptions::PragmaMSPointersToMembersKind Kind,
2263 SourceLocation PragmaLoc);
2264
2265 /// Called on well formed \#pragma vtordisp().
2266 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2267 SourceLocation PragmaLoc, MSVtorDispMode Value);
2268
2269 bool UnifySection(StringRef SectionName, int SectionFlags,
2270 NamedDecl *TheDecl);
2271 bool UnifySection(StringRef SectionName, int SectionFlags,
2272 SourceLocation PragmaSectionLocation);
2273
2274 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2275 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2276 PragmaMsStackAction Action,
2277 llvm::StringRef StackSlotLabel,
2278 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2279
2280 /// Called on well formed \#pragma section().
2281 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2282 StringLiteral *SegmentName);
2283
2284 /// Called on well-formed \#pragma init_seg().
2285 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2286 StringLiteral *SegmentName);
2287
2288 /// Called on well-formed \#pragma alloc_text().
2289 void ActOnPragmaMSAllocText(
2290 SourceLocation PragmaLocation, StringRef Section,
2291 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2292 &Functions);
2293
2294 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2295 /// strict_gs_check.
2296 void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
2297 PragmaMsStackAction Action,
2298 bool Value);
2299
2300 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2301 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2302 SourceLocation PragmaLoc);
2303
2304 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
2305 SourceLocation PragmaLoc,
2306 attr::ParsedSubjectMatchRuleSet Rules);
2307 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
2308 const IdentifierInfo *Namespace);
2309
2310 /// Called on well-formed '\#pragma clang attribute pop'.
2311 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
2312 const IdentifierInfo *Namespace);
2313
2314 /// Adds the attributes that have been specified using the
2315 /// '\#pragma clang attribute push' directives to the given declaration.
2316 void AddPragmaAttributes(Scope *S, Decl *D);
2317
2318 using InstantiationContextDiagFuncRef =
2319 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2320 auto getDefaultDiagFunc() {
2321 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2322 // This bypasses a lot of the filters in the diag engine, as it's
2323 // to be used to attach notes to diagnostics which have already
2324 // been filtered through.
2325 DiagnosticBuilder Builder(Diags.Report(Loc, DiagID: PD.getDiagID()));
2326 PD.Emit(DB: Builder);
2327 };
2328 }
2329
2330 void PrintPragmaAttributeInstantiationPoint(
2331 InstantiationContextDiagFuncRef DiagFunc);
2332 void PrintPragmaAttributeInstantiationPoint() {
2333 PrintPragmaAttributeInstantiationPoint(DiagFunc: getDefaultDiagFunc());
2334 }
2335
2336 void DiagnoseUnterminatedPragmaAttribute();
2337
2338 /// Called on well formed \#pragma clang optimize.
2339 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2340
2341 /// #pragma optimize("[optimization-list]", on | off).
2342 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2343
2344 /// Call on well formed \#pragma function.
2345 void
2346 ActOnPragmaMSFunction(SourceLocation Loc,
2347 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2348
2349 NamedDecl *lookupExternCFunctionOrVariable(IdentifierInfo *IdentId,
2350 SourceLocation NameLoc,
2351 Scope *curScope);
2352
2353 /// Information from a C++ #pragma export, for a symbol that we
2354 /// haven't seen the declaration for yet.
2355 struct PendingPragmaInfo {
2356 SourceLocation NameLoc;
2357 bool Used;
2358 };
2359
2360 llvm::DenseMap<IdentifierInfo *, PendingPragmaInfo> PendingExportedNames;
2361
2362 /// ActonPragmaExport - called on well-formed '\#pragma export'.
2363 void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
2364 Scope *curScope);
2365
2366 /// Only called on function definitions; if there is a pragma in scope
2367 /// with the effect of a range-based optnone, consider marking the function
2368 /// with attribute optnone.
2369 void AddRangeBasedOptnone(FunctionDecl *FD);
2370
2371 /// Only called on function definitions; if there is a `#pragma alloc_text`
2372 /// that decides which code section the function should be in, add
2373 /// attribute section to the function.
2374 void AddSectionMSAllocText(FunctionDecl *FD);
2375
2376 /// Adds the 'optnone' attribute to the function declaration if there
2377 /// are no conflicts; Loc represents the location causing the 'optnone'
2378 /// attribute to be added (usually because of a pragma).
2379 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
2380
2381 /// Only called on function definitions; if there is a MSVC #pragma optimize
2382 /// in scope, consider changing the function's attributes based on the
2383 /// optimization list passed to the pragma.
2384 void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
2385
2386 /// Only called on function definitions; if there is a pragma in scope
2387 /// with the effect of a range-based no_builtin, consider marking the function
2388 /// with attribute no_builtin.
2389 void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
2390
2391 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2392 /// add an appropriate visibility attribute.
2393 void AddPushedVisibilityAttribute(Decl *RD);
2394
2395 /// FreeVisContext - Deallocate and null out VisContext.
2396 void FreeVisContext();
2397
2398 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2399 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2400 SourceLocation PragmaLoc);
2401
2402 /// ActOnPragmaFPContract - Called on well formed
2403 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2404 /// \#pragma clang fp contract
2405 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
2406
2407 /// Called on well formed
2408 /// \#pragma clang fp reassociate
2409 /// or
2410 /// \#pragma clang fp reciprocal
2411 void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind,
2412 bool IsEnabled);
2413
2414 /// ActOnPragmaFenvAccess - Called on well formed
2415 /// \#pragma STDC FENV_ACCESS
2416 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2417
2418 /// ActOnPragmaCXLimitedRange - Called on well formed
2419 /// \#pragma STDC CX_LIMITED_RANGE
2420 void ActOnPragmaCXLimitedRange(SourceLocation Loc,
2421 LangOptions::ComplexRangeKind Range);
2422
2423 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2424 void ActOnPragmaFPExceptions(SourceLocation Loc,
2425 LangOptions::FPExceptionModeKind);
2426
2427 /// Called to set constant rounding mode for floating point operations.
2428 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2429
2430 /// Called to set exception behavior for floating point operations.
2431 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
2432
2433 /// PushNamespaceVisibilityAttr - Note that we've entered a
2434 /// namespace with a visibility attribute.
2435 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2436 SourceLocation Loc);
2437
2438 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2439 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2440 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2441
2442 /// Handles semantic checking for features that are common to all attributes,
2443 /// such as checking whether a parameter was properly specified, or the
2444 /// correct number of arguments were passed, etc. Returns true if the
2445 /// attribute has been diagnosed.
2446 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2447 bool SkipArgCountCheck = false);
2448 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2449 bool SkipArgCountCheck = false);
2450
2451 ///@}
2452
2453 //
2454 //
2455 // -------------------------------------------------------------------------
2456 //
2457 //
2458
2459 /// \name Availability Attribute Handling
2460 /// Implementations are in SemaAvailability.cpp
2461 ///@{
2462
2463public:
2464 /// Issue any -Wunguarded-availability warnings in \c FD
2465 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
2466
2467 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2468
2469 /// Retrieve the current function, if any, that should be analyzed for
2470 /// potential availability violations.
2471 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2472
2473 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
2474 const ObjCInterfaceDecl *UnknownObjCClass,
2475 bool ObjCPropertyAccess,
2476 bool AvoidPartialAvailabilityChecks,
2477 ObjCInterfaceDecl *ClassReceiver);
2478
2479 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs);
2480
2481 std::pair<AvailabilityResult, const NamedDecl *>
2482 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2483 ObjCInterfaceDecl *ClassReceiver);
2484 ///@}
2485
2486 //
2487 //
2488 // -------------------------------------------------------------------------
2489 //
2490 //
2491
2492 /// \name Bounds Safety
2493 /// Implementations are in SemaBoundsSafety.cpp
2494 ///@{
2495public:
2496 /// Check if applying the specified attribute variant from the "counted by"
2497 /// family of attributes to FieldDecl \p FD is semantically valid. If
2498 /// semantically invalid diagnostics will be emitted explaining the problems.
2499 ///
2500 /// \param FD The FieldDecl to apply the attribute to
2501 /// \param E The count expression on the attribute
2502 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2503 /// attributes. If the false the attribute is from
2504 /// "counted_by" family of attributes.
2505 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2506 /// of attributes. If false the attribute does not have the
2507 /// suffix.
2508 ///
2509 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2510 /// \p CountInBytes and \p OrNull both being true indicates the
2511 /// `counted_by_or_null` attribute.
2512 ///
2513 /// \returns false iff semantically valid.
2514 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2515 bool OrNull);
2516
2517 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2518 /// `__counted_by_or_null` pointer type \param LHSTy.
2519 ///
2520 /// \param LHSTy The type being assigned to. Checks will only be performed if
2521 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2522 /// \param RHSExpr The expression being assigned from.
2523 /// \param Action The type assignment being performed
2524 /// \param Loc The SourceLocation to use for error diagnostics
2525 /// \param Assignee The ValueDecl being assigned. This is used to compute
2526 /// the name of the assignee. If the assignee isn't known this can
2527 /// be set to nullptr.
2528 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2529 /// Assignee to compute the name of the assignee use the fully
2530 /// qualified name, otherwise use the unqualified name.
2531 ///
2532 /// \returns True iff no diagnostic where emitted, false otherwise.
2533 bool BoundsSafetyCheckAssignmentToCountAttrPtr(
2534 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2535 SourceLocation Loc, const ValueDecl *Assignee,
2536 bool ShowFullyQualifiedAssigneeName);
2537
2538 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2539 /// pointer.
2540 ///
2541 /// \param Entity The entity being initialized
2542 /// \param Kind The kind of initialization being performed
2543 /// \param Action The type assignment being performed
2544 /// \param LHSTy The type being assigned to. Checks will only be performed if
2545 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2546 /// \param RHSExpr The expression being used for initialization.
2547 ///
2548 /// \returns True iff no diagnostic where emitted, false otherwise.
2549 bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity,
2550 const InitializationKind &Kind,
2551 AssignmentAction Action,
2552 QualType LHSType, Expr *RHSExpr);
2553
2554 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2555 /// or counted_by_or_null pointers in \param E.
2556 ///
2557 /// \param E the expression to check
2558 ///
2559 /// \returns True iff no diagnostic where emitted, false otherwise.
2560 bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E);
2561 ///@}
2562
2563 //
2564 //
2565 // -------------------------------------------------------------------------
2566 //
2567 //
2568
2569 /// \name Casts
2570 /// Implementations are in SemaCast.cpp
2571 ///@{
2572
2573public:
2574 static bool isCast(CheckedConversionKind CCK) {
2575 return CCK == CheckedConversionKind::CStyleCast ||
2576 CCK == CheckedConversionKind::FunctionalCast ||
2577 CCK == CheckedConversionKind::OtherCast;
2578 }
2579
2580 /// ActOnCXXNamedCast - Parse
2581 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2582 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2583 SourceLocation LAngleBracketLoc, Declarator &D,
2584 SourceLocation RAngleBracketLoc,
2585 SourceLocation LParenLoc, Expr *E,
2586 SourceLocation RParenLoc);
2587
2588 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2589 TypeSourceInfo *Ty, Expr *E,
2590 SourceRange AngleBrackets, SourceRange Parens);
2591
2592 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
2593 ExprResult Operand,
2594 SourceLocation RParenLoc);
2595
2596 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
2597 Expr *Operand, SourceLocation RParenLoc);
2598
2599 // Checks that reinterpret casts don't have undefined behavior.
2600 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2601 bool IsDereference, SourceRange Range);
2602
2603 // Checks that the vector type should be initialized from a scalar
2604 // by splatting the value rather than populating a single element.
2605 // This is the case for AltiVecVector types as well as with
2606 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2607 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2608
2609 // Checks if the -faltivec-src-compat=gcc option is specified.
2610 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2611 // treated the same way as they are when trying to initialize
2612 // these vectors on gcc (an error is emitted).
2613 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
2614 QualType SrcTy);
2615
2616 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
2617 SourceLocation RParenLoc, Expr *Op);
2618
2619 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
2620 SourceLocation LParenLoc,
2621 Expr *CastExpr,
2622 SourceLocation RParenLoc);
2623
2624 ///@}
2625
2626 //
2627 //
2628 // -------------------------------------------------------------------------
2629 //
2630 //
2631
2632 /// \name Extra Semantic Checking
2633 /// Implementations are in SemaChecking.cpp
2634 ///@{
2635
2636public:
2637 /// Used to change context to isConstantEvaluated without pushing a heavy
2638 /// ExpressionEvaluationContextRecord object.
2639 bool isConstantEvaluatedOverride = false;
2640
2641 bool isConstantEvaluatedContext() const {
2642 return currentEvaluationContext().isConstantEvaluated() ||
2643 isConstantEvaluatedOverride;
2644 }
2645
2646 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
2647 unsigned ByteNo) const;
2648
2649 enum FormatArgumentPassingKind {
2650 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2651 FAPK_Variadic, // values to format are passed as variadic arguments
2652 FAPK_VAList, // values to format are passed in a va_list
2653 FAPK_Elsewhere, // values to format are not passed to this function
2654 };
2655
2656 // Used to grab the relevant information from a FormatAttr and a
2657 // FunctionDeclaration.
2658 struct FormatStringInfo {
2659 unsigned FormatIdx;
2660 unsigned FirstDataArg;
2661 FormatArgumentPassingKind ArgPassingKind;
2662 };
2663
2664 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2665 /// populate the FormatStringInfo parameter with the attribute's correct
2666 /// format_idx and firstDataArg. Returns true when the format fits the
2667 /// function and the FormatStringInfo has been populated.
2668 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2669 unsigned FirstArg, FormatStringInfo *FSI);
2670 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2671 bool HasImplicitThisParam, bool IsVariadic,
2672 FormatStringInfo *FSI);
2673
2674 // Used by C++ template instantiation.
2675 ExprResult BuiltinShuffleVector(CallExpr *TheCall);
2676
2677 /// ConvertVectorExpr - Handle __builtin_convertvector
2678 ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2679 SourceLocation BuiltinLoc,
2680 SourceLocation RParenLoc);
2681
2682 static StringRef GetFormatStringTypeName(FormatStringType FST);
2683 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2684 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2685 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2686
2687 bool FormatStringHasSArg(const StringLiteral *FExpr);
2688
2689 /// Check for comparisons of floating-point values using == and !=. Issue a
2690 /// warning if the comparison is not likely to do what the programmer
2691 /// intended.
2692 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2693 const Expr *RHS, BinaryOperatorKind Opcode);
2694
2695 /// Register a magic integral constant to be used as a type tag.
2696 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2697 uint64_t MagicValue, QualType Type,
2698 bool LayoutCompatible, bool MustBeNull);
2699
2700 struct TypeTagData {
2701 TypeTagData() {}
2702
2703 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
2704 : Type(Type), LayoutCompatible(LayoutCompatible),
2705 MustBeNull(MustBeNull) {}
2706
2707 QualType Type;
2708
2709 /// If true, \c Type should be compared with other expression's types for
2710 /// layout-compatibility.
2711 LLVM_PREFERRED_TYPE(bool)
2712 unsigned LayoutCompatible : 1;
2713 LLVM_PREFERRED_TYPE(bool)
2714 unsigned MustBeNull : 1;
2715 };
2716
2717 /// A pair of ArgumentKind identifier and magic value. This uniquely
2718 /// identifies the magic value.
2719 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2720
2721 /// Diagnoses the current set of gathered accesses. This happens at the end of
2722 /// each expression evaluation context. Diagnostics are emitted only for
2723 /// accesses gathered in the current evaluation context.
2724 void DiagnoseMisalignedMembers();
2725
2726 /// This function checks if the expression is in the sef of potentially
2727 /// misaligned members and it is converted to some pointer type T with lower
2728 /// or equal alignment requirements. If so it removes it. This is used when
2729 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2730 /// void*).
2731 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2732
2733 /// Returns true if `From` is a function or pointer to a function with the
2734 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2735 /// function without this attribute.
2736 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2737
2738 /// This function calls Action when it determines that E designates a
2739 /// misaligned member due to the packed attribute. This is used to emit
2740 /// local diagnostics like in reference binding.
2741 void RefersToMemberWithReducedAlignment(
2742 Expr *E,
2743 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2744 Action);
2745
2746 enum class AtomicArgumentOrder { API, AST };
2747 ExprResult
2748 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2749 SourceLocation RParenLoc, MultiExprArg Args,
2750 AtomicExpr::AtomicOp Op,
2751 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
2752
2753 /// Check to see if a given expression could have '.c_str()' called on it.
2754 bool hasCStrMethod(const Expr *E);
2755
2756 /// Diagnose pointers that are always non-null.
2757 /// \param E the expression containing the pointer
2758 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2759 /// compared to a null pointer
2760 /// \param IsEqual True when the comparison is equal to a null pointer
2761 /// \param Range Extra SourceRange to highlight in the diagnostic
2762 void DiagnoseAlwaysNonNullPointer(Expr *E,
2763 Expr::NullPointerConstantKind NullType,
2764 bool IsEqual, SourceRange Range);
2765
2766 /// CheckParmsForFunctionDef - Check that the parameters of the given
2767 /// function are appropriate for the definition of a function. This
2768 /// takes care of any checks that cannot be performed on the
2769 /// declaration itself, e.g., that the types of each of the function
2770 /// parameters are complete.
2771 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2772 bool CheckParameterNames);
2773
2774 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2775 /// pointer cast increases the alignment requirements.
2776 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2777
2778 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2779 /// to weak/__unsafe_unretained type.
2780 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2781
2782 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2783 /// to weak/__unsafe_unretained expression.
2784 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2785
2786 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2787 /// statement as a \p Body, and it is located on the same line.
2788 ///
2789 /// This helps prevent bugs due to typos, such as:
2790 /// if (condition);
2791 /// do_stuff();
2792 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2793 unsigned DiagID);
2794
2795 /// Warn if a for/while loop statement \p S, which is followed by
2796 /// \p PossibleBody, has a suspicious null statement as a body.
2797 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2798
2799 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2800 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2801 SourceLocation OpLoc);
2802
2803 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2804 bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
2805 const TypeSourceInfo *Derived);
2806
2807 /// CheckFunctionCall - Check a direct function call for various correctness
2808 /// and safety properties not strictly enforced by the C type system.
2809 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2810 const FunctionProtoType *Proto);
2811
2812 enum class EltwiseBuiltinArgTyRestriction {
2813 None,
2814 FloatTy,
2815 IntegerTy,
2816 SignedIntOrFloatTy,
2817 };
2818
2819 /// \param FPOnly restricts the arguments to floating-point types.
2820 std::optional<QualType>
2821 BuiltinVectorMath(CallExpr *TheCall,
2822 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2823 EltwiseBuiltinArgTyRestriction::None);
2824 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2825
2826 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2827 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2828
2829 /// Handles the checks for format strings, non-POD arguments to vararg
2830 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2831 /// attributes and AArch64 SME attributes.
2832 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2833 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2834 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2835 VariadicCallType CallType);
2836
2837 /// Verify that two format strings (as understood by attribute(format) and
2838 /// attribute(format_matches) are compatible. If they are incompatible,
2839 /// diagnostics are emitted with the assumption that \c
2840 /// AuthoritativeFormatString is correct and
2841 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2842 /// diagnostics will point to it and a note will refer to \c
2843 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2844 bool
2845 CheckFormatStringsCompatible(FormatStringType FST,
2846 const StringLiteral *AuthoritativeFormatString,
2847 const StringLiteral *TestedFormatString,
2848 const Expr *FunctionCallArg = nullptr);
2849
2850 /// Verify that one format string (as understood by attribute(format)) is
2851 /// self-consistent; for instance, that it doesn't have multiple positional
2852 /// arguments referring to the same argument in incompatible ways. Diagnose
2853 /// if it isn't.
2854 bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str);
2855
2856 /// \brief Enforce the bounds of a TCB
2857 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2858 /// directly calls other functions in the same TCB as marked by the
2859 /// enforce_tcb and enforce_tcb_leaf attributes.
2860 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2861 const NamedDecl *Callee);
2862
2863 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2864
2865 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2866 /// TheCall is a constant expression.
2867 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2868 llvm::APSInt &Result);
2869
2870 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2871 /// TheCall is a constant expression in the range [Low, High].
2872 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2873 int High, bool RangeIsError = true);
2874
2875 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2876 /// TheCall is a constant expression is a multiple of Num..
2877 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2878 unsigned Multiple);
2879
2880 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2881 /// constant expression representing a power of 2.
2882 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
2883
2884 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2885 /// a constant expression representing an arbitrary byte value shifted left by
2886 /// a multiple of 8 bits.
2887 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
2888 unsigned ArgBits);
2889
2890 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2891 /// TheCall is a constant expression representing either a shifted byte value,
2892 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2893 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2894 /// Arm MVE intrinsics.
2895 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
2896 unsigned ArgBits);
2897
2898 /// Checks that a call expression's argument count is at least the desired
2899 /// number. This is useful when doing custom type-checking on a variadic
2900 /// function. Returns true on error.
2901 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2902
2903 /// Checks that a call expression's argument count is at most the desired
2904 /// number. This is useful when doing custom type-checking on a variadic
2905 /// function. Returns true on error.
2906 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2907
2908 /// Checks that a call expression's argument count is in the desired range.
2909 /// This is useful when doing custom type-checking on a variadic function.
2910 /// Returns true on error.
2911 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2912 unsigned MaxArgCount);
2913
2914 /// Checks that a call expression's argument count is the desired number.
2915 /// This is useful when doing custom type-checking. Returns true on error.
2916 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2917
2918 /// Returns true if the argument consists of one contiguous run of 1s with any
2919 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2920 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2921 /// since all 1s are not contiguous.
2922 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2923
2924 void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
2925 bool *ICContext = nullptr,
2926 bool IsListInit = false);
2927
2928 /// Check for overflow behavior type related implicit conversion diagnostics.
2929 /// Returns true if OBT-related diagnostic was issued, false otherwise.
2930 bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
2931 SourceLocation CC);
2932
2933 bool
2934 BuiltinElementwiseTernaryMath(CallExpr *TheCall,
2935 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2936 EltwiseBuiltinArgTyRestriction::FloatTy);
2937 bool PrepareBuiltinElementwiseMathOneArgCall(
2938 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
2939 EltwiseBuiltinArgTyRestriction::None);
2940
2941private:
2942 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2943 const ArraySubscriptExpr *ASE = nullptr,
2944 bool AllowOnePastEnd = true, bool IndexNegated = false);
2945 void CheckArrayAccess(const Expr *E);
2946
2947 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2948 const FunctionProtoType *Proto);
2949
2950 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2951 /// such as function pointers returned from functions.
2952 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2953
2954 /// CheckConstructorCall - Check a constructor call for correctness and safety
2955 /// properties not enforced by the C type system.
2956 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2957 ArrayRef<const Expr *> Args,
2958 const FunctionProtoType *Proto, SourceLocation Loc);
2959
2960 /// Warn if a pointer or reference argument passed to a function points to an
2961 /// object that is less aligned than the parameter. This can happen when
2962 /// creating a typedef with a lower alignment than the original type and then
2963 /// calling functions defined in terms of the original type.
2964 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2965 StringRef ParamName, QualType ArgTy, QualType ParamTy);
2966
2967 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2968
2969 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2970 CallExpr *TheCall);
2971
2972 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2973 CallExpr *TheCall);
2974
2975 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2976
2977 /// Argument-value fortify checks for libc functions that are not builtins,
2978 /// dispatched by name (e.g. umask). Diagnostics belong to -Wfortify-source.
2979 void checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall);
2980
2981 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
2982 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
2983 /// on failure; return false on success.
2984 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2985 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2986
2987 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2988 /// friends. This is declared to take (...), so we have to check everything.
2989 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2990
2991 /// BuiltinSemaBuiltinFPClassification - Handle functions like
2992 /// __builtin_isnan and friends. This is declared to take (...), so we have
2993 /// to check everything.
2994 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
2995 unsigned BuiltinID);
2996
2997 /// Perform semantic analysis for a call to __builtin_complex.
2998 bool BuiltinComplex(CallExpr *TheCall);
2999 bool BuiltinOSLogFormat(CallExpr *TheCall);
3000
3001 /// BuiltinPrefetch - Handle __builtin_prefetch.
3002 /// This is declared to take (const void*, ...) and can take two
3003 /// optional constant int args.
3004 bool BuiltinPrefetch(CallExpr *TheCall);
3005
3006 /// Handle __builtin_alloca_with_align. This is declared
3007 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3008 /// than 8.
3009 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
3010
3011 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
3012 bool BuiltinArithmeticFence(CallExpr *TheCall);
3013
3014 /// BuiltinAssume - Handle __assume (MS Extension).
3015 /// __assume does not evaluate its arguments, and should warn if its argument
3016 /// has side effects.
3017 bool BuiltinAssume(CallExpr *TheCall);
3018
3019 /// Handle __builtin_assume_aligned. This is declared
3020 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3021 bool BuiltinAssumeAligned(CallExpr *TheCall);
3022
3023 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3024 /// This checks that the target supports __builtin_longjmp and
3025 /// that val is a constant 1.
3026 bool BuiltinLongjmp(CallExpr *TheCall);
3027
3028 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3029 /// This checks that the target supports __builtin_setjmp.
3030 bool BuiltinSetjmp(CallExpr *TheCall);
3031
3032 /// We have a call to a function like __sync_fetch_and_add, which is an
3033 /// overloaded function based on the pointer type of its first argument.
3034 /// The main BuildCallExpr routines have already promoted the types of
3035 /// arguments because all of these calls are prototyped as void(...).
3036 ///
3037 /// This function goes through and does final semantic checking for these
3038 /// builtins, as well as generating any warnings.
3039 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
3040
3041 /// BuiltinNontemporalOverloaded - We have a call to
3042 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3043 /// overloaded function based on the pointer type of its last argument.
3044 ///
3045 /// This function goes through and does final semantic checking for these
3046 /// builtins.
3047 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
3048 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
3049 AtomicExpr::AtomicOp Op);
3050
3051 /// \param FPOnly restricts the arguments to floating-point types.
3052 bool BuiltinElementwiseMath(CallExpr *TheCall,
3053 EltwiseBuiltinArgTyRestriction ArgTyRestr =
3054 EltwiseBuiltinArgTyRestriction::None);
3055 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
3056
3057 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
3058
3059 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
3060 BuiltinCountedByRefKind K);
3061 bool BuiltinCountedByRef(CallExpr *TheCall);
3062
3063 // Matrix builtin handling.
3064 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3065 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3066 ExprResult CallResult);
3067 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3068 ExprResult CallResult);
3069
3070 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3071 /// functions) for correct use of format strings.
3072 /// Returns true if a format string has been fully checked.
3073 bool CheckFormatArguments(const FormatAttr *Format,
3074 ArrayRef<const Expr *> Args, bool IsCXXMember,
3075 VariadicCallType CallType, SourceLocation Loc,
3076 SourceRange Range,
3077 llvm::SmallBitVector &CheckedVarArgs);
3078 bool CheckFormatString(const FormatMatchesAttr *Format,
3079 ArrayRef<const Expr *> Args, bool IsCXXMember,
3080 VariadicCallType CallType, SourceLocation Loc,
3081 SourceRange Range,
3082 llvm::SmallBitVector &CheckedVarArgs);
3083 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3084 FormatArgumentPassingKind FAPK,
3085 StringLiteral *ReferenceFormatString,
3086 unsigned format_idx, unsigned firstDataArg,
3087 FormatStringType Type, VariadicCallType CallType,
3088 SourceLocation Loc, SourceRange range,
3089 llvm::SmallBitVector &CheckedVarArgs);
3090
3091 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3092
3093 /// Warn when using the wrong abs() function.
3094 void CheckAbsoluteValueFunction(const CallExpr *Call,
3095 const FunctionDecl *FDecl);
3096
3097 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3098
3099 /// Check for dangerous or invalid arguments to memset().
3100 ///
3101 /// This issues warnings on known problematic, dangerous or unspecified
3102 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3103 /// function calls.
3104 ///
3105 /// \param Call The call expression to diagnose.
3106 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3107 IdentifierInfo *FnName);
3108
3109 bool CheckSizeofMemaccessArgument(const Expr *SizeOfArg, const Expr *Dest,
3110 IdentifierInfo *FnName);
3111 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3112 // be the size of the source, instead of the destination.
3113 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3114
3115 // Warn on anti-patterns as the 'size' argument to strncat.
3116 // The correct size argument should look like following:
3117 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3118 void CheckStrncatArguments(const CallExpr *Call,
3119 const IdentifierInfo *FnName);
3120
3121 /// Alerts the user that they are attempting to free a non-malloc'd object.
3122 void CheckFreeArguments(const CallExpr *E);
3123
3124 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3125 SourceLocation ReturnLoc, bool isObjCMethod = false,
3126 const AttrVec *Attrs = nullptr,
3127 const FunctionDecl *FD = nullptr);
3128
3129 /// Diagnoses "dangerous" implicit conversions within the given
3130 /// expression (which is a full expression). Implements -Wconversion
3131 /// and -Wsign-compare.
3132 ///
3133 /// \param CC the "context" location of the implicit conversion, i.e.
3134 /// the most location of the syntactic entity requiring the implicit
3135 /// conversion
3136 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3137
3138 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3139 /// Input argument E is a logical expression.
3140 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
3141
3142 /// Diagnose when expression is an integer constant expression and its
3143 /// evaluation results in integer overflow
3144 void CheckForIntOverflow(const Expr *E);
3145 void CheckUnsequencedOperations(const Expr *E);
3146
3147 /// Perform semantic checks on a completed expression. This will either
3148 /// be a full-expression or a default argument expression.
3149 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3150 bool IsConstexpr = false);
3151
3152 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3153 Expr *Init);
3154
3155 /// A map from magic value to type information.
3156 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3157 TypeTagForDatatypeMagicValues;
3158
3159 /// Peform checks on a call of a function with argument_with_type_tag
3160 /// or pointer_with_type_tag attributes.
3161 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3162 const ArrayRef<const Expr *> ExprArgs,
3163 SourceLocation CallSiteLoc);
3164
3165 /// Check if we are taking the address of a packed field
3166 /// as this may be a problem if the pointer value is dereferenced.
3167 void CheckAddressOfPackedMember(Expr *rhs);
3168
3169 /// Helper class that collects misaligned member designations and
3170 /// their location info for delayed diagnostics.
3171 struct MisalignedMember {
3172 Expr *E;
3173 RecordDecl *RD;
3174 ValueDecl *MD;
3175 CharUnits Alignment;
3176
3177 MisalignedMember() : E(), RD(), MD() {}
3178 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3179 CharUnits Alignment)
3180 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3181 explicit MisalignedMember(Expr *E)
3182 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3183
3184 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3185 };
3186
3187 /// Adds an expression to the set of gathered misaligned members.
3188 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3189 CharUnits Alignment);
3190 ///@}
3191
3192 //
3193 //
3194 // -------------------------------------------------------------------------
3195 //
3196 //
3197
3198 /// \name C++ Coroutines
3199 /// Implementations are in SemaCoroutine.cpp
3200 ///@{
3201
3202public:
3203 /// The C++ "std::coroutine_traits" template, which is defined in
3204 /// \<coroutine_traits>
3205 ClassTemplateDecl *StdCoroutineTraitsCache;
3206
3207 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
3208 StringRef Keyword);
3209 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3210 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3211 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
3212
3213 ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
3214 ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
3215 UnresolvedLookupExpr *Lookup);
3216 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3217 Expr *Awaiter, bool IsImplicit = false);
3218 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3219 UnresolvedLookupExpr *Lookup);
3220 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
3221 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
3222 bool IsImplicit = false);
3223 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
3224 bool buildCoroutineParameterMoves(SourceLocation Loc);
3225 VarDecl *buildCoroutinePromise(SourceLocation Loc);
3226 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
3227
3228 // As a clang extension, enforces that a non-coroutine function must be marked
3229 // with [[clang::coro_wrapper]] if it returns a type marked with
3230 // [[clang::coro_return_type]].
3231 // Expects that FD is not a coroutine.
3232 void CheckCoroutineWrapper(FunctionDecl *FD);
3233 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3234 /// namespace. The namespace found is recorded in Namespace.
3235 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
3236 SourceLocation FuncLoc);
3237 /// Check that the expression co_await promise.final_suspend() shall not be
3238 /// potentially-throwing.
3239 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3240
3241 ///@}
3242
3243 //
3244 //
3245 // -------------------------------------------------------------------------
3246 //
3247 //
3248
3249 /// \name C++ Scope Specifiers
3250 /// Implementations are in SemaCXXScopeSpec.cpp
3251 ///@{
3252
3253public:
3254 // Marks SS invalid if it represents an incomplete type.
3255 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3256 // Complete an enum decl, maybe without a scope spec.
3257 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
3258 CXXScopeSpec *SS = nullptr);
3259
3260 /// Compute the DeclContext that is associated with the given type.
3261 ///
3262 /// \param T the type for which we are attempting to find a DeclContext.
3263 ///
3264 /// \returns the declaration context represented by the type T,
3265 /// or NULL if the declaration context cannot be computed (e.g., because it is
3266 /// dependent and not the current instantiation).
3267 DeclContext *computeDeclContext(QualType T);
3268
3269 /// Compute the DeclContext that is associated with the given
3270 /// scope specifier.
3271 ///
3272 /// \param SS the C++ scope specifier as it appears in the source
3273 ///
3274 /// \param EnteringContext when true, we will be entering the context of
3275 /// this scope specifier, so we can retrieve the declaration context of a
3276 /// class template or class template partial specialization even if it is
3277 /// not the current instantiation.
3278 ///
3279 /// \returns the declaration context represented by the scope specifier @p SS,
3280 /// or NULL if the declaration context cannot be computed (e.g., because it is
3281 /// dependent and not the current instantiation).
3282 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3283 bool EnteringContext = false);
3284 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3285
3286 /// If the given nested name specifier refers to the current
3287 /// instantiation, return the declaration that corresponds to that
3288 /// current instantiation (C++0x [temp.dep.type]p1).
3289 ///
3290 /// \param NNS a dependent nested name specifier.
3291 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier NNS);
3292
3293 /// The parser has parsed a global nested-name-specifier '::'.
3294 ///
3295 /// \param CCLoc The location of the '::'.
3296 ///
3297 /// \param SS The nested-name-specifier, which will be updated in-place
3298 /// to reflect the parsed nested-name-specifier.
3299 ///
3300 /// \returns true if an error occurred, false otherwise.
3301 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
3302
3303 /// The parser has parsed a '__super' nested-name-specifier.
3304 ///
3305 /// \param SuperLoc The location of the '__super' keyword.
3306 ///
3307 /// \param ColonColonLoc The location of the '::'.
3308 ///
3309 /// \param SS The nested-name-specifier, which will be updated in-place
3310 /// to reflect the parsed nested-name-specifier.
3311 ///
3312 /// \returns true if an error occurred, false otherwise.
3313 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
3314 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3315
3316 /// Determines whether the given declaration is an valid acceptable
3317 /// result for name lookup of a nested-name-specifier.
3318 /// \param SD Declaration checked for nested-name-specifier.
3319 /// \param IsExtension If not null and the declaration is accepted as an
3320 /// extension, the pointed variable is assigned true.
3321 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
3322 bool *CanCorrect = nullptr);
3323
3324 /// If the given nested-name-specifier begins with a bare identifier
3325 /// (e.g., Base::), perform name lookup for that identifier as a
3326 /// nested-name-specifier within the given scope, and return the result of
3327 /// that name lookup.
3328 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier NNS);
3329
3330 /// Keeps information about an identifier in a nested-name-spec.
3331 ///
3332 struct NestedNameSpecInfo {
3333 /// The type of the object, if we're parsing nested-name-specifier in
3334 /// a member access expression.
3335 ParsedType ObjectType;
3336
3337 /// The identifier preceding the '::'.
3338 IdentifierInfo *Identifier;
3339
3340 /// The location of the identifier.
3341 SourceLocation IdentifierLoc;
3342
3343 /// The location of the '::'.
3344 SourceLocation CCLoc;
3345
3346 /// Creates info object for the most typical case.
3347 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3348 SourceLocation ColonColonLoc,
3349 ParsedType ObjectType = ParsedType())
3350 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
3351 CCLoc(ColonColonLoc) {}
3352
3353 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3354 SourceLocation ColonColonLoc, QualType ObjectType)
3355 : ObjectType(ParsedType::make(P: ObjectType)), Identifier(II),
3356 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3357 };
3358
3359 /// Build a new nested-name-specifier for "identifier::", as described
3360 /// by ActOnCXXNestedNameSpecifier.
3361 ///
3362 /// \param S Scope in which the nested-name-specifier occurs.
3363 /// \param IdInfo Parser information about an identifier in the
3364 /// nested-name-spec.
3365 /// \param EnteringContext If true, enter the context specified by the
3366 /// nested-name-specifier.
3367 /// \param SS Optional nested name specifier preceding the identifier.
3368 /// \param ScopeLookupResult Provides the result of name lookup within the
3369 /// scope of the nested-name-specifier that was computed at template
3370 /// definition time.
3371 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3372 /// error recovery and what kind of recovery is performed.
3373 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3374 /// are allowed. The bool value pointed by this parameter is set to
3375 /// 'true' if the identifier is treated as if it was followed by ':',
3376 /// not '::'.
3377 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3378 ///
3379 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3380 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3381 /// the result of name lookup within the scope of the nested-name-specifier
3382 /// that was computed at template definition time.
3383 ///
3384 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3385 /// recovery. This means that it should not emit diagnostics, it should
3386 /// just return true on failure. It also means it should only return a valid
3387 /// scope if it *knows* that the result is correct. It should not return in a
3388 /// dependent context, for example. Nor will it extend \p SS with the scope
3389 /// specifier.
3390 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3391 bool EnteringContext, CXXScopeSpec &SS,
3392 NamedDecl *ScopeLookupResult,
3393 bool ErrorRecoveryLookup,
3394 bool *IsCorrectedToColon = nullptr,
3395 bool OnlyNamespace = false);
3396
3397 /// The parser has parsed a nested-name-specifier 'identifier::'.
3398 ///
3399 /// \param S The scope in which this nested-name-specifier occurs.
3400 ///
3401 /// \param IdInfo Parser information about an identifier in the
3402 /// nested-name-spec.
3403 ///
3404 /// \param EnteringContext Whether we're entering the context nominated by
3405 /// this nested-name-specifier.
3406 ///
3407 /// \param SS The nested-name-specifier, which is both an input
3408 /// parameter (the nested-name-specifier before this type) and an
3409 /// output parameter (containing the full nested-name-specifier,
3410 /// including this new type).
3411 ///
3412 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3413 /// are allowed. The bool value pointed by this parameter is set to 'true'
3414 /// if the identifier is treated as if it was followed by ':', not '::'.
3415 ///
3416 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3417 ///
3418 /// \returns true if an error occurred, false otherwise.
3419 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3420 bool EnteringContext, CXXScopeSpec &SS,
3421 bool *IsCorrectedToColon = nullptr,
3422 bool OnlyNamespace = false);
3423
3424 /// The parser has parsed a nested-name-specifier
3425 /// 'template[opt] template-name < template-args >::'.
3426 ///
3427 /// \param S The scope in which this nested-name-specifier occurs.
3428 ///
3429 /// \param SS The nested-name-specifier, which is both an input
3430 /// parameter (the nested-name-specifier before this type) and an
3431 /// output parameter (containing the full nested-name-specifier,
3432 /// including this new type).
3433 ///
3434 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3435 /// \param TemplateName the template name.
3436 /// \param TemplateNameLoc The location of the template name.
3437 /// \param LAngleLoc The location of the opening angle bracket ('<').
3438 /// \param TemplateArgs The template arguments.
3439 /// \param RAngleLoc The location of the closing angle bracket ('>').
3440 /// \param CCLoc The location of the '::'.
3441 ///
3442 /// \param EnteringContext Whether we're entering the context of the
3443 /// nested-name-specifier.
3444 ///
3445 ///
3446 /// \returns true if an error occurred, false otherwise.
3447 bool ActOnCXXNestedNameSpecifier(
3448 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3449 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3450 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3451 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3452
3453 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS,
3454 SourceLocation ColonColonLoc);
3455
3456 bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS,
3457 const DeclSpec &DS,
3458 SourceLocation ColonColonLoc,
3459 QualType Type);
3460
3461 /// IsInvalidUnlessNestedName - This method is used for error recovery
3462 /// purposes to determine whether the specified identifier is only valid as
3463 /// a nested name specifier, for example a namespace name. It is
3464 /// conservatively correct to always return false from this method.
3465 ///
3466 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3467 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3468 NestedNameSpecInfo &IdInfo,
3469 bool EnteringContext);
3470
3471 /// Given a C++ nested-name-specifier, produce an annotation value
3472 /// that the parser can use later to reconstruct the given
3473 /// nested-name-specifier.
3474 ///
3475 /// \param SS A nested-name-specifier.
3476 ///
3477 /// \returns A pointer containing all of the information in the
3478 /// nested-name-specifier \p SS.
3479 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3480
3481 /// Given an annotation pointer for a nested-name-specifier, restore
3482 /// the nested-name-specifier structure.
3483 ///
3484 /// \param Annotation The annotation pointer, produced by
3485 /// \c SaveNestedNameSpecifierAnnotation().
3486 ///
3487 /// \param AnnotationRange The source range corresponding to the annotation.
3488 ///
3489 /// \param SS The nested-name-specifier that will be updated with the contents
3490 /// of the annotation pointer.
3491 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3492 SourceRange AnnotationRange,
3493 CXXScopeSpec &SS);
3494
3495 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3496
3497 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3498 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3499 /// After this method is called, according to [C++ 3.4.3p3], names should be
3500 /// looked up in the declarator-id's scope, until the declarator is parsed and
3501 /// ActOnCXXExitDeclaratorScope is called.
3502 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3503 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3504
3505 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3506 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3507 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3508 /// Used to indicate that names should revert to being looked up in the
3509 /// defining scope.
3510 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3511
3512 ///@}
3513
3514 //
3515 //
3516 // -------------------------------------------------------------------------
3517 //
3518 //
3519
3520 /// \name Declarations
3521 /// Implementations are in SemaDecl.cpp
3522 ///@{
3523
3524public:
3525 IdentifierResolver IdResolver;
3526
3527 /// The index of the first InventedParameterInfo that refers to the current
3528 /// context.
3529 unsigned InventedParameterInfosStart = 0;
3530
3531 /// A RAII object to temporarily push a declaration context.
3532 class ContextRAII {
3533 private:
3534 Sema &S;
3535 DeclContext *SavedContext;
3536 ProcessingContextState SavedContextState;
3537 QualType SavedCXXThisTypeOverride;
3538 unsigned SavedFunctionScopesStart;
3539 unsigned SavedInventedParameterInfosStart;
3540
3541 public:
3542 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3543 : S(S), SavedContext(S.CurContext),
3544 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3545 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3546 SavedFunctionScopesStart(S.FunctionScopesStart),
3547 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3548 assert(ContextToPush && "pushing null context");
3549 S.CurContext = ContextToPush;
3550 if (NewThisContext)
3551 S.CXXThisTypeOverride = QualType();
3552 // Any saved FunctionScopes do not refer to this context.
3553 S.FunctionScopesStart = S.FunctionScopes.size();
3554 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3555 }
3556
3557 void pop() {
3558 if (!SavedContext)
3559 return;
3560 S.CurContext = SavedContext;
3561 S.DelayedDiagnostics.popUndelayed(state: SavedContextState);
3562 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3563 S.FunctionScopesStart = SavedFunctionScopesStart;
3564 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3565 SavedContext = nullptr;
3566 }
3567
3568 ~ContextRAII() { pop(); }
3569 ContextRAII(const ContextRAII &) = delete;
3570 ContextRAII &operator=(const ContextRAII &) = delete;
3571 };
3572
3573 void DiagnoseInvalidJumps(Stmt *Body);
3574
3575 /// The function definitions which were renamed as part of typo-correction
3576 /// to match their respective declarations. We want to keep track of them
3577 /// to ensure that we don't emit a "redefinition" error if we encounter a
3578 /// correctly named definition after the renamed definition.
3579 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
3580
3581 /// A cache of the flags available in enumerations with the flag_enum
3582 /// attribute.
3583 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3584
3585 /// A cache of enumerator values for enums checked by -Wassign-enum.
3586 llvm::DenseMap<const EnumDecl *, llvm::SmallVector<llvm::APSInt>>
3587 AssignEnumCache;
3588
3589 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3590 /// declared. Rare. May alias another identifier, declared or undeclared.
3591 ///
3592 /// For aliases, the target identifier is used as a key for eventual
3593 /// processing when the target is declared. For the single-identifier form,
3594 /// the sole identifier is used as the key. Each entry is a `SetVector`
3595 /// (ordered by parse order) of aliases (identified by the alias name) in case
3596 /// of multiple aliases to the same undeclared identifier.
3597 llvm::MapVector<
3598 IdentifierInfo *,
3599 llvm::SetVector<
3600 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
3601 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3602 WeakUndeclaredIdentifiers;
3603
3604 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3605 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3606 /// to define functions that occur in multiple standards to call the version
3607 /// in the currently selected standard.
3608 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>
3609 ExtnameUndeclaredIdentifiers;
3610
3611 /// Set containing all typedefs that are likely unused.
3612 llvm::SmallPtrSet<const TypedefNameDecl *, 4>
3613 UnusedLocalTypedefNameCandidates;
3614
3615 /// Store UnusedLocalTypedefNameCandidates in \p Sorted in a deterministic
3616 /// order.
3617 void getSortedUnusedLocalTypedefNameCandidates(
3618 SmallVectorImpl<const TypedefNameDecl *> &Sorted) const;
3619
3620 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
3621 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
3622 UnusedFileScopedDeclsType;
3623
3624 /// The set of file scoped decls seen so far that have not been used
3625 /// and must warn if not used. Only contains the first declaration.
3626 UnusedFileScopedDeclsType UnusedFileScopedDecls;
3627
3628 typedef LazyVector<VarDecl *, ExternalSemaSource,
3629 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
3630 TentativeDefinitionsType;
3631
3632 /// All the tentative definitions encountered in the TU.
3633 TentativeDefinitionsType TentativeDefinitions;
3634
3635 /// All the external declarations encoutered and used in the TU.
3636 SmallVector<DeclaratorDecl *, 4> ExternalDeclarations;
3637
3638 /// Generally null except when we temporarily switch decl contexts,
3639 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3640 DeclContext *OriginalLexicalContext;
3641
3642 /// Is the module scope we are in a C++ Header Unit?
3643 bool currentModuleIsHeaderUnit() const {
3644 return ModuleScopes.empty() ? false
3645 : ModuleScopes.back().Module->isHeaderUnit();
3646 }
3647
3648 /// Get the module owning an entity.
3649 Module *getOwningModule(const Decl *Entity) {
3650 return Entity->getOwningModule();
3651 }
3652
3653 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3654
3655 enum class DiagCtorKind { None, Implicit, Typename };
3656 /// Returns the TypeDeclType for the given type declaration,
3657 /// as ASTContext::getTypeDeclType would, but
3658 /// performs the required semantic checks for name lookup of said entity.
3659 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3660 SourceLocation NameLoc);
3661
3662 /// If the identifier refers to a type name within this scope,
3663 /// return the declaration of that type.
3664 ///
3665 /// This routine performs ordinary name lookup of the identifier II
3666 /// within the given scope, with optional C++ scope specifier SS, to
3667 /// determine whether the name refers to a type. If so, returns an
3668 /// opaque pointer (actually a QualType) corresponding to that
3669 /// type. Otherwise, returns NULL.
3670 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
3671 Scope *S, CXXScopeSpec *SS = nullptr,
3672 bool isClassName = false, bool HasTrailingDot = false,
3673 ParsedType ObjectType = nullptr,
3674 bool IsCtorOrDtorName = false,
3675 bool WantNontrivialTypeSourceInfo = false,
3676 bool IsClassTemplateDeductionContext = true,
3677 ImplicitTypenameContext AllowImplicitTypename =
3678 ImplicitTypenameContext::No,
3679 IdentifierInfo **CorrectedII = nullptr);
3680
3681 /// isTagName() - This method is called *for error recovery purposes only*
3682 /// to determine if the specified name is a valid tag name ("struct foo"). If
3683 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3684 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3685 /// diagnose cases in C where the user forgot to specify the tag.
3686 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
3687
3688 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3689 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3690 /// then downgrade the missing typename error to a warning.
3691 /// This is needed for MSVC compatibility; Example:
3692 /// @code
3693 /// template<class T> class A {
3694 /// public:
3695 /// typedef int TYPE;
3696 /// };
3697 /// template<class T> class B : public A<T> {
3698 /// public:
3699 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3700 /// };
3701 /// @endcode
3702 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3703 void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc,
3704 Scope *S, CXXScopeSpec *SS,
3705 ParsedType &SuggestedType,
3706 bool IsTemplateName = false);
3707
3708 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3709 /// type name has failed in a dependent context. In these situations, we
3710 /// automatically form a DependentTypeName that will retry lookup in a related
3711 /// scope during instantiation.
3712 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
3713 SourceLocation NameLoc,
3714 bool IsTemplateTypeArg);
3715
3716 class NameClassification {
3717 NameClassificationKind Kind;
3718 union {
3719 ExprResult Expr;
3720 NamedDecl *NonTypeDecl;
3721 TemplateName Template;
3722 ParsedType Type;
3723 };
3724
3725 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3726
3727 public:
3728 NameClassification(ParsedType Type)
3729 : Kind(NameClassificationKind::Type), Type(Type) {}
3730
3731 NameClassification(const IdentifierInfo *Keyword)
3732 : Kind(NameClassificationKind::Keyword) {}
3733
3734 static NameClassification Error() {
3735 return NameClassification(NameClassificationKind::Error);
3736 }
3737
3738 static NameClassification Unknown() {
3739 return NameClassification(NameClassificationKind::Unknown);
3740 }
3741
3742 static NameClassification OverloadSet(ExprResult E) {
3743 NameClassification Result(NameClassificationKind::OverloadSet);
3744 Result.Expr = E;
3745 return Result;
3746 }
3747
3748 static NameClassification NonType(NamedDecl *D) {
3749 NameClassification Result(NameClassificationKind::NonType);
3750 Result.NonTypeDecl = D;
3751 return Result;
3752 }
3753
3754 static NameClassification UndeclaredNonType() {
3755 return NameClassification(NameClassificationKind::UndeclaredNonType);
3756 }
3757
3758 static NameClassification DependentNonType() {
3759 return NameClassification(NameClassificationKind::DependentNonType);
3760 }
3761
3762 static NameClassification TypeTemplate(TemplateName Name) {
3763 NameClassification Result(NameClassificationKind::TypeTemplate);
3764 Result.Template = Name;
3765 return Result;
3766 }
3767
3768 static NameClassification VarTemplate(TemplateName Name) {
3769 NameClassification Result(NameClassificationKind::VarTemplate);
3770 Result.Template = Name;
3771 return Result;
3772 }
3773
3774 static NameClassification FunctionTemplate(TemplateName Name) {
3775 NameClassification Result(NameClassificationKind::FunctionTemplate);
3776 Result.Template = Name;
3777 return Result;
3778 }
3779
3780 static NameClassification Concept(TemplateName Name) {
3781 NameClassification Result(NameClassificationKind::Concept);
3782 Result.Template = Name;
3783 return Result;
3784 }
3785
3786 static NameClassification UndeclaredTemplate(TemplateName Name) {
3787 NameClassification Result(NameClassificationKind::UndeclaredTemplate);
3788 Result.Template = Name;
3789 return Result;
3790 }
3791
3792 NameClassificationKind getKind() const { return Kind; }
3793
3794 ExprResult getExpression() const {
3795 assert(Kind == NameClassificationKind::OverloadSet);
3796 return Expr;
3797 }
3798
3799 ParsedType getType() const {
3800 assert(Kind == NameClassificationKind::Type);
3801 return Type;
3802 }
3803
3804 NamedDecl *getNonTypeDecl() const {
3805 assert(Kind == NameClassificationKind::NonType);
3806 return NonTypeDecl;
3807 }
3808
3809 TemplateName getTemplateName() const {
3810 assert(Kind == NameClassificationKind::TypeTemplate ||
3811 Kind == NameClassificationKind::FunctionTemplate ||
3812 Kind == NameClassificationKind::VarTemplate ||
3813 Kind == NameClassificationKind::Concept ||
3814 Kind == NameClassificationKind::UndeclaredTemplate);
3815 return Template;
3816 }
3817
3818 TemplateNameKind getTemplateNameKind() const {
3819 switch (Kind) {
3820 case NameClassificationKind::TypeTemplate:
3821 return TNK_Type_template;
3822 case NameClassificationKind::FunctionTemplate:
3823 return TNK_Function_template;
3824 case NameClassificationKind::VarTemplate:
3825 return TNK_Var_template;
3826 case NameClassificationKind::Concept:
3827 return TNK_Concept_template;
3828 case NameClassificationKind::UndeclaredTemplate:
3829 return TNK_Undeclared_template;
3830 default:
3831 llvm_unreachable("unsupported name classification.");
3832 }
3833 }
3834 };
3835
3836 /// Perform name lookup on the given name, classifying it based on
3837 /// the results of name lookup and the following token.
3838 ///
3839 /// This routine is used by the parser to resolve identifiers and help direct
3840 /// parsing. When the identifier cannot be found, this routine will attempt
3841 /// to correct the typo and classify based on the resulting name.
3842 ///
3843 /// \param S The scope in which we're performing name lookup.
3844 ///
3845 /// \param SS The nested-name-specifier that precedes the name.
3846 ///
3847 /// \param Name The identifier. If typo correction finds an alternative name,
3848 /// this pointer parameter will be updated accordingly.
3849 ///
3850 /// \param NameLoc The location of the identifier.
3851 ///
3852 /// \param NextToken The token following the identifier. Used to help
3853 /// disambiguate the name.
3854 ///
3855 /// \param CCC The correction callback, if typo correction is desired.
3856 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3857 IdentifierInfo *&Name, SourceLocation NameLoc,
3858 const Token &NextToken,
3859 CorrectionCandidateCallback *CCC = nullptr);
3860
3861 /// Act on the result of classifying a name as an undeclared (ADL-only)
3862 /// non-type declaration.
3863 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
3864 SourceLocation NameLoc);
3865 /// Act on the result of classifying a name as an undeclared member of a
3866 /// dependent base class.
3867 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
3868 IdentifierInfo *Name,
3869 SourceLocation NameLoc,
3870 bool IsAddressOfOperand);
3871 /// Act on the result of classifying a name as a specific non-type
3872 /// declaration.
3873 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
3874 NamedDecl *Found,
3875 SourceLocation NameLoc,
3876 const Token &NextToken);
3877 /// Act on the result of classifying a name as an overload set.
3878 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
3879
3880 /// Describes the detailed kind of a template name. Used in diagnostics.
3881 enum class TemplateNameKindForDiagnostics {
3882 ClassTemplate,
3883 FunctionTemplate,
3884 VarTemplate,
3885 AliasTemplate,
3886 TemplateTemplateParam,
3887 Concept,
3888 DependentTemplate
3889 };
3890 TemplateNameKindForDiagnostics
3891 getTemplateNameKindForDiagnostics(TemplateName Name);
3892
3893 /// Determine whether it's plausible that E was intended to be a
3894 /// template-name.
3895 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
3896 if (!getLangOpts().CPlusPlus || E.isInvalid())
3897 return false;
3898 Dependent = false;
3899 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E.get()))
3900 return !DRE->hasExplicitTemplateArgs();
3901 if (auto *ME = dyn_cast<MemberExpr>(Val: E.get()))
3902 return !ME->hasExplicitTemplateArgs();
3903 Dependent = true;
3904 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(Val: E.get()))
3905 return !DSDRE->hasExplicitTemplateArgs();
3906 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(Val: E.get()))
3907 return !DSME->hasExplicitTemplateArgs();
3908 // Any additional cases recognized here should also be handled by
3909 // diagnoseExprIntendedAsTemplateName.
3910 return false;
3911 }
3912
3913 void warnOnReservedIdentifier(const NamedDecl *D);
3914 void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D);
3915
3916 void ProcessPragmaExport(DeclaratorDecl *newDecl);
3917
3918 Decl *ActOnDeclarator(Scope *S, Declarator &D);
3919
3920 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
3921 MultiTemplateParamsArg TemplateParameterLists);
3922
3923 /// Attempt to fold a variable-sized type to a constant-sized type, returning
3924 /// true if we were successful.
3925 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T,
3926 SourceLocation Loc,
3927 unsigned FailedFoldDiagID);
3928
3929 /// Register the given locally-scoped extern "C" declaration so
3930 /// that it can be found later for redeclarations. We include any extern "C"
3931 /// declaration that is not visible in the translation unit here, not just
3932 /// function-scope declarations.
3933 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
3934
3935 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3936 /// If T is the name of a class, then each of the following shall have a
3937 /// name different from T:
3938 /// - every static data member of class T;
3939 /// - every member function of class T
3940 /// - every member of class T that is itself a type;
3941 /// \returns true if the declaration name violates these rules.
3942 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
3943
3944 /// Diagnose a declaration whose declarator-id has the given
3945 /// nested-name-specifier.
3946 ///
3947 /// \param SS The nested-name-specifier of the declarator-id.
3948 ///
3949 /// \param DC The declaration context to which the nested-name-specifier
3950 /// resolves.
3951 ///
3952 /// \param Name The name of the entity being declared.
3953 ///
3954 /// \param Loc The location of the name of the entity being declared.
3955 ///
3956 /// \param IsMemberSpecialization Whether we are declaring a member
3957 /// specialization.
3958 ///
3959 /// \param TemplateId The template-id, if any.
3960 ///
3961 /// \returns true if we cannot safely recover from this error, false
3962 /// otherwise.
3963 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3964 DeclarationName Name, SourceLocation Loc,
3965 TemplateIdAnnotation *TemplateId,
3966 bool IsMemberSpecialization);
3967
3968 bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range);
3969
3970 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
3971
3972 bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind,
3973 unsigned &IntVal);
3974
3975 /// Diagnose function specifiers on a declaration of an identifier that
3976 /// does not identify a function.
3977 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
3978
3979 /// Return the declaration shadowed by the given typedef \p D, or null
3980 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3981 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
3982 const LookupResult &R);
3983
3984 /// Return the declaration shadowed by the given variable \p D, or null
3985 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3986 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
3987
3988 /// Return the declaration shadowed by the given variable \p D, or null
3989 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3990 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
3991 const LookupResult &R);
3992 /// Diagnose variable or built-in function shadowing. Implements
3993 /// -Wshadow.
3994 ///
3995 /// This method is called whenever a VarDecl is added to a "useful"
3996 /// scope.
3997 ///
3998 /// \param ShadowedDecl the declaration that is shadowed by the given variable
3999 /// \param R the lookup of the name
4000 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
4001 const LookupResult &R);
4002
4003 /// Check -Wshadow without the advantage of a previous lookup.
4004 void CheckShadow(Scope *S, VarDecl *D);
4005
4006 /// Warn if 'E', which is an expression that is about to be modified, refers
4007 /// to a shadowing declaration.
4008 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
4009
4010 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
4011 /// when these variables are captured by the lambda.
4012 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
4013
4014 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
4015 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4016 TypedefNameDecl *NewTD);
4017 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
4018 NamedDecl *ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4019 TypeSourceInfo *TInfo,
4020 LookupResult &Previous);
4021
4022 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4023 /// declares a typedef-name, either using the 'typedef' type specifier or via
4024 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4025 NamedDecl *ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D,
4026 LookupResult &Previous, bool &Redeclaration);
4027 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4028 TypeSourceInfo *TInfo,
4029 LookupResult &Previous,
4030 MultiTemplateParamsArg TemplateParamLists,
4031 bool &AddToScope,
4032 ArrayRef<BindingDecl *> Bindings = {});
4033
4034private:
4035 // Perform a check on an AsmLabel to verify its consistency and emit
4036 // diagnostics in case of an error.
4037 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
4038 TypeSourceInfo *TInfo, VarDecl *);
4039
4040public:
4041 /// Perform semantic checking on a newly-created variable
4042 /// declaration.
4043 ///
4044 /// This routine performs all of the type-checking required for a
4045 /// variable declaration once it has been built. It is used both to
4046 /// check variables after they have been parsed and their declarators
4047 /// have been translated into a declaration, and to check variables
4048 /// that have been instantiated from a template.
4049 ///
4050 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4051 ///
4052 /// Returns true if the variable declaration is a redeclaration.
4053 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
4054 void CheckVariableDeclarationType(VarDecl *NewVD);
4055 void CheckCompleteVariableDeclaration(VarDecl *VD);
4056
4057 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4058 TypeSourceInfo *TInfo,
4059 LookupResult &Previous,
4060 MultiTemplateParamsArg TemplateParamLists,
4061 bool &AddToScope);
4062
4063 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4064 /// and if so, check that it's a valid override and remember it.
4065 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
4066
4067 /// Perform semantic checking of a new function declaration.
4068 ///
4069 /// Performs semantic analysis of the new function declaration
4070 /// NewFD. This routine performs all semantic checking that does not
4071 /// require the actual declarator involved in the declaration, and is
4072 /// used both for the declaration of functions as they are parsed
4073 /// (called via ActOnDeclarator) and for the declaration of functions
4074 /// that have been instantiated via C++ template instantiation (called
4075 /// via InstantiateDecl).
4076 ///
4077 /// \param IsMemberSpecialization whether this new function declaration is
4078 /// a member specialization (that replaces any definition provided by the
4079 /// previous declaration).
4080 ///
4081 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4082 ///
4083 /// \returns true if the function declaration is a redeclaration.
4084 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4085 LookupResult &Previous,
4086 bool IsMemberSpecialization, bool DeclIsDefn);
4087
4088 /// Checks if the new declaration declared in dependent context must be
4089 /// put in the same redeclaration chain as the specified declaration.
4090 ///
4091 /// \param D Declaration that is checked.
4092 /// \param PrevDecl Previous declaration found with proper lookup method for
4093 /// the same declaration name.
4094 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4095 /// belongs to.
4096 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4097
4098 /// Determines if we can perform a correct type check for \p D as a
4099 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4100 /// best-effort check.
4101 ///
4102 /// \param NewD The new declaration.
4103 /// \param OldD The old declaration.
4104 /// \param NewT The portion of the type of the new declaration to check.
4105 /// \param OldT The portion of the type of the old declaration to check.
4106 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4107 QualType NewT, QualType OldT);
4108 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4109 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4110
4111 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4112 /// containing class. Otherwise it will return implicit SectionAttr if the
4113 /// function is a definition and there is an active value on CodeSegStack
4114 /// (from the current #pragma code-seg value).
4115 ///
4116 /// \param FD Function being declared.
4117 /// \param IsDefinition Whether it is a definition or just a declaration.
4118 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4119 /// nullptr if no attribute should be added.
4120 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4121 bool IsDefinition);
4122
4123 /// Common checks for a parameter-declaration that should apply to both
4124 /// function parameters and non-type template parameters.
4125 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4126
4127 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4128 /// to introduce parameters into function prototype scope.
4129 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4130 SourceLocation ExplicitThisLoc = {});
4131
4132 /// Synthesizes a variable for a parameter arising from a
4133 /// typedef.
4134 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4135 QualType T);
4136 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4137 SourceLocation NameLoc,
4138 const IdentifierInfo *Name, QualType T,
4139 TypeSourceInfo *TSInfo, StorageClass SC);
4140
4141 /// Emit diagnostics if the initializer or any of its explicit or
4142 /// implicitly-generated subexpressions require copying or
4143 /// default-initializing a type that is or contains a C union type that is
4144 /// non-trivial to copy or default-initialize.
4145 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4146
4147 // These flags are passed to checkNonTrivialCUnion.
4148 enum NonTrivialCUnionKind {
4149 NTCUK_Init = 0x1,
4150 NTCUK_Destruct = 0x2,
4151 NTCUK_Copy = 0x4,
4152 };
4153
4154 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4155 /// a non-trivial C union is used in an invalid context.
4156 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
4157 NonTrivialCUnionContext UseContext,
4158 unsigned NonTrivialKind);
4159
4160 /// Certain globally-unique variables might be accidentally duplicated if
4161 /// built into multiple shared libraries with hidden visibility. This can
4162 /// cause problems if the variable is mutable, its initialization is
4163 /// effectful, or its address is taken.
4164 bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl);
4165 void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl);
4166
4167 /// AddInitializerToDecl - Adds the initializer Init to the
4168 /// declaration dcl. If DirectInit is true, this is C++ direct
4169 /// initialization rather than copy initialization.
4170 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4171 void ActOnUninitializedDecl(Decl *dcl);
4172
4173 /// ActOnInitializerError - Given that there was an error parsing an
4174 /// initializer for the given declaration, try to at least re-establish
4175 /// invariants such as whether a variable's type is either dependent or
4176 /// complete.
4177 void ActOnInitializerError(Decl *Dcl);
4178
4179 void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt);
4180 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
4181 IdentifierInfo *Ident,
4182 ParsedAttributes &Attrs);
4183
4184 /// Check if VD needs to be dllexport/dllimport due to being in a
4185 /// dllexport/import function.
4186 void CheckStaticLocalForDllExport(VarDecl *VD);
4187 void CheckThreadLocalForLargeAlignment(VarDecl *VD);
4188
4189 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4190 /// any semantic actions necessary after any initializer has been attached.
4191 void FinalizeDeclaration(Decl *D);
4192 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4193 ArrayRef<Decl *> Group);
4194
4195 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4196 /// group, performing any necessary semantic checking.
4197 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
4198
4199 /// Should be called on all declarations that might have attached
4200 /// documentation comments.
4201 void ActOnDocumentableDecl(Decl *D);
4202 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
4203
4204 enum class FnBodyKind {
4205 /// C++26 [dcl.fct.def.general]p1
4206 /// function-body:
4207 /// ctor-initializer[opt] compound-statement
4208 /// function-try-block
4209 Other,
4210 /// = default ;
4211 Default,
4212 /// deleted-function-body
4213 ///
4214 /// deleted-function-body:
4215 /// = delete ;
4216 /// = delete ( unevaluated-string ) ;
4217 Delete
4218 };
4219
4220 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4221 SourceLocation LocAfterDecls);
4222 void CheckForFunctionRedefinition(
4223 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4224 SkipBodyInfo *SkipBody = nullptr);
4225 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
4226 MultiTemplateParamsArg TemplateParamLists,
4227 SkipBodyInfo *SkipBody = nullptr,
4228 FnBodyKind BodyKind = FnBodyKind::Other);
4229 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
4230 SkipBodyInfo *SkipBody = nullptr,
4231 FnBodyKind BodyKind = FnBodyKind::Other);
4232 void applyFunctionAttributesBeforeParsingBody(Decl *FD);
4233
4234 /// Determine whether we can delay parsing the body of a function or
4235 /// function template until it is used, assuming we don't care about emitting
4236 /// code for that function.
4237 ///
4238 /// This will be \c false if we may need the body of the function in the
4239 /// middle of parsing an expression (where it's impractical to switch to
4240 /// parsing a different function), for instance, if it's constexpr in C++11
4241 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4242 bool canDelayFunctionBody(const Declarator &D);
4243
4244 /// Determine whether we can skip parsing the body of a function
4245 /// definition, assuming we don't care about analyzing its body or emitting
4246 /// code for that function.
4247 ///
4248 /// This will be \c false only if we may need the body of the function in
4249 /// order to parse the rest of the program (for instance, if it is
4250 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4251 bool canSkipFunctionBody(Decl *D);
4252
4253 /// Given the set of return statements within a function body,
4254 /// compute the variables that are subject to the named return value
4255 /// optimization.
4256 ///
4257 /// Each of the variables that is subject to the named return value
4258 /// optimization will be marked as NRVO variables in the AST, and any
4259 /// return statement that has a marked NRVO variable as its NRVO candidate can
4260 /// use the named return value optimization.
4261 ///
4262 /// This function applies a very simplistic algorithm for NRVO: if every
4263 /// return statement in the scope of a variable has the same NRVO candidate,
4264 /// that candidate is an NRVO variable.
4265 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
4266
4267 /// Performs semantic analysis at the end of a function body.
4268 ///
4269 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4270 /// releasing the associated \p FunctionScopeInfo. This is useful when
4271 /// building e.g. LambdaExprs.
4272 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body,
4273 bool IsInstantiation = false,
4274 bool RetainFunctionScopeInfo = false);
4275 Decl *ActOnSkippedFunctionBody(Decl *Decl);
4276 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
4277
4278 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4279 /// attribute for which parsing is delayed.
4280 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
4281
4282 /// Diagnose any unused parameters in the given sequence of
4283 /// ParmVarDecl pointers.
4284 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
4285
4286 /// Diagnose whether the size of parameters or return value of a
4287 /// function or obj-c method definition is pass-by-value and larger than a
4288 /// specified threshold.
4289 void
4290 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
4291 QualType ReturnTy, NamedDecl *D);
4292
4293 Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc,
4294 SourceLocation RParenLoc);
4295
4296 TopLevelStmtDecl *ActOnStartTopLevelStmtDecl(Scope *S);
4297 void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement);
4298
4299 void ActOnPopScope(SourceLocation Loc, Scope *S);
4300
4301 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4302 /// no declarator (e.g. "struct foo;") is parsed.
4303 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4304 const ParsedAttributesView &DeclAttrs,
4305 RecordDecl *&AnonRecord);
4306
4307 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4308 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4309 /// parameters to cope with template friend declarations.
4310 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4311 const ParsedAttributesView &DeclAttrs,
4312 MultiTemplateParamsArg TemplateParams,
4313 bool IsExplicitInstantiation,
4314 RecordDecl *&AnonRecord,
4315 SourceLocation EllipsisLoc = {});
4316
4317 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4318 /// anonymous structure or union. Anonymous unions are a C++ feature
4319 /// (C++ [class.union]) and a C11 feature; anonymous structures
4320 /// are a C11 feature and GNU C++ extension.
4321 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4322 RecordDecl *Record,
4323 const PrintingPolicy &Policy);
4324
4325 /// Called once it is known whether
4326 /// a tag declaration is an anonymous union or struct.
4327 void ActOnDefinedDeclarationSpecifier(Decl *D);
4328
4329 /// Emit diagnostic warnings for placeholder members.
4330 /// We can only do that after the class is fully constructed,
4331 /// as anonymous union/structs can insert placeholders
4332 /// in their parent scope (which might be a Record).
4333 void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record);
4334
4335 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4336 /// Microsoft C anonymous structure.
4337 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4338 /// Example:
4339 ///
4340 /// struct A { int a; };
4341 /// struct B { struct A; int b; };
4342 ///
4343 /// void foo() {
4344 /// B var;
4345 /// var.a = 3;
4346 /// }
4347 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4348 RecordDecl *Record);
4349
4350 /// Given a non-tag type declaration, returns an enum useful for indicating
4351 /// what kind of non-tag type this is.
4352 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4353
4354 /// Determine whether a tag with a given kind is acceptable
4355 /// as a redeclaration of the given tag declaration.
4356 ///
4357 /// \returns true if the new tag kind is acceptable, false otherwise.
4358 bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag,
4359 bool isDefinition, SourceLocation NewTagLoc,
4360 const IdentifierInfo *Name);
4361
4362 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4363 /// former case, Name will be non-null. In the later case, Name will be null.
4364 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4365 /// a reference/declaration/definition of a tag.
4366 ///
4367 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4368 /// trailing-type-specifier) other than one in an alias-declaration.
4369 ///
4370 /// \param SkipBody If non-null, will be set to indicate if the caller should
4371 /// skip the definition of this tag and treat it as if it were a declaration.
4372 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4373 SourceLocation KWLoc, CXXScopeSpec &SS,
4374 IdentifierInfo *Name, SourceLocation NameLoc,
4375 const ParsedAttributesView &Attr, AccessSpecifier AS,
4376 SourceLocation ModulePrivateLoc,
4377 MultiTemplateParamsArg TemplateParameterLists,
4378 bool &OwnedDecl, bool &IsDependent,
4379 SourceLocation ScopedEnumKWLoc,
4380 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4381 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4382 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4383
4384 /// ActOnField - Each field of a C struct/union is passed into this in order
4385 /// to create a FieldDecl object for it.
4386 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4387 Declarator &D, Expr *BitfieldWidth);
4388
4389 /// HandleField - Analyze a field of a C struct or a C++ data member.
4390 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4391 Declarator &D, Expr *BitfieldWidth,
4392 InClassInitStyle InitStyle, AccessSpecifier AS);
4393
4394 /// Build a new FieldDecl and check its well-formedness.
4395 ///
4396 /// This routine builds a new FieldDecl given the fields name, type,
4397 /// record, etc. \p PrevDecl should refer to any previous declaration
4398 /// with the same name and in the same scope as the field to be
4399 /// created.
4400 ///
4401 /// \returns a new FieldDecl.
4402 ///
4403 /// \todo The Declarator argument is a hack. It will be removed once
4404 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4405 TypeSourceInfo *TInfo, RecordDecl *Record,
4406 SourceLocation Loc, bool Mutable,
4407 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4408 SourceLocation TSSL, AccessSpecifier AS,
4409 NamedDecl *PrevDecl, Declarator *D = nullptr);
4410
4411 bool CheckNontrivialField(FieldDecl *FD);
4412
4413 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4414 /// class and class extensions. For every class \@interface and class
4415 /// extension \@interface, if the last ivar is a bitfield of any type,
4416 /// then add an implicit `char :0` ivar to the end of that interface.
4417 void ActOnLastBitfield(SourceLocation DeclStart,
4418 SmallVectorImpl<Decl *> &AllIvarDecls);
4419
4420 // This is used for both record definitions and ObjC interface declarations.
4421 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4422 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4423 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4424
4425 /// ActOnTagStartDefinition - Invoked when we have entered the
4426 /// scope of a tag's definition (e.g., for an enumeration, class,
4427 /// struct, or union).
4428 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4429
4430 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4431 /// Differently from C++, actually parse the body and reject / error out
4432 /// in case of a structural mismatch.
4433 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4434
4435 typedef void *SkippedDefinitionContext;
4436
4437 /// Invoked when we enter a tag definition that we're skipping.
4438 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
4439
4440 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4441 /// C++ record definition's base-specifiers clause and are starting its
4442 /// member declarations.
4443 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
4444 SourceLocation FinalLoc,
4445 bool IsFinalSpelledSealed,
4446 bool IsAbstract,
4447 SourceLocation LBraceLoc);
4448
4449 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4450 /// the definition of a tag (enumeration, class, struct, or union).
4451 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
4452 SourceRange BraceRange);
4453
4454 ASTContext::CXXRecordDeclRelocationInfo
4455 CheckCXX2CRelocatable(const clang::CXXRecordDecl *D);
4456
4457 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
4458
4459 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4460 /// error parsing the definition of a tag.
4461 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
4462
4463 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
4464 EnumConstantDecl *LastEnumConst,
4465 SourceLocation IdLoc, IdentifierInfo *Id,
4466 Expr *val);
4467
4468 /// Check that this is a valid underlying type for an enum declaration.
4469 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
4470
4471 /// Check whether this is a valid redeclaration of a previous enumeration.
4472 /// \return true if the redeclaration was invalid.
4473 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4474 QualType EnumUnderlyingTy, bool IsFixed,
4475 const EnumDecl *Prev);
4476
4477 /// Determine whether the body of an anonymous enumeration should be skipped.
4478 /// \param II The name of the first enumerator.
4479 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
4480 SourceLocation IILoc);
4481
4482 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4483 SourceLocation IdLoc, IdentifierInfo *Id,
4484 const ParsedAttributesView &Attrs,
4485 SourceLocation EqualLoc, Expr *Val,
4486 SkipBodyInfo *SkipBody = nullptr);
4487 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4488 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4489 const ParsedAttributesView &Attr);
4490
4491 /// Set the current declaration context until it gets popped.
4492 void PushDeclContext(Scope *S, DeclContext *DC);
4493 void PopDeclContext();
4494
4495 /// EnterDeclaratorContext - Used when we must lookup names in the context
4496 /// of a declarator's nested name specifier.
4497 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
4498 void ExitDeclaratorContext(Scope *S);
4499
4500 /// Enter a template parameter scope, after it's been associated with a
4501 /// particular DeclContext. Causes lookup within the scope to chain through
4502 /// enclosing contexts in the correct order.
4503 void EnterTemplatedContext(Scope *S, DeclContext *DC);
4504
4505 /// Push the parameters of D, which must be a function, into scope.
4506 void ActOnReenterFunctionContext(Scope *S, Decl *D);
4507 void ActOnExitFunctionContext();
4508
4509 /// Add this decl to the scope shadowed decl chains.
4510 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4511
4512 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4513 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4514 /// true if 'D' belongs to the given declaration context.
4515 ///
4516 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4517 /// enclosing namespace set of the context, rather than contained
4518 /// directly within it.
4519 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4520 bool AllowInlineNamespace = false) const;
4521
4522 /// Finds the scope corresponding to the given decl context, if it
4523 /// happens to be an enclosing scope. Otherwise return NULL.
4524 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
4525
4526 /// Subroutines of ActOnDeclarator().
4527 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4528 TypeSourceInfo *TInfo);
4529 bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New);
4530
4531 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4532 void mergeDeclAttributes(
4533 NamedDecl *New, Decl *Old,
4534 AvailabilityMergeKind AMK = AvailabilityMergeKind::Redeclaration);
4535
4536 /// CheckAttributesOnDeducedType - Calls Sema functions for attributes that
4537 /// requires the type to be deduced.
4538 void CheckAttributesOnDeducedType(Decl *D);
4539
4540 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4541 /// same name and scope as a previous declaration 'Old'. Figure out
4542 /// how to resolve this situation, merging decls or emitting
4543 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4544 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
4545 LookupResult &OldDecls);
4546
4547 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4548 /// definition visible.
4549 /// This method performs any necessary cleanup on the parser state to discard
4550 /// child nodes from newly parsed decl we are retiring.
4551 void CleanupMergedEnum(Scope *S, Decl *New);
4552
4553 /// MergeFunctionDecl - We just parsed a function 'New' from
4554 /// declarator D which has the same name and scope as a previous
4555 /// declaration 'Old'. Figure out how to resolve this situation,
4556 /// merging decls or emitting diagnostics as appropriate.
4557 ///
4558 /// In C++, New and Old must be declarations that are not
4559 /// overloaded. Use IsOverload to determine whether New and Old are
4560 /// overloaded, and to select the Old declaration that New should be
4561 /// merged with.
4562 ///
4563 /// Returns true if there was an error, false otherwise.
4564 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
4565 bool MergeTypeWithOld, bool NewDeclIsDefn);
4566
4567 /// Completes the merge of two function declarations that are
4568 /// known to be compatible.
4569 ///
4570 /// This routine handles the merging of attributes and other
4571 /// properties of function declarations from the old declaration to
4572 /// the new declaration, once we know that New is in fact a
4573 /// redeclaration of Old.
4574 ///
4575 /// \returns false
4576 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4577 Scope *S, bool MergeTypeWithOld);
4578 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
4579
4580 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4581 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4582 /// situation, merging decls or emitting diagnostics as appropriate.
4583 ///
4584 /// Tentative definition rules (C99 6.9.2p2) are checked by
4585 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4586 /// definitions here, since the initializer hasn't been attached.
4587 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
4588
4589 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4590 /// scope as a previous declaration 'Old'. Figure out how to merge their
4591 /// types, emitting diagnostics as appropriate.
4592 ///
4593 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4594 /// back to here in AddInitializerToDecl. We can't check them before the
4595 /// initializer is attached.
4596 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4597
4598 /// We've just determined that \p Old and \p New both appear to be definitions
4599 /// of the same variable. Either diagnose or fix the problem.
4600 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4601 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
4602
4603 /// Filters out lookup results that don't fall within the given scope
4604 /// as determined by isDeclInScope.
4605 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4606 bool ConsiderLinkage, bool AllowInlineNamespace);
4607
4608 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4609 /// have compatible owning modules.
4610 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4611
4612 /// [module.interface]p6:
4613 /// A redeclaration of an entity X is implicitly exported if X was introduced
4614 /// by an exported declaration; otherwise it shall not be exported.
4615 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4616
4617 /// A wrapper function for checking the semantic restrictions of
4618 /// a redeclaration within a module.
4619 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4620
4621 /// Check the redefinition in C++20 Modules.
4622 ///
4623 /// [basic.def.odr]p14:
4624 /// For any definable item D with definitions in multiple translation units,
4625 /// - if D is a non-inline non-templated function or variable, or
4626 /// - if the definitions in different translation units do not satisfy the
4627 /// following requirements,
4628 /// the program is ill-formed; a diagnostic is required only if the
4629 /// definable item is attached to a named module and a prior definition is
4630 /// reachable at the point where a later definition occurs.
4631 /// - Each such definition shall not be attached to a named module
4632 /// ([module.unit]).
4633 /// - Each such definition shall consist of the same sequence of tokens, ...
4634 /// ...
4635 ///
4636 /// Return true if the redefinition is not allowed. Return false otherwise.
4637 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4638
4639 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4640
4641 /// If it's a file scoped decl that must warn if not used, keep track
4642 /// of it.
4643 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4644
4645 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4646 DiagReceiverTy;
4647
4648 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4649 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
4650 DiagReceiverTy DiagReceiver);
4651 void DiagnoseUnusedDecl(const NamedDecl *ND);
4652
4653 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4654 /// unless they are marked attr(unused).
4655 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4656
4657 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4658 /// variable.
4659 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4660
4661 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4662 /// from S, where a non-field would be declared. This routine copes
4663 /// with the difference between C and C++ scoping rules in structs and
4664 /// unions. For example, the following code is well-formed in C but
4665 /// ill-formed in C++:
4666 /// @code
4667 /// struct S6 {
4668 /// enum { BAR } e;
4669 /// };
4670 ///
4671 /// void test_S6() {
4672 /// struct S6 a;
4673 /// a.e = BAR;
4674 /// }
4675 /// @endcode
4676 /// For the declaration of BAR, this routine will return a different
4677 /// scope. The scope S will be the scope of the unnamed enumeration
4678 /// within S6. In C++, this routine will return the scope associated
4679 /// with S6, because the enumeration's scope is a transparent
4680 /// context but structures can contain non-field names. In C, this
4681 /// routine will return the translation unit scope, since the
4682 /// enumeration's scope is a transparent context and structures cannot
4683 /// contain non-field names.
4684 Scope *getNonFieldDeclScope(Scope *S);
4685
4686 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4687 SourceLocation Loc);
4688
4689 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4690 /// file scope. lazily create a decl for it. ForRedeclaration is true
4691 /// if we're creating this built-in in anticipation of redeclaring the
4692 /// built-in.
4693 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4694 bool ForRedeclaration, SourceLocation Loc);
4695
4696 /// Get the outermost AttributedType node that sets a calling convention.
4697 /// Valid types should not have multiple attributes with different CCs.
4698 const AttributedType *getCallingConvAttributedType(QualType T) const;
4699
4700 /// GetNameForDeclarator - Determine the full declaration name for the
4701 /// given Declarator.
4702 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
4703
4704 /// Retrieves the declaration name from a parsed unqualified-id.
4705 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
4706
4707 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4708 /// we are currently parsing the initializer.
4709 llvm::SmallPtrSet<const Decl *, 4> ParsingInitForAutoVars;
4710
4711 /// Look for a locally scoped extern "C" declaration by the given name.
4712 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
4713
4714 void deduceOpenCLAddressSpace(VarDecl *decl);
4715 void deduceHLSLAddressSpace(VarDecl *decl);
4716
4717 /// Adjust the \c DeclContext for a function or variable that might be a
4718 /// function-local external declaration.
4719 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
4720
4721 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4722
4723 /// Checks if the variant/multiversion functions are compatible.
4724 bool areMultiversionVariantFunctionsCompatible(
4725 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4726 const PartialDiagnostic &NoProtoDiagID,
4727 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4728 const PartialDiagnosticAt &NoSupportDiagIDAt,
4729 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4730 bool ConstexprSupported, bool CLinkageMayDiffer);
4731
4732 /// type checking declaration initializers (C99 6.7.8)
4733 bool CheckForConstantInitializer(
4734 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4735
4736 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
4737 QualType Type, TypeSourceInfo *TSI,
4738 SourceRange Range, bool DirectInit,
4739 Expr *Init);
4740
4741 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
4742 Expr *Init);
4743
4744 sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator);
4745
4746 // Heuristically tells if the function is `get_return_object` member of a
4747 // coroutine promise_type by matching the function name.
4748 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4749 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4750
4751 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4752 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4753 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4754 Scope *S);
4755
4756 /// If this function is a C++ replaceable global allocation function
4757 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4758 /// adds any function attributes that we know a priori based on the standard.
4759 ///
4760 /// We need to check for duplicate attributes both here and where user-written
4761 /// attributes are applied to declarations.
4762 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4763 FunctionDecl *FD);
4764
4765 /// Adds any function attributes that we know a priori based on
4766 /// the declaration of this function.
4767 ///
4768 /// These attributes can apply both to implicitly-declared builtins
4769 /// (like __builtin___printf_chk) or to library-declared functions
4770 /// like NSLog or printf.
4771 ///
4772 /// We need to check for duplicate attributes both here and where user-written
4773 /// attributes are applied to declarations.
4774 void AddKnownFunctionAttributes(FunctionDecl *FD);
4775
4776 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4777 /// the correct width, and that the field type is valid.
4778 /// Returns false on success.
4779 ExprResult VerifyBitField(SourceLocation FieldLoc,
4780 const IdentifierInfo *FieldName, QualType FieldTy,
4781 bool IsMsStruct, Expr *BitWidth);
4782
4783 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4784 /// enum. If AllowMask is true, then we also allow the complement of a valid
4785 /// value, to be used as a mask.
4786 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4787 bool AllowMask) const;
4788
4789 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4790 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4791 SourceLocation WeakNameLoc);
4792
4793 /// ActOnPragmaRedefineExtname - Called on well formed
4794 /// \#pragma redefine_extname oldname newname.
4795 void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName,
4796 IdentifierInfo *AliasName,
4797 SourceLocation PragmaLoc,
4798 SourceLocation WeakNameLoc,
4799 SourceLocation AliasNameLoc);
4800
4801 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4802 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4803 SourceLocation PragmaLoc,
4804 SourceLocation WeakNameLoc,
4805 SourceLocation AliasNameLoc);
4806
4807 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4808 enum class FunctionEmissionStatus {
4809 Emitted,
4810 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4811 OMPDiscarded, // Discarded due to OpenMP hostness
4812 TemplateDiscarded, // Discarded due to uninstantiated templates
4813 Unknown,
4814 };
4815 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4816 bool Final = false);
4817
4818 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4819 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4820
4821 /// Function or variable declarations to be checked for whether the deferred
4822 /// diagnostics should be emitted.
4823 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
4824
4825private:
4826 /// Map of current shadowing declarations to shadowed declarations. Warn if
4827 /// it looks like the user is trying to modify the shadowing declaration.
4828 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4829
4830 // We need this to handle
4831 //
4832 // typedef struct {
4833 // void *foo() { return 0; }
4834 // } A;
4835 //
4836 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4837 // for example. If 'A', foo will have external linkage. If we have '*A',
4838 // foo will have no linkage. Since we can't know until we get to the end
4839 // of the typedef, this function finds out if D might have non-external
4840 // linkage. Callers should verify at the end of the TU if it D has external
4841 // linkage or not.
4842 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4843
4844#include "clang/Sema/AttrIsTypeDependent.inc"
4845
4846 ///@}
4847
4848 //
4849 //
4850 // -------------------------------------------------------------------------
4851 //
4852 //
4853
4854 /// \name Declaration Attribute Handling
4855 /// Implementations are in SemaDeclAttr.cpp
4856 ///@{
4857
4858public:
4859 /// Describes the kind of priority given to an availability attribute.
4860 ///
4861 /// The sum of priorities deteremines the final priority of the attribute.
4862 /// The final priority determines how the attribute will be merged.
4863 /// An attribute with a lower priority will always remove higher priority
4864 /// attributes for the specified platform when it is being applied. An
4865 /// attribute with a higher priority will not be applied if the declaration
4866 /// already has an availability attribute with a lower priority for the
4867 /// specified platform. The final prirority values are not expected to match
4868 /// the values in this enumeration, but instead should be treated as a plain
4869 /// integer value. This enumeration just names the priority weights that are
4870 /// used to calculate that final vaue.
4871 enum AvailabilityPriority : int {
4872 /// The availability attribute was specified explicitly next to the
4873 /// declaration.
4874 AP_Explicit = 0,
4875
4876 /// The availability attribute was applied using '#pragma clang attribute'.
4877 AP_PragmaClangAttribute = 1,
4878
4879 /// The availability attribute for a specific platform was inferred from
4880 /// an availability attribute for another platform.
4881 AP_InferredFromOtherPlatform = 2,
4882
4883 /// The availability attribute was inferred from an 'anyAppleOS'
4884 /// availability attribute.
4885 AP_InferredFromAnyAppleOS = 3,
4886
4887 /// The availability attribute was inferred from an 'anyAppleOS'
4888 /// availability attribute that was applied using '#pragma clang attribute'.
4889 /// This has the lowest priority.
4890 AP_PragmaClangAttribute_InferredFromAnyAppleOS = 4
4891 };
4892
4893 /// Describes the reason a calling convention specification was ignored, used
4894 /// for diagnostics.
4895 enum class CallingConventionIgnoredReason {
4896 ForThisTarget = 0,
4897 VariadicFunction,
4898 ConstructorDestructor,
4899 BuiltinFunction
4900 };
4901
4902 /// A helper function to provide Attribute Location for the Attr types
4903 /// AND the ParsedAttr.
4904 template <typename AttrInfo>
4905 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
4906 getAttrLoc(const AttrInfo &AL) {
4907 return AL.getLocation();
4908 }
4909 SourceLocation getAttrLoc(const AttributeCommonInfo &CI);
4910
4911 /// If Expr is a valid integer constant, get the value of the integer
4912 /// expression and return success or failure. May output an error.
4913 ///
4914 /// Negative argument is implicitly converted to unsigned, unless
4915 /// \p StrictlyUnsigned is true.
4916 template <typename AttrInfo>
4917 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4918 unsigned Idx = UINT_MAX,
4919 bool StrictlyUnsigned = false) {
4920 std::optional<llvm::APSInt> I = llvm::APSInt(32);
4921 if (Expr->isTypeDependent() ||
4922 !(I = Expr->getIntegerConstantExpr(Ctx: Context))) {
4923 if (Idx != UINT_MAX)
4924 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4925 << &AI << Idx << AANT_ArgumentIntegerConstant
4926 << Expr->getSourceRange();
4927 else
4928 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4929 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
4930 return false;
4931 }
4932
4933 if (!I->isIntN(N: 32)) {
4934 Diag(Loc: Expr->getExprLoc(), DiagID: diag::err_ice_too_large)
4935 << toString(I: *I, Radix: 10, Signed: false) << 32 << /* Unsigned */ 1;
4936 return false;
4937 }
4938
4939 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
4940 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
4941 << &AI << /*non-negative*/ 1;
4942 return false;
4943 }
4944
4945 Val = (uint32_t)I->getZExtValue();
4946 return true;
4947 }
4948
4949 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
4950 /// \#pragma weak during processing of other Decls.
4951 /// I couldn't figure out a clean way to generate these in-line, so
4952 /// we store them here and handle separately -- which is a hack.
4953 /// It would be best to refactor this.
4954 SmallVector<Decl *, 2> WeakTopLevelDecl;
4955
4956 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
4957 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
4958
4959 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
4960 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
4961 ExtVectorDeclsType;
4962
4963 /// ExtVectorDecls - This is a list all the extended vector types. This allows
4964 /// us to associate a raw vector type with one of the ext_vector type names.
4965 /// This is only necessary for issuing pretty diagnostics.
4966 ExtVectorDeclsType ExtVectorDecls;
4967
4968 /// Check if the argument \p E is a ASCII string literal. If not emit an error
4969 /// and return false, otherwise set \p Str to the value of the string literal
4970 /// and return true.
4971 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4972 const Expr *E, StringRef &Str,
4973 SourceLocation *ArgLocation = nullptr);
4974
4975 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
4976 /// If not emit an error and return false. If the argument is an identifier it
4977 /// will emit an error with a fixit hint and treat it as if it was a string
4978 /// literal.
4979 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4980 StringRef &Str,
4981 SourceLocation *ArgLocation = nullptr);
4982
4983 /// Determine if type T is a valid subject for a nonnull and similar
4984 /// attributes. Dependent types are considered valid so they can be checked
4985 /// during instantiation time. By default, we look through references (the
4986 /// behavior used by nonnull), but if the second parameter is true, then we
4987 /// treat a reference type as valid.
4988 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4989
4990 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
4991 /// declaration.
4992 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4993 Expr *OE);
4994
4995 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
4996 /// declaration.
4997 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
4998 Expr *ParamExpr);
4999
5000 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
5001 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
5002
5003 AvailabilityAttr *
5004 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
5005 const IdentifierInfo *Platform, bool Implicit,
5006 VersionTuple Introduced, VersionTuple Deprecated,
5007 VersionTuple Obsoleted, bool IsUnavailable,
5008 StringRef Message, bool IsStrict, StringRef Replacement,
5009 AvailabilityMergeKind AMK, int Priority,
5010 const IdentifierInfo *IIEnvironment,
5011 const IdentifierInfo *InferredPlatformII = nullptr);
5012
5013 AvailabilityAttr *mergeAndInferAvailabilityAttr(
5014 NamedDecl *D, const AttributeCommonInfo &CI,
5015 const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced,
5016 VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable,
5017 StringRef Message, bool IsStrict, StringRef Replacement,
5018 AvailabilityMergeKind AMK, int Priority,
5019 const IdentifierInfo *IIEnvironment,
5020 const IdentifierInfo *InferredPlatformII);
5021
5022 TypeVisibilityAttr *
5023 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5024 TypeVisibilityAttr::VisibilityType Vis);
5025 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5026 VisibilityAttr::VisibilityType Vis);
5027 void mergeVisibilityType(Decl *D, SourceLocation Loc,
5028 VisibilityAttr::VisibilityType Type);
5029 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
5030 StringRef Name);
5031
5032 /// Used to implement to perform semantic checking on
5033 /// attribute((section("foo"))) specifiers.
5034 ///
5035 /// In this case, "foo" is passed in to be checked. If the section
5036 /// specifier is invalid, return an Error that indicates the problem.
5037 ///
5038 /// This is a simple quality of implementation feature to catch errors
5039 /// and give good diagnostics in cases when the assembler or code generator
5040 /// would otherwise reject the section specifier.
5041 llvm::Error isValidSectionSpecifier(StringRef Str);
5042 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
5043 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
5044 StringRef Name);
5045
5046 // Check for things we'd like to warn about. Multiversioning issues are
5047 // handled later in the process, once we know how many exist.
5048 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
5049
5050 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5051 StringRef NewUserDiagnostic);
5052 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5053 const IdentifierInfo *Format, int FormatIdx,
5054 int FirstArg);
5055 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
5056 const AttributeCommonInfo &CI,
5057 const IdentifierInfo *Format,
5058 int FormatIdx,
5059 StringLiteral *FormatStr);
5060 ModularFormatAttr *mergeModularFormatAttr(Decl *D,
5061 const AttributeCommonInfo &CI,
5062 const IdentifierInfo *ModularImplFn,
5063 StringRef ImplName,
5064 MutableArrayRef<StringRef> Aspects);
5065
5066 PersonalityAttr *mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
5067 const AttributeCommonInfo &CI);
5068
5069 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5070 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5071 bool IsPackExpansion);
5072 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
5073 bool IsPackExpansion);
5074
5075 /// AddAlignValueAttr - Adds an align_value attribute to a particular
5076 /// declaration.
5077 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
5078
5079 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
5080 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
5081 MutableArrayRef<Expr *> Args);
5082 Attr *CreateAnnotationAttr(const ParsedAttr &AL);
5083
5084 bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range,
5085 bool BestCase,
5086 MSInheritanceModel SemanticSpelling);
5087
5088 void CheckAlignasUnderalignment(Decl *D);
5089
5090 /// AddModeAttr - Adds a mode attribute to a particular declaration.
5091 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5092 const IdentifierInfo *Name, bool InInstantiation = false);
5093 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
5094 const AttributeCommonInfo &CI,
5095 const IdentifierInfo *Ident);
5096 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
5097 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
5098 const AttributeCommonInfo &CI);
5099 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
5100 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
5101 const InternalLinkageAttr &AL);
5102
5103 /// Check validaty of calling convention attribute \p attr. If \p FD
5104 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
5105 /// target. Otherwise, it is specified by \p CFT.
5106 bool CheckCallingConvAttr(
5107 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
5108 CUDAFunctionTarget CFT = CUDAFunctionTarget::InvalidTarget);
5109
5110 /// Checks a regparm attribute, returning true if it is ill-formed and
5111 /// otherwise setting numParams to the appropriate value.
5112 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
5113
5114 /// Create a CUDALaunchBoundsAttr attribute. By default, the function only
5115 /// supports nvptx target architectures and skips MaxBlocks if it is previous
5116 /// to sm_90. Use \p IgnoreArch to skip the architecture check.
5117 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5118 Expr *MaxThreads,
5119 Expr *MinBlocks, Expr *MaxBlocks,
5120 bool IgnoreArch = false);
5121
5122 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5123 /// declaration.
5124 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5125 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5126
5127 /// Add a cluster_dims attribute to a particular declaration.
5128 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5129 Expr *X, Expr *Y, Expr *Z);
5130 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5131 Expr *Y, Expr *Z);
5132 /// Add a no_cluster attribute to a particular declaration.
5133 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5134
5135 enum class RetainOwnershipKind { NS, CF, OS };
5136
5137 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5138 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5139
5140 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5141
5142 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5143 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5144 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5145 const AttributeCommonInfo &CI,
5146 bool BestCase,
5147 MSInheritanceModel Model);
5148
5149 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5150 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5151 const EnforceTCBLeafAttr &AL);
5152
5153 /// Helper for delayed processing TransparentUnion or
5154 /// BPFPreserveAccessIndexAttr attribute.
5155 void ProcessDeclAttributeDelayed(Decl *D,
5156 const ParsedAttributesView &AttrList);
5157
5158 // Options for ProcessDeclAttributeList().
5159 struct ProcessDeclAttributeOptions {
5160 ProcessDeclAttributeOptions()
5161 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
5162
5163 ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
5164 ProcessDeclAttributeOptions Result = *this;
5165 Result.IncludeCXX11Attributes = Val;
5166 return Result;
5167 }
5168
5169 ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
5170 ProcessDeclAttributeOptions Result = *this;
5171 Result.IgnoreTypeAttributes = Val;
5172 return Result;
5173 }
5174
5175 // Should C++11 attributes be processed?
5176 bool IncludeCXX11Attributes;
5177
5178 // Should any type attributes encountered be ignored?
5179 // If this option is false, a diagnostic will be emitted for any type
5180 // attributes of a kind that does not "slide" from the declaration to
5181 // the decl-specifier-seq.
5182 bool IgnoreTypeAttributes;
5183 };
5184
5185 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5186 /// attribute list to the specified decl, ignoring any type attributes.
5187 void ProcessDeclAttributeList(Scope *S, Decl *D,
5188 const ParsedAttributesView &AttrList,
5189 const ProcessDeclAttributeOptions &Options =
5190 ProcessDeclAttributeOptions());
5191
5192 /// Annotation attributes are the only attributes allowed after an access
5193 /// specifier.
5194 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5195 const ParsedAttributesView &AttrList);
5196
5197 /// checkUnusedDeclAttributes - Given a declarator which is not being
5198 /// used to build a declaration, complain about any decl attributes
5199 /// which might be lying around on it.
5200 void checkUnusedDeclAttributes(Declarator &D);
5201
5202 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5203
5204 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5205 /// \#pragma weak needs a non-definition decl and source may not have one.
5206 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
5207 SourceLocation Loc);
5208
5209 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5210 /// applied to it, possibly with an alias.
5211 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5212
5213 void ProcessPragmaWeak(Scope *S, Decl *D);
5214 // Decl attributes - this routine is the top level dispatcher.
5215 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5216
5217 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5218
5219 /// Given a set of delayed diagnostics, re-emit them as if they had
5220 /// been delayed in the current context instead of in the given pool.
5221 /// Essentially, this just moves them to the current pool.
5222 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5223
5224 /// Check that the type is a plain record with one field being a pointer
5225 /// type and the other field being an integer. This matches the common
5226 /// implementation of std::span or sized_allocation_t in P0901R11.
5227 bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty);
5228
5229 /// Check if IdxExpr is a valid parameter index for a function or
5230 /// instance method D. May output an error.
5231 ///
5232 /// \returns true if IdxExpr is a valid index.
5233 template <typename AttrInfo>
5234 bool checkFunctionOrMethodParameterIndex(
5235 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5236 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5237 bool CanIndexVariadicArguments = false) {
5238 assert(isFunctionOrMethodOrBlockForAttrSubject(D));
5239
5240 // In C++ the implicit 'this' function parameter also counts.
5241 // Parameters are counted from one.
5242 bool HP = hasFunctionProto(D);
5243 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
5244 bool IV = HP && isFunctionOrMethodVariadic(D);
5245 unsigned NumParams =
5246 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
5247
5248 std::optional<llvm::APSInt> IdxInt;
5249 if (IdxExpr->isTypeDependent() ||
5250 !(IdxInt = IdxExpr->getIntegerConstantExpr(Ctx: Context))) {
5251 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5252 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5253 << IdxExpr->getSourceRange();
5254 return false;
5255 }
5256
5257 constexpr unsigned Limit = 1 << ParamIdx::IdxBitWidth;
5258 unsigned IdxSource = IdxInt->getLimitedValue(Limit);
5259 if (IdxSource < 1 || IdxSource == Limit ||
5260 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5261 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5262 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5263 return false;
5264 }
5265 if (HasImplicitThisParam && !CanIndexImplicitThis) {
5266 if (IdxSource == 1) {
5267 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5268 << &AI << IdxExpr->getSourceRange();
5269 return false;
5270 }
5271 }
5272
5273 Idx = ParamIdx(IdxSource, D);
5274 return true;
5275 }
5276
5277 ///@}
5278
5279 //
5280 //
5281 // -------------------------------------------------------------------------
5282 //
5283 //
5284
5285 /// \name C++ Declarations
5286 /// Implementations are in SemaDeclCXX.cpp
5287 ///@{
5288
5289public:
5290 void CheckDelegatingCtorCycles();
5291
5292 /// Called before parsing a function declarator belonging to a function
5293 /// declaration.
5294 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
5295 unsigned TemplateParameterDepth);
5296
5297 /// Called after parsing a function declarator belonging to a function
5298 /// declaration.
5299 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
5300
5301 // Act on C++ namespaces
5302 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5303 SourceLocation NamespaceLoc,
5304 SourceLocation IdentLoc, IdentifierInfo *Ident,
5305 SourceLocation LBrace,
5306 const ParsedAttributesView &AttrList,
5307 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5308
5309 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5310 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5311 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5312
5313 NamespaceDecl *getStdNamespace() const;
5314
5315 /// Retrieve the special "std" namespace, which may require us to
5316 /// implicitly define the namespace.
5317 NamespaceDecl *getOrCreateStdNamespace();
5318
5319 CXXRecordDecl *getStdBadAlloc() const;
5320 EnumDecl *getStdAlignValT() const;
5321
5322 TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const;
5323 FunctionDecl *BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl,
5324 QualType AllocType, SourceLocation);
5325
5326 ValueDecl *tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
5327 const IdentifierInfo *MemberOrBase);
5328
5329 enum class ComparisonCategoryUsage {
5330 /// The '<=>' operator was used in an expression and a builtin operator
5331 /// was selected.
5332 OperatorInExpression,
5333 /// A defaulted 'operator<=>' needed the comparison category. This
5334 /// typically only applies to 'std::strong_ordering', due to the implicit
5335 /// fallback return value.
5336 DefaultedOperator,
5337 };
5338
5339 /// Lookup the specified comparison category types in the standard
5340 /// library, an check the VarDecls possibly returned by the operator<=>
5341 /// builtins for that type.
5342 ///
5343 /// \return The type of the comparison category type corresponding to the
5344 /// specified Kind, or a null type if an error occurs
5345 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5346 SourceLocation Loc,
5347 ComparisonCategoryUsage Usage);
5348
5349 /// Tests whether Ty is an instance of std::initializer_list and, if
5350 /// it is and Element is not NULL, assigns the element type to Element.
5351 bool isStdInitializerList(QualType Ty, QualType *Element);
5352
5353 /// Tests whether Ty is an instance of std::type_identity and, if
5354 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5355 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5356 /// incorrectly structured despite having the correct name, the faulty Decl
5357 /// will be assigned to MalformedDecl.
5358 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5359 const Decl **MalformedDecl = nullptr);
5360
5361 /// Looks for the std::initializer_list template and instantiates it
5362 /// with Element, or emits an error if it's not found.
5363 ///
5364 /// \returns The instantiated template, or null on error.
5365 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5366
5367 /// Looks for the std::type_identity template and instantiates it
5368 /// with Type, or returns a null type if type_identity has not been declared
5369 ///
5370 /// \returns The instantiated template, or null if std::type_identity is not
5371 /// declared
5372 QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc);
5373
5374 /// Determine whether Ctor is an initializer-list constructor, as
5375 /// defined in [dcl.init.list]p2.
5376 bool isInitListConstructor(const FunctionDecl *Ctor);
5377
5378 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5379 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5380 SourceLocation IdentLoc,
5381 IdentifierInfo *NamespcName,
5382 const ParsedAttributesView &AttrList);
5383
5384 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5385
5386 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5387 SourceLocation AliasLoc, IdentifierInfo *Alias,
5388 CXXScopeSpec &SS, SourceLocation IdentLoc,
5389 IdentifierInfo *Ident);
5390
5391 /// Remove decls we can't actually see from a lookup being used to declare
5392 /// shadow using decls.
5393 ///
5394 /// \param S - The scope of the potential shadow decl
5395 /// \param Previous - The lookup of a potential shadow decl's name.
5396 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5397
5398 /// Hides a using shadow declaration. This is required by the current
5399 /// using-decl implementation when a resolvable using declaration in a
5400 /// class is followed by a declaration which would hide or override
5401 /// one or more of the using decl's targets; for example:
5402 ///
5403 /// struct Base { void foo(int); };
5404 /// struct Derived : Base {
5405 /// using Base::foo;
5406 /// void foo(int);
5407 /// };
5408 ///
5409 /// The governing language is C++03 [namespace.udecl]p12:
5410 ///
5411 /// When a using-declaration brings names from a base class into a
5412 /// derived class scope, member functions in the derived class
5413 /// override and/or hide member functions with the same name and
5414 /// parameter types in a base class (rather than conflicting).
5415 ///
5416 /// There are two ways to implement this:
5417 /// (1) optimistically create shadow decls when they're not hidden
5418 /// by existing declarations, or
5419 /// (2) don't create any shadow decls (or at least don't make them
5420 /// visible) until we've fully parsed/instantiated the class.
5421 /// The problem with (1) is that we might have to retroactively remove
5422 /// a shadow decl, which requires several O(n) operations because the
5423 /// decl structures are (very reasonably) not designed for removal.
5424 /// (2) avoids this but is very fiddly and phase-dependent.
5425 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5426
5427 /// Determines whether to create a using shadow decl for a particular
5428 /// decl, given the set of decls existing prior to this using lookup.
5429 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5430 const LookupResult &PreviousDecls,
5431 UsingShadowDecl *&PrevShadow);
5432
5433 /// Builds a shadow declaration corresponding to a 'using' declaration.
5434 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5435 NamedDecl *Target,
5436 UsingShadowDecl *PrevDecl);
5437
5438 /// Checks that the given using declaration is not an invalid
5439 /// redeclaration. Note that this is checking only for the using decl
5440 /// itself, not for any ill-formedness among the UsingShadowDecls.
5441 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5442 bool HasTypenameKeyword,
5443 const CXXScopeSpec &SS,
5444 SourceLocation NameLoc,
5445 const LookupResult &Previous);
5446
5447 /// Checks that the given nested-name qualifier used in a using decl
5448 /// in the current context is appropriately related to the current
5449 /// scope. If an error is found, diagnoses it and returns true.
5450 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5451 /// the result of that lookup. UD is likewise nullptr, except when we have an
5452 /// already-populated UsingDecl whose shadow decls contain the same
5453 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5454 /// scope).
5455 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5456 const CXXScopeSpec &SS,
5457 const DeclarationNameInfo &NameInfo,
5458 SourceLocation NameLoc,
5459 const LookupResult *R = nullptr,
5460 const UsingDecl *UD = nullptr);
5461
5462 /// Builds a using declaration.
5463 ///
5464 /// \param IsInstantiation - Whether this call arises from an
5465 /// instantiation of an unresolved using declaration. We treat
5466 /// the lookup differently for these declarations.
5467 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5468 SourceLocation UsingLoc,
5469 bool HasTypenameKeyword,
5470 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5471 DeclarationNameInfo NameInfo,
5472 SourceLocation EllipsisLoc,
5473 const ParsedAttributesView &AttrList,
5474 bool IsInstantiation, bool IsUsingIfExists);
5475 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5476 SourceLocation UsingLoc,
5477 SourceLocation EnumLoc,
5478 SourceLocation NameLoc,
5479 TypeSourceInfo *EnumType, EnumDecl *ED);
5480 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5481 ArrayRef<NamedDecl *> Expansions);
5482
5483 /// Additional checks for a using declaration referring to a constructor name.
5484 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5485
5486 /// Given a derived-class using shadow declaration for a constructor and the
5487 /// correspnding base class constructor, find or create the implicit
5488 /// synthesized derived class constructor to use for this initialization.
5489 CXXConstructorDecl *
5490 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5491 ConstructorUsingShadowDecl *DerivedShadow);
5492
5493 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5494 SourceLocation UsingLoc,
5495 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5496 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5497 const ParsedAttributesView &AttrList);
5498 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5499 SourceLocation UsingLoc,
5500 SourceLocation EnumLoc, SourceRange TyLoc,
5501 const IdentifierInfo &II, ParsedType Ty,
5502 const CXXScopeSpec &SS);
5503 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5504 MultiTemplateParamsArg TemplateParams,
5505 SourceLocation UsingLoc, UnqualifiedId &Name,
5506 const ParsedAttributesView &AttrList,
5507 TypeResult Type, Decl *DeclFromDeclSpec);
5508
5509 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5510 /// including handling of its default argument expressions.
5511 ///
5512 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5513 ExprResult BuildCXXConstructExpr(
5514 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5515 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5516 bool HadMultipleCandidates, bool IsListInitialization,
5517 bool IsStdInitListInitialization, bool RequiresZeroInit,
5518 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5519
5520 /// Build a CXXConstructExpr whose constructor has already been resolved if
5521 /// it denotes an inherited constructor.
5522 ExprResult BuildCXXConstructExpr(
5523 SourceLocation ConstructLoc, QualType DeclInitType,
5524 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5525 bool HadMultipleCandidates, bool IsListInitialization,
5526 bool IsStdInitListInitialization, bool RequiresZeroInit,
5527 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5528
5529 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5530 // the constructor can be elidable?
5531 ExprResult BuildCXXConstructExpr(
5532 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5533 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5534 bool HadMultipleCandidates, bool IsListInitialization,
5535 bool IsStdInitListInitialization, bool RequiresZeroInit,
5536 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5537
5538 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr,
5539 SourceLocation InitLoc);
5540
5541 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5542 /// constructed variable.
5543 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5544
5545 /// Helper class that collects exception specifications for
5546 /// implicitly-declared special member functions.
5547 class ImplicitExceptionSpecification {
5548 // Pointer to allow copying
5549 Sema *Self;
5550 // We order exception specifications thus:
5551 // noexcept is the most restrictive, but is only used in C++11.
5552 // throw() comes next.
5553 // Then a throw(collected exceptions)
5554 // Finally no specification, which is expressed as noexcept(false).
5555 // throw(...) is used instead if any called function uses it.
5556 ExceptionSpecificationType ComputedEST;
5557 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5558 SmallVector<QualType, 4> Exceptions;
5559
5560 void ClearExceptions() {
5561 ExceptionsSeen.clear();
5562 Exceptions.clear();
5563 }
5564
5565 public:
5566 explicit ImplicitExceptionSpecification(Sema &Self)
5567 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5568 if (!Self.getLangOpts().CPlusPlus11)
5569 ComputedEST = EST_DynamicNone;
5570 }
5571
5572 /// Get the computed exception specification type.
5573 ExceptionSpecificationType getExceptionSpecType() const {
5574 assert(!isComputedNoexcept(ComputedEST) &&
5575 "noexcept(expr) should not be a possible result");
5576 return ComputedEST;
5577 }
5578
5579 /// The number of exceptions in the exception specification.
5580 unsigned size() const { return Exceptions.size(); }
5581
5582 /// The set of exceptions in the exception specification.
5583 const QualType *data() const { return Exceptions.data(); }
5584
5585 /// Integrate another called method into the collected data.
5586 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5587
5588 /// Integrate an invoked expression into the collected data.
5589 void CalledExpr(Expr *E) { CalledStmt(S: E); }
5590
5591 /// Integrate an invoked statement into the collected data.
5592 void CalledStmt(Stmt *S);
5593
5594 /// Overwrite an EPI's exception specification with this
5595 /// computed exception specification.
5596 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5597 FunctionProtoType::ExceptionSpecInfo ESI;
5598 ESI.Type = getExceptionSpecType();
5599 if (ESI.Type == EST_Dynamic) {
5600 ESI.Exceptions = Exceptions;
5601 } else if (ESI.Type == EST_None) {
5602 /// C++11 [except.spec]p14:
5603 /// The exception-specification is noexcept(false) if the set of
5604 /// potential exceptions of the special member function contains "any"
5605 ESI.Type = EST_NoexceptFalse;
5606 ESI.NoexceptExpr =
5607 Self->ActOnCXXBoolLiteral(OpLoc: SourceLocation(), Kind: tok::kw_false).get();
5608 }
5609 return ESI;
5610 }
5611 };
5612
5613 /// Evaluate the implicit exception specification for a defaulted
5614 /// special member function.
5615 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5616
5617 /// Check the given exception-specification and update the
5618 /// exception specification information with the results.
5619 void checkExceptionSpecification(bool IsTopLevel,
5620 ExceptionSpecificationType EST,
5621 ArrayRef<ParsedType> DynamicExceptions,
5622 ArrayRef<SourceRange> DynamicExceptionRanges,
5623 Expr *NoexceptExpr,
5624 SmallVectorImpl<QualType> &Exceptions,
5625 FunctionProtoType::ExceptionSpecInfo &ESI);
5626
5627 /// Add an exception-specification to the given member or friend function
5628 /// (or function template). The exception-specification was parsed
5629 /// after the function itself was declared.
5630 void actOnDelayedExceptionSpecification(
5631 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5632 ArrayRef<ParsedType> DynamicExceptions,
5633 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5634
5635 class InheritedConstructorInfo;
5636
5637 /// Determine if a special member function should have a deleted
5638 /// definition when it is defaulted.
5639 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
5640 InheritedConstructorInfo *ICI = nullptr,
5641 bool Diagnose = false);
5642
5643 /// Produce notes explaining why a defaulted function was defined as deleted.
5644 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5645
5646 /// Declare the implicit default constructor for the given class.
5647 ///
5648 /// \param ClassDecl The class declaration into which the implicit
5649 /// default constructor will be added.
5650 ///
5651 /// \returns The implicitly-declared default constructor.
5652 CXXConstructorDecl *
5653 DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl);
5654
5655 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5656 /// defining this constructor as the default constructor.
5657 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5658 CXXConstructorDecl *Constructor);
5659
5660 /// Declare the implicit destructor for the given class.
5661 ///
5662 /// \param ClassDecl The class declaration into which the implicit
5663 /// destructor will be added.
5664 ///
5665 /// \returns The implicitly-declared destructor.
5666 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5667
5668 /// DefineImplicitDestructor - Checks for feasibility of
5669 /// defining this destructor as the default destructor.
5670 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5671 CXXDestructorDecl *Destructor);
5672
5673 /// Build an exception spec for destructors that don't have one.
5674 ///
5675 /// C++11 says that user-defined destructors with no exception spec get one
5676 /// that looks as if the destructor was implicitly declared.
5677 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5678
5679 /// Define the specified inheriting constructor.
5680 void DefineInheritingConstructor(SourceLocation UseLoc,
5681 CXXConstructorDecl *Constructor);
5682
5683 /// Declare the implicit copy constructor for the given class.
5684 ///
5685 /// \param ClassDecl The class declaration into which the implicit
5686 /// copy constructor will be added.
5687 ///
5688 /// \returns The implicitly-declared copy constructor.
5689 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5690
5691 /// DefineImplicitCopyConstructor - Checks for feasibility of
5692 /// defining this constructor as the copy constructor.
5693 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5694 CXXConstructorDecl *Constructor);
5695
5696 /// Declare the implicit move constructor for the given class.
5697 ///
5698 /// \param ClassDecl The Class declaration into which the implicit
5699 /// move constructor will be added.
5700 ///
5701 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5702 /// declared.
5703 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5704
5705 /// DefineImplicitMoveConstructor - Checks for feasibility of
5706 /// defining this constructor as the move constructor.
5707 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5708 CXXConstructorDecl *Constructor);
5709
5710 /// Declare the implicit copy assignment operator for the given class.
5711 ///
5712 /// \param ClassDecl The class declaration into which the implicit
5713 /// copy assignment operator will be added.
5714 ///
5715 /// \returns The implicitly-declared copy assignment operator.
5716 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5717
5718 /// Defines an implicitly-declared copy assignment operator.
5719 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5720 CXXMethodDecl *MethodDecl);
5721
5722 /// Declare the implicit move assignment operator for the given class.
5723 ///
5724 /// \param ClassDecl The Class declaration into which the implicit
5725 /// move assignment operator will be added.
5726 ///
5727 /// \returns The implicitly-declared move assignment operator, or NULL if it
5728 /// wasn't declared.
5729 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5730
5731 /// Defines an implicitly-declared move assignment operator.
5732 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5733 CXXMethodDecl *MethodDecl);
5734
5735 /// Check a completed declaration of an implicit special member.
5736 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5737
5738 /// Determine whether the given function is an implicitly-deleted
5739 /// special member function.
5740 bool isImplicitlyDeleted(FunctionDecl *FD);
5741
5742 /// Check whether 'this' shows up in the type of a static member
5743 /// function after the (naturally empty) cv-qualifier-seq would be.
5744 ///
5745 /// \returns true if an error occurred.
5746 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5747
5748 /// Whether this' shows up in the exception specification of a static
5749 /// member function.
5750 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5751
5752 /// Check whether 'this' shows up in the attributes of the given
5753 /// static member function.
5754 ///
5755 /// \returns true if an error occurred.
5756 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5757
5758 bool CheckImmediateEscalatingFunctionDefinition(
5759 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5760
5761 void DiagnoseImmediateEscalatingReason(FunctionDecl *FD);
5762
5763 /// Given a constructor and the set of arguments provided for the
5764 /// constructor, convert the arguments and add any required default arguments
5765 /// to form a proper call to this constructor.
5766 ///
5767 /// \returns true if an error occurred, false otherwise.
5768 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5769 QualType DeclInitType, MultiExprArg ArgsPtr,
5770 SourceLocation Loc,
5771 SmallVectorImpl<Expr *> &ConvertedArgs,
5772 bool AllowExplicit = false,
5773 bool IsListInitialization = false);
5774
5775 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5776 /// initializer for the declaration 'Dcl'.
5777 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5778 /// static data member of class X, names should be looked up in the scope of
5779 /// class X.
5780 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5781
5782 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5783 /// initializer for the declaration 'Dcl'.
5784 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5785
5786 /// Define the "body" of the conversion from a lambda object to a
5787 /// function pointer.
5788 ///
5789 /// This routine doesn't actually define a sensible body; rather, it fills
5790 /// in the initialization expression needed to copy the lambda object into
5791 /// the block, and IR generation actually generates the real body of the
5792 /// block pointer conversion.
5793 void
5794 DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc,
5795 CXXConversionDecl *Conv);
5796
5797 /// Define the "body" of the conversion from a lambda object to a
5798 /// block pointer.
5799 ///
5800 /// This routine doesn't actually define a sensible body; rather, it fills
5801 /// in the initialization expression needed to copy the lambda object into
5802 /// the block, and IR generation actually generates the real body of the
5803 /// block pointer conversion.
5804 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5805 CXXConversionDecl *Conv);
5806
5807 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5808 /// linkage specification, including the language and (if present)
5809 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5810 /// language string literal. LBraceLoc, if valid, provides the location of
5811 /// the '{' brace. Otherwise, this linkage specification does not
5812 /// have any braces.
5813 Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5814 Expr *LangStr, SourceLocation LBraceLoc);
5815
5816 /// ActOnFinishLinkageSpecification - Complete the definition of
5817 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5818 /// valid, it's the position of the closing '}' brace in a linkage
5819 /// specification that uses braces.
5820 Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec,
5821 SourceLocation RBraceLoc);
5822
5823 //===--------------------------------------------------------------------===//
5824 // C++ Classes
5825 //
5826
5827 /// Get the class that is directly named by the current context. This is the
5828 /// class for which an unqualified-id in this scope could name a constructor
5829 /// or destructor.
5830 ///
5831 /// If the scope specifier denotes a class, this will be that class.
5832 /// If the scope specifier is empty, this will be the class whose
5833 /// member-specification we are currently within. Otherwise, there
5834 /// is no such class.
5835 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
5836
5837 /// isCurrentClassName - Determine whether the identifier II is the
5838 /// name of the class type currently being defined. In the case of
5839 /// nested classes, this will only return true if II is the name of
5840 /// the innermost class.
5841 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5842 const CXXScopeSpec *SS = nullptr);
5843
5844 /// Determine whether the identifier II is a typo for the name of
5845 /// the class type currently being defined. If so, update it to the identifier
5846 /// that should have been used.
5847 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5848
5849 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5850 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
5851 SourceLocation ColonLoc,
5852 const ParsedAttributesView &Attrs);
5853
5854 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5855 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5856 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5857 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5858 /// present (but parsing it has been deferred).
5859 NamedDecl *
5860 ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
5861 MultiTemplateParamsArg TemplateParameterLists,
5862 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5863 InClassInitStyle InitStyle);
5864
5865 /// Enter a new C++ default initializer scope. After calling this, the
5866 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5867 /// parsing or instantiating the initializer failed.
5868 void ActOnStartCXXInClassMemberInitializer();
5869
5870 /// This is invoked after parsing an in-class initializer for a
5871 /// non-static C++ class member, and after instantiating an in-class
5872 /// initializer in a class template. Such actions are deferred until the class
5873 /// is complete.
5874 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5875 SourceLocation EqualLoc,
5876 ExprResult Init);
5877
5878 /// Handle a C++ member initializer using parentheses syntax.
5879 MemInitResult
5880 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
5881 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
5882 const DeclSpec &DS, SourceLocation IdLoc,
5883 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
5884 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
5885
5886 /// Handle a C++ member initializer using braced-init-list syntax.
5887 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
5888 CXXScopeSpec &SS,
5889 IdentifierInfo *MemberOrBase,
5890 ParsedType TemplateTypeTy,
5891 const DeclSpec &DS, SourceLocation IdLoc,
5892 Expr *InitList, SourceLocation EllipsisLoc);
5893
5894 /// Handle a C++ member initializer.
5895 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
5896 CXXScopeSpec &SS,
5897 IdentifierInfo *MemberOrBase,
5898 ParsedType TemplateTypeTy,
5899 const DeclSpec &DS, SourceLocation IdLoc,
5900 Expr *Init, SourceLocation EllipsisLoc);
5901
5902 MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init,
5903 SourceLocation IdLoc);
5904
5905 MemInitResult BuildBaseInitializer(QualType BaseType,
5906 TypeSourceInfo *BaseTInfo, Expr *Init,
5907 CXXRecordDecl *ClassDecl,
5908 SourceLocation EllipsisLoc);
5909
5910 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
5911 CXXRecordDecl *ClassDecl);
5912
5913 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5914 CXXCtorInitializer *Initializer);
5915
5916 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5917 ArrayRef<CXXCtorInitializer *> Initializers = {});
5918
5919 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5920 /// mark all the non-trivial destructors of its members and bases as
5921 /// referenced.
5922 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5923 CXXRecordDecl *Record);
5924
5925 /// Mark destructors of virtual bases of this class referenced. In the Itanium
5926 /// C++ ABI, this is done when emitting a destructor for any non-abstract
5927 /// class. In the Microsoft C++ ABI, this is done any time a class's
5928 /// destructor is referenced.
5929 void MarkVirtualBaseDestructorsReferenced(
5930 SourceLocation Location, CXXRecordDecl *ClassDecl,
5931 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
5932 nullptr);
5933
5934 /// Do semantic checks to allow the complete destructor variant to be emitted
5935 /// when the destructor is defined in another translation unit. In the Itanium
5936 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
5937 /// can be emitted in separate TUs. To emit the complete variant, run a subset
5938 /// of the checks performed when emitting a regular destructor.
5939 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
5940 CXXDestructorDecl *Dtor);
5941
5942 /// The list of classes whose vtables have been used within
5943 /// this translation unit, and the source locations at which the
5944 /// first use occurred.
5945 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
5946
5947 /// The list of vtables that are required but have not yet been
5948 /// materialized.
5949 SmallVector<VTableUse, 16> VTableUses;
5950
5951 /// The set of classes whose vtables have been used within
5952 /// this translation unit, and a bit that will be true if the vtable is
5953 /// required to be emitted (otherwise, it should be emitted only if needed
5954 /// by code generation).
5955 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5956
5957 /// Load any externally-stored vtable uses.
5958 void LoadExternalVTableUses();
5959
5960 /// Note that the vtable for the given class was used at the
5961 /// given location.
5962 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5963 bool DefinitionRequired = false);
5964
5965 /// Mark the exception specifications of all virtual member functions
5966 /// in the given class as needed.
5967 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5968 const CXXRecordDecl *RD);
5969
5970 /// MarkVirtualMembersReferenced - Will mark all members of the given
5971 /// CXXRecordDecl referenced.
5972 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
5973 bool ConstexprOnly = false);
5974
5975 /// Define all of the vtables that have been used in this
5976 /// translation unit and reference any virtual members used by those
5977 /// vtables.
5978 ///
5979 /// \returns true if any work was done, false otherwise.
5980 bool DefineUsedVTables();
5981
5982 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5983 /// special functions, such as the default constructor, copy
5984 /// constructor, or destructor, to the given C++ class (C++
5985 /// [special]p1). This routine can only be executed just before the
5986 /// definition of the class is complete.
5987 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5988
5989 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5990 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
5991 ArrayRef<CXXCtorInitializer *> MemInits,
5992 bool AnyErrors);
5993
5994 /// Check class-level dllimport/dllexport attribute. The caller must
5995 /// ensure that referenceDLLExportedClassMethods is called some point later
5996 /// when all outer classes of Class are complete.
5997 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5998 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
5999
6000 void referenceDLLExportedClassMethods();
6001
6002 /// Perform propagation of DLL attributes from a derived class to a
6003 /// templated base class for MS compatibility.
6004 void propagateDLLAttrToBaseClassTemplate(
6005 CXXRecordDecl *Class, Attr *ClassAttr,
6006 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6007 SourceLocation BaseLoc);
6008
6009 /// Perform semantic checks on a class definition that has been
6010 /// completing, introducing implicitly-declared members, checking for
6011 /// abstract types, etc.
6012 ///
6013 /// \param S The scope in which the class was parsed. Null if we didn't just
6014 /// parse a class definition.
6015 /// \param Record The completed class.
6016 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
6017
6018 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6019 /// conditions that are needed for the attribute to have an effect.
6020 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6021
6022 /// Check that VTable Pointer authentication is only being set on the first
6023 /// first instantiation of the vtable
6024 void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD);
6025
6026 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6027 Decl *TagDecl, SourceLocation LBrac,
6028 SourceLocation RBrac,
6029 const ParsedAttributesView &AttrList);
6030
6031 /// Perform any semantic analysis which needs to be delayed until all
6032 /// pending class member declarations have been parsed.
6033 void ActOnFinishCXXMemberDecls();
6034 void ActOnFinishCXXNonNestedClass();
6035
6036 /// This is used to implement the constant expression evaluation part of the
6037 /// attribute enable_if extension. There is nothing in standard C++ which
6038 /// would require reentering parameters.
6039 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6040 unsigned ActOnReenterTemplateScope(Decl *Template,
6041 llvm::function_ref<Scope *()> EnterScope);
6042 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6043
6044 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6045 /// parsing a top-level (non-nested) C++ class, and we are now
6046 /// parsing those parts of the given Method declaration that could
6047 /// not be parsed earlier (C++ [class.mem]p2), such as default
6048 /// arguments. This action should enter the scope of the given
6049 /// Method declaration as if we had just parsed the qualified method
6050 /// name. However, it should not bring the parameters into scope;
6051 /// that will be performed by ActOnDelayedCXXMethodParameter.
6052 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6053 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6054 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6055
6056 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6057 /// processing the delayed method declaration for Method. The method
6058 /// declaration is now considered finished. There may be a separate
6059 /// ActOnStartOfFunctionDef action later (not necessarily
6060 /// immediately!) for this method, if it was also defined inside the
6061 /// class body.
6062 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6063 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6064
6065 enum class StringEvaluationContext { StaticAssert = 0, Asm = 1 };
6066
6067 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
6068 StringEvaluationContext EvalContext,
6069 bool ErrorOnInvalidMessage);
6070 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
6071 StringEvaluationContext EvalContext,
6072 bool ErrorOnInvalidMessage);
6073
6074 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6075 Expr *AssertExpr, Expr *AssertMessageExpr,
6076 SourceLocation RParenLoc);
6077 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6078 Expr *AssertExpr, Expr *AssertMessageExpr,
6079 SourceLocation RParenLoc, bool Failed);
6080
6081 /// Try to print more useful information about a failed static_assert
6082 /// with expression \E
6083 void DiagnoseStaticAssertDetails(const Expr *E);
6084
6085 /// If E represents a built-in type trait, or a known standard type trait,
6086 /// try to print more information about why the type type-trait failed.
6087 /// This assumes we already evaluated the expression to a false boolean value.
6088 void DiagnoseTypeTraitDetails(const Expr *E);
6089
6090 /// Handle a friend type declaration. This works in tandem with
6091 /// ActOnTag.
6092 ///
6093 /// Notes on friend class templates:
6094 ///
6095 /// We generally treat friend class declarations as if they were
6096 /// declaring a class. So, for example, the elaborated type specifier
6097 /// in a friend declaration is required to obey the restrictions of a
6098 /// class-head (i.e. no typedefs in the scope chain), template
6099 /// parameters are required to match up with simple template-ids, &c.
6100 /// However, unlike when declaring a template specialization, it's
6101 /// okay to refer to a template specialization without an empty
6102 /// template parameter declaration, e.g.
6103 /// friend class A<T>::B<unsigned>;
6104 /// We permit this as a special case; if there are any template
6105 /// parameters present at all, require proper matching, i.e.
6106 /// template <> template \<class T> friend class A<int>::B;
6107 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6108 MultiTemplateParamsArg TemplateParams,
6109 SourceLocation EllipsisLoc);
6110 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6111 MultiTemplateParamsArg TemplateParams);
6112
6113 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6114 /// the well-formedness of the constructor declarator @p D with type @p
6115 /// R. If there are any errors in the declarator, this routine will
6116 /// emit diagnostics and set the invalid bit to true. In any case, the type
6117 /// will be updated to reflect a well-formed type for the constructor and
6118 /// returned.
6119 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6120 StorageClass &SC);
6121
6122 /// CheckConstructor - Checks a fully-formed constructor for
6123 /// well-formedness, issuing any diagnostics required. Returns true if
6124 /// the constructor declarator is invalid.
6125 void CheckConstructor(CXXConstructorDecl *Constructor);
6126
6127 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6128 /// the well-formednes of the destructor declarator @p D with type @p
6129 /// R. If there are any errors in the declarator, this routine will
6130 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6131 /// will be updated to reflect a well-formed type for the destructor and
6132 /// returned.
6133 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6134 StorageClass &SC);
6135
6136 /// CheckDestructor - Checks a fully-formed destructor definition for
6137 /// well-formedness, issuing any diagnostics required. Returns true
6138 /// on error.
6139 bool CheckDestructor(CXXDestructorDecl *Destructor);
6140
6141 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6142 /// well-formednes of the conversion function declarator @p D with
6143 /// type @p R. If there are any errors in the declarator, this routine
6144 /// will emit diagnostics and return true. Otherwise, it will return
6145 /// false. Either way, the type @p R will be updated to reflect a
6146 /// well-formed type for the conversion operator.
6147 void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC);
6148
6149 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6150 /// the declaration of the given C++ conversion function. This routine
6151 /// is responsible for recording the conversion function in the C++
6152 /// class, if possible.
6153 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6154
6155 /// Check the validity of a declarator that we parsed for a deduction-guide.
6156 /// These aren't actually declarators in the grammar, so we need to check that
6157 /// the user didn't specify any pieces that are not part of the
6158 /// deduction-guide grammar. Return true on invalid deduction-guide.
6159 bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6160 StorageClass &SC);
6161
6162 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6163
6164 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6165 CXXSpecialMemberKind CSM,
6166 SourceLocation DefaultLoc);
6167 void CheckDelayedMemberExceptionSpecs();
6168
6169 /// Kinds of defaulted comparison operator functions.
6170 enum class DefaultedComparisonKind : unsigned char {
6171 /// This is not a defaultable comparison operator.
6172 None,
6173 /// This is an operator== that should be implemented as a series of
6174 /// subobject comparisons.
6175 Equal,
6176 /// This is an operator<=> that should be implemented as a series of
6177 /// subobject comparisons.
6178 ThreeWay,
6179 /// This is an operator!= that should be implemented as a rewrite in terms
6180 /// of a == comparison.
6181 NotEqual,
6182 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
6183 /// terms of a <=> comparison.
6184 Relational,
6185 };
6186
6187 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6188 DefaultedComparisonKind DCK);
6189 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6190 FunctionDecl *Spaceship);
6191 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6192 DefaultedComparisonKind DCK);
6193
6194 void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name,
6195 QualType R, bool IsLambda,
6196 DeclContext *DC = nullptr);
6197 void CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
6198 DeclarationName Name, QualType R);
6199 void CheckExplicitObjectLambda(Declarator &D);
6200
6201 //===--------------------------------------------------------------------===//
6202 // C++ Derived Classes
6203 //
6204
6205 /// Check the validity of a C++ base class specifier.
6206 ///
6207 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6208 /// and returns NULL otherwise.
6209 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6210 SourceRange SpecifierRange, bool Virtual,
6211 AccessSpecifier Access,
6212 TypeSourceInfo *TInfo,
6213 SourceLocation EllipsisLoc);
6214
6215 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6216 /// one entry in the base class list of a class specifier, for
6217 /// example:
6218 /// class foo : public bar, virtual private baz {
6219 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6220 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6221 const ParsedAttributesView &Attrs, bool Virtual,
6222 AccessSpecifier Access, ParsedType basetype,
6223 SourceLocation BaseLoc,
6224 SourceLocation EllipsisLoc);
6225
6226 /// Performs the actual work of attaching the given base class
6227 /// specifiers to a C++ class.
6228 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6229 MutableArrayRef<CXXBaseSpecifier *> Bases);
6230
6231 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6232 /// class, after checking whether there are any duplicate base
6233 /// classes.
6234 void ActOnBaseSpecifiers(Decl *ClassDecl,
6235 MutableArrayRef<CXXBaseSpecifier *> Bases);
6236
6237 /// Determine whether the type \p Derived is a C++ class that is
6238 /// derived from the type \p Base.
6239 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6240 CXXRecordDecl *Base, CXXBasePaths &Paths);
6241 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6242 CXXRecordDecl *Base);
6243 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6244 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6245 CXXBasePaths &Paths);
6246
6247 // FIXME: I don't like this name.
6248 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6249
6250 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6251 SourceLocation Loc, SourceRange Range,
6252 CXXCastPath *BasePath = nullptr,
6253 bool IgnoreAccess = false);
6254
6255 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6256 /// conversion (where Derived and Base are class types) is
6257 /// well-formed, meaning that the conversion is unambiguous (and
6258 /// that all of the base classes are accessible). Returns true
6259 /// and emits a diagnostic if the code is ill-formed, returns false
6260 /// otherwise. Loc is the location where this routine should point to
6261 /// if there is an error, and Range is the source range to highlight
6262 /// if there is an error.
6263 ///
6264 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6265 /// diagnostic for the respective type of error will be suppressed, but the
6266 /// check for ill-formed code will still be performed.
6267 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6268 unsigned InaccessibleBaseID,
6269 unsigned AmbiguousBaseConvID,
6270 SourceLocation Loc, SourceRange Range,
6271 DeclarationName Name, CXXCastPath *BasePath,
6272 bool IgnoreAccess = false);
6273
6274 /// Builds a string representing ambiguous paths from a
6275 /// specific derived class to different subobjects of the same base
6276 /// class.
6277 ///
6278 /// This function builds a string that can be used in error messages
6279 /// to show the different paths that one can take through the
6280 /// inheritance hierarchy to go from the derived class to different
6281 /// subobjects of a base class. The result looks something like this:
6282 /// @code
6283 /// struct D -> struct B -> struct A
6284 /// struct D -> struct C -> struct A
6285 /// @endcode
6286 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6287
6288 bool CheckOverridingFunctionAttributes(CXXMethodDecl *New,
6289 const CXXMethodDecl *Old);
6290
6291 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6292 /// covariant, according to C++ [class.virtual]p5.
6293 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6294 const CXXMethodDecl *Old);
6295
6296 // Check that the overriding method has no explicit object parameter.
6297 bool CheckExplicitObjectOverride(CXXMethodDecl *New,
6298 const CXXMethodDecl *Old);
6299
6300 /// Mark the given method pure.
6301 ///
6302 /// \param Method the method to be marked pure.
6303 ///
6304 /// \param InitRange the source range that covers the "0" initializer.
6305 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6306
6307 /// CheckOverrideControl - Check C++11 override control semantics.
6308 void CheckOverrideControl(NamedDecl *D);
6309
6310 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6311 /// not used in the declaration of an overriding method.
6312 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
6313
6314 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6315 /// function overrides a virtual member function marked 'final', according to
6316 /// C++11 [class.virtual]p4.
6317 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6318 const CXXMethodDecl *Old);
6319
6320 enum AbstractDiagSelID {
6321 AbstractNone = -1,
6322 AbstractReturnType,
6323 AbstractParamType,
6324 AbstractVariableType,
6325 AbstractFieldType,
6326 AbstractIvarType,
6327 AbstractSynthesizedIvarType,
6328 AbstractArrayType
6329 };
6330
6331 struct TypeDiagnoser;
6332
6333 bool isAbstractType(SourceLocation Loc, QualType T);
6334 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6335 TypeDiagnoser &Diagnoser);
6336 template <typename... Ts>
6337 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6338 const Ts &...Args) {
6339 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6340 return RequireNonAbstractType(Loc, T, Diagnoser);
6341 }
6342
6343 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6344
6345 //===--------------------------------------------------------------------===//
6346 // C++ Overloaded Operators [C++ 13.5]
6347 //
6348
6349 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6350 /// of this overloaded operator is well-formed. If so, returns false;
6351 /// otherwise, emits appropriate diagnostics and returns true.
6352 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6353
6354 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6355 /// of this literal operator function is well-formed. If so, returns
6356 /// false; otherwise, emits appropriate diagnostics and returns true.
6357 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6358
6359 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6360 /// found in an explicit(bool) specifier.
6361 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
6362
6363 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6364 /// Returns true if the explicit specifier is now resolved.
6365 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
6366
6367 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6368 /// C++ if/switch/while/for statement.
6369 /// e.g: "if (int x = f()) {...}"
6370 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
6371
6372 // Emitting members of dllexported classes is delayed until the class
6373 // (including field initializers) is fully parsed.
6374 SmallVector<CXXRecordDecl *, 4> DelayedDllExportClasses;
6375 SmallVector<CXXMethodDecl *, 4> DelayedDllExportMemberFunctions;
6376
6377 /// Merge the exception specifications of two variable declarations.
6378 ///
6379 /// This is called when there's a redeclaration of a VarDecl. The function
6380 /// checks if the redeclaration might have an exception specification and
6381 /// validates compatibility and merges the specs if necessary.
6382 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
6383
6384 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6385 /// function, once we already know that they have the same
6386 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6387 /// error, false otherwise.
6388 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
6389
6390 /// Helpers for dealing with blocks and functions.
6391 void CheckCXXDefaultArguments(FunctionDecl *FD);
6392
6393 /// CheckExtraCXXDefaultArguments - Check for any extra default
6394 /// arguments in the declarator, which is not a function declaration
6395 /// or definition and therefore is not permitted to have default
6396 /// arguments. This routine should be invoked for every declarator
6397 /// that is not a function declaration or definition.
6398 void CheckExtraCXXDefaultArguments(Declarator &D);
6399
6400 CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD) {
6401 return getDefaultedFunctionKind(FD: MD).asSpecialMember();
6402 }
6403
6404 /// Perform semantic analysis for the variable declaration that
6405 /// occurs within a C++ catch clause, returning the newly-created
6406 /// variable.
6407 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
6408 SourceLocation StartLoc,
6409 SourceLocation IdLoc,
6410 const IdentifierInfo *Id);
6411
6412 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6413 /// handler.
6414 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
6415
6416 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
6417
6418 /// Handle a friend tag declaration where the scope specifier was
6419 /// templated.
6420 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6421 unsigned TagSpec, SourceLocation TagLoc,
6422 CXXScopeSpec &SS, IdentifierInfo *Name,
6423 SourceLocation NameLoc,
6424 SourceLocation EllipsisLoc,
6425 const ParsedAttributesView &Attr,
6426 MultiTemplateParamsArg TempParamLists);
6427
6428 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
6429 SourceLocation DeclStart, Declarator &D,
6430 Expr *BitfieldWidth,
6431 InClassInitStyle InitStyle,
6432 AccessSpecifier AS,
6433 const ParsedAttr &MSPropertyAttr);
6434
6435 /// Diagnose why the specified class does not have a trivial special member of
6436 /// the given kind.
6437 void DiagnoseNontrivial(const CXXRecordDecl *Record,
6438 CXXSpecialMemberKind CSM);
6439
6440 /// Determine whether a defaulted or deleted special member function is
6441 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6442 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6443 bool SpecialMemberIsTrivial(
6444 CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
6445 TrivialABIHandling TAH = TrivialABIHandling::IgnoreTrivialABI,
6446 bool Diagnose = false);
6447
6448 /// For a defaulted function, the kind of defaulted function that it is.
6449 class DefaultedFunctionKind {
6450 LLVM_PREFERRED_TYPE(CXXSpecialMemberKind)
6451 unsigned SpecialMember : 8;
6452 unsigned Comparison : 8;
6453
6454 public:
6455 DefaultedFunctionKind()
6456 : SpecialMember(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid)),
6457 Comparison(llvm::to_underlying(E: DefaultedComparisonKind::None)) {}
6458 DefaultedFunctionKind(CXXSpecialMemberKind CSM)
6459 : SpecialMember(llvm::to_underlying(E: CSM)),
6460 Comparison(llvm::to_underlying(E: DefaultedComparisonKind::None)) {}
6461 DefaultedFunctionKind(DefaultedComparisonKind Comp)
6462 : SpecialMember(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid)),
6463 Comparison(llvm::to_underlying(E: Comp)) {}
6464
6465 bool isSpecialMember() const {
6466 return static_cast<CXXSpecialMemberKind>(SpecialMember) !=
6467 CXXSpecialMemberKind::Invalid;
6468 }
6469 bool isComparison() const {
6470 return static_cast<DefaultedComparisonKind>(Comparison) !=
6471 DefaultedComparisonKind::None;
6472 }
6473
6474 explicit operator bool() const {
6475 return isSpecialMember() || isComparison();
6476 }
6477
6478 CXXSpecialMemberKind asSpecialMember() const {
6479 return static_cast<CXXSpecialMemberKind>(SpecialMember);
6480 }
6481 DefaultedComparisonKind asComparison() const {
6482 return static_cast<DefaultedComparisonKind>(Comparison);
6483 }
6484
6485 /// Get the index of this function kind for use in diagnostics.
6486 unsigned getDiagnosticIndex() const {
6487 static_assert(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid) >
6488 llvm::to_underlying(E: CXXSpecialMemberKind::Destructor),
6489 "invalid should have highest index");
6490 static_assert((unsigned)DefaultedComparisonKind::None == 0,
6491 "none should be equal to zero");
6492 return SpecialMember + Comparison;
6493 }
6494 };
6495
6496 /// Determine the kind of defaulting that would be done for a given function.
6497 ///
6498 /// If the function is both a default constructor and a copy / move
6499 /// constructor (due to having a default argument for the first parameter),
6500 /// this picks CXXSpecialMemberKind::DefaultConstructor.
6501 ///
6502 /// FIXME: Check that case is properly handled by all callers.
6503 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
6504
6505 /// Handle a C++11 empty-declaration and attribute-declaration.
6506 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
6507 SourceLocation SemiLoc);
6508
6509 enum class CheckConstexprKind {
6510 /// Diagnose issues that are non-constant or that are extensions.
6511 Diagnose,
6512 /// Identify whether this function satisfies the formal rules for constexpr
6513 /// functions in the current lanugage mode (with no extensions).
6514 CheckValid
6515 };
6516
6517 // Check whether a function declaration satisfies the requirements of a
6518 // constexpr function definition or a constexpr constructor definition. If so,
6519 // return true. If not, produce appropriate diagnostics (unless asked not to
6520 // by Kind) and return false.
6521 //
6522 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6523 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
6524 CheckConstexprKind Kind);
6525
6526 /// Diagnose methods which overload virtual methods in a base class
6527 /// without overriding any.
6528 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
6529
6530 /// Check if a method overloads virtual methods in a base class without
6531 /// overriding any.
6532 void
6533 FindHiddenVirtualMethods(CXXMethodDecl *MD,
6534 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6535 void
6536 NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6537 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6538
6539 /// ActOnParamDefaultArgument - Check whether the default argument
6540 /// provided for a function parameter is well-formed. If so, attach it
6541 /// to the parameter declaration.
6542 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6543 Expr *defarg);
6544
6545 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6546 /// argument for a function parameter, but we can't parse it yet
6547 /// because we're inside a class definition. Note that this default
6548 /// argument will be parsed later.
6549 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
6550 SourceLocation ArgLoc);
6551
6552 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6553 /// the default argument for the parameter param failed.
6554 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
6555 Expr *DefaultArg);
6556 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6557 SourceLocation EqualLoc);
6558 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6559 SourceLocation EqualLoc);
6560
6561 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6562 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6563 StringLiteral *Message = nullptr);
6564 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
6565
6566 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6567 StringLiteral *DeletedMessage = nullptr);
6568 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
6569 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
6570 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
6571
6572 NamedDecl *
6573 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
6574 MultiTemplateParamsArg TemplateParamLists);
6575 void DiagPlaceholderVariableDefinition(SourceLocation Loc);
6576 bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
6577 RecordDecl *ClassDecl,
6578 const IdentifierInfo *Name);
6579
6580 UnsignedOrNone GetDecompositionElementCount(QualType DecompType,
6581 SourceLocation Loc);
6582 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
6583
6584 /// Stack containing information needed when in C++2a an 'auto' is encountered
6585 /// in a function declaration parameter type specifier in order to invent a
6586 /// corresponding template parameter in the enclosing abbreviated function
6587 /// template. This information is also present in LambdaScopeInfo, stored in
6588 /// the FunctionScopes stack.
6589 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
6590
6591 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6592 std::unique_ptr<CXXFieldCollector> FieldCollector;
6593
6594 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
6595 /// Set containing all declared private fields that are not used.
6596 NamedDeclSetType UnusedPrivateFields;
6597
6598 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> RecordDeclSetTy;
6599
6600 /// PureVirtualClassDiagSet - a set of class declarations which we have
6601 /// emitted a list of pure virtual functions. Used to prevent emitting the
6602 /// same list more than once.
6603 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6604
6605 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
6606 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
6607 DelegatingCtorDeclsType;
6608
6609 /// All the delegating constructors seen so far in the file, used for
6610 /// cycle detection at the end of the TU.
6611 DelegatingCtorDeclsType DelegatingCtorDecls;
6612
6613 /// The C++ "std" namespace, where the standard library resides.
6614 LazyDeclPtr StdNamespace;
6615
6616 /// The C++ "std::initializer_list" template, which is defined in
6617 /// \<initializer_list>.
6618 ClassTemplateDecl *StdInitializerList;
6619
6620 /// The C++ "std::type_identity" template, which is defined in
6621 /// \<type_traits>.
6622 ClassTemplateDecl *StdTypeIdentity;
6623
6624 // Contains the locations of the beginning of unparsed default
6625 // argument locations.
6626 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6627
6628 /// UndefinedInternals - all the used, undefined objects which require a
6629 /// definition in this translation unit.
6630 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6631
6632 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6633 SpecialMemberDecl;
6634
6635 /// The C++ special members which we are currently in the process of
6636 /// declaring. If this process recursively triggers the declaration of the
6637 /// same special member, we should act as if it is not yet declared.
6638 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
6639
6640 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
6641
6642 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6643
6644 typedef ProcessingContextState ParsingClassState;
6645 ParsingClassState PushParsingClass() {
6646 ParsingClassDepth++;
6647 return DelayedDiagnostics.pushUndelayed();
6648 }
6649 void PopParsingClass(ParsingClassState state) {
6650 ParsingClassDepth--;
6651 DelayedDiagnostics.popUndelayed(state);
6652 }
6653
6654 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
6655 CXXScopeSpec &SS,
6656 ParsedType TemplateTypeTy,
6657 IdentifierInfo *MemberOrBase);
6658
6659private:
6660 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6661 QualType ResultTy,
6662 ArrayRef<QualType> Args);
6663 // Helper for ActOnFields to check for all function pointer members.
6664 bool EntirelyFunctionPointers(const RecordDecl *Record);
6665
6666 // A cache representing if we've fully checked the various comparison category
6667 // types stored in ASTContext. The bit-index corresponds to the integer value
6668 // of a ComparisonCategoryType enumerator.
6669 llvm::SmallBitVector FullyCheckedComparisonCategories;
6670
6671 /// Check if there is a field shadowing.
6672 void CheckShadowInheritedFields(const SourceLocation &Loc,
6673 DeclarationName FieldName,
6674 const CXXRecordDecl *RD,
6675 bool DeclIsField = true);
6676
6677 ///@}
6678
6679 //
6680 //
6681 // -------------------------------------------------------------------------
6682 //
6683 //
6684
6685 /// \name C++ Exception Specifications
6686 /// Implementations are in SemaExceptionSpec.cpp
6687 ///@{
6688
6689public:
6690 /// All the overriding functions seen during a class definition
6691 /// that had their exception spec checks delayed, plus the overridden
6692 /// function.
6693 SmallVector<std::pair<const CXXMethodDecl *, const CXXMethodDecl *>, 2>
6694 DelayedOverridingExceptionSpecChecks;
6695
6696 /// All the function redeclarations seen during a class definition that had
6697 /// their exception spec checks delayed, plus the prior declaration they
6698 /// should be checked against. Except during error recovery, the new decl
6699 /// should always be a friend declaration, as that's the only valid way to
6700 /// redeclare a special member before its class is complete.
6701 SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 2>
6702 DelayedEquivalentExceptionSpecChecks;
6703
6704 /// Determine if we're in a case where we need to (incorrectly) eagerly
6705 /// parse an exception specification to work around a libstdc++ bug.
6706 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6707
6708 /// Check the given noexcept-specifier, convert its expression, and compute
6709 /// the appropriate ExceptionSpecificationType.
6710 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6711 ExceptionSpecificationType &EST);
6712
6713 CanThrowResult canThrow(const Stmt *E);
6714 /// Determine whether the callee of a particular function call can throw.
6715 /// E, D and Loc are all optional.
6716 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6717 SourceLocation Loc = SourceLocation());
6718 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
6719 const FunctionProtoType *FPT);
6720 void UpdateExceptionSpec(FunctionDecl *FD,
6721 const FunctionProtoType::ExceptionSpecInfo &ESI);
6722
6723 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6724 /// exception specification. Incomplete types, or pointers to incomplete types
6725 /// other than void are not allowed.
6726 ///
6727 /// \param[in,out] T The exception type. This will be decayed to a pointer
6728 /// type
6729 /// when the input is an array or a function type.
6730 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
6731
6732 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6733 /// pointer to member to a function with an exception specification. This
6734 /// means that it is invalid to add another level of indirection.
6735 bool CheckDistantExceptionSpec(QualType T);
6736 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
6737
6738 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6739 /// exception specifications. Exception specifications are equivalent if
6740 /// they allow exactly the same set of exception types. It does not matter how
6741 /// that is achieved. See C++ [except.spec]p2.
6742 bool CheckEquivalentExceptionSpec(const FunctionProtoType *Old,
6743 SourceLocation OldLoc,
6744 const FunctionProtoType *New,
6745 SourceLocation NewLoc);
6746 bool CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
6747 const PartialDiagnostic &NoteID,
6748 const FunctionProtoType *Old,
6749 SourceLocation OldLoc,
6750 const FunctionProtoType *New,
6751 SourceLocation NewLoc);
6752 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6753
6754 /// CheckExceptionSpecSubset - Check whether the second function type's
6755 /// exception specification is a subset (or equivalent) of the first function
6756 /// type. This is used by override and pointer assignment checks.
6757 bool CheckExceptionSpecSubset(
6758 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6759 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6760 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6761 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6762 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6763
6764 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6765 /// two functions have equivalent exception specs. This is part of the
6766 /// assignment and override compatibility check. We do not check the
6767 /// parameters of parameter function pointers recursively, as no sane
6768 /// programmer would even be able to write such a function type.
6769 bool CheckParamExceptionSpec(
6770 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6771 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6772 SourceLocation TargetLoc, const FunctionProtoType *Source,
6773 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6774
6775 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6776
6777 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6778 /// spec is a subset of base spec.
6779 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6780 const CXXMethodDecl *Old);
6781
6782 ///@}
6783
6784 //
6785 //
6786 // -------------------------------------------------------------------------
6787 //
6788 //
6789
6790 /// \name Expressions
6791 /// Implementations are in SemaExpr.cpp
6792 ///@{
6793
6794public:
6795 /// Describes how the expressions currently being parsed are
6796 /// evaluated at run-time, if at all.
6797 enum class ExpressionEvaluationContext {
6798 /// The current expression and its subexpressions occur within an
6799 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6800 /// \c sizeof, where the type of the expression may be significant but
6801 /// no code will be generated to evaluate the value of the expression at
6802 /// run time.
6803 Unevaluated,
6804
6805 /// The current expression occurs within a braced-init-list within
6806 /// an unevaluated operand. This is mostly like a regular unevaluated
6807 /// context, except that we still instantiate constexpr functions that are
6808 /// referenced here so that we can perform narrowing checks correctly.
6809 UnevaluatedList,
6810
6811 /// The current expression occurs within a discarded statement.
6812 /// This behaves largely similarly to an unevaluated operand in preventing
6813 /// definitions from being required, but not in other ways.
6814 DiscardedStatement,
6815
6816 /// The current expression occurs within an unevaluated
6817 /// operand that unconditionally permits abstract references to
6818 /// fields, such as a SIZE operator in MS-style inline assembly.
6819 UnevaluatedAbstract,
6820
6821 /// The current context is "potentially evaluated" in C++11 terms,
6822 /// but the expression is evaluated at compile-time (like the values of
6823 /// cases in a switch statement).
6824 ConstantEvaluated,
6825
6826 /// In addition of being constant evaluated, the current expression
6827 /// occurs in an immediate function context - either a consteval function
6828 /// or a consteval if statement.
6829 ImmediateFunctionContext,
6830
6831 /// The current expression is potentially evaluated at run time,
6832 /// which means that code may be generated to evaluate the value of the
6833 /// expression at run time.
6834 PotentiallyEvaluated,
6835
6836 /// The current expression is potentially evaluated, but any
6837 /// declarations referenced inside that expression are only used if
6838 /// in fact the current expression is used.
6839 ///
6840 /// This value is used when parsing default function arguments, for which
6841 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6842 /// through varargs) but do not want to mark declarations as "referenced"
6843 /// until the default argument is used.
6844 PotentiallyEvaluatedIfUsed
6845 };
6846
6847 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6848 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6849 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6850 /// have been applied to all subexpressions of the enclosing full expression.
6851 /// This is cleared at the end of each full expression.
6852 using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>;
6853 MaybeODRUseExprSet MaybeODRUseExprs;
6854
6855 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6856
6857 /// Data structure used to record current or nested
6858 /// expression evaluation contexts.
6859 struct ExpressionEvaluationContextRecord {
6860 /// The expression evaluation context.
6861 ExpressionEvaluationContext Context;
6862
6863 /// Whether the enclosing context needed a cleanup.
6864 CleanupInfo ParentCleanup;
6865
6866 /// The number of active cleanup objects when we entered
6867 /// this expression evaluation context.
6868 unsigned NumCleanupObjects;
6869
6870 MaybeODRUseExprSet SavedMaybeODRUseExprs;
6871
6872 /// The lambdas that are present within this context, if it
6873 /// is indeed an unevaluated context.
6874 SmallVector<LambdaExpr *, 2> Lambdas;
6875
6876 /// The declaration that provides context for lambda expressions
6877 /// and block literals if the normal declaration context does not
6878 /// suffice, e.g., in a default function argument.
6879 Decl *ManglingContextDecl;
6880
6881 /// Declaration for initializer if one is currently being
6882 /// parsed. Used when an expression has a possibly unreachable
6883 /// diagnostic to reference the declaration as a whole.
6884 VarDecl *DeclForInitializer = nullptr;
6885
6886 /// If we are processing a decltype type, a set of call expressions
6887 /// for which we have deferred checking the completeness of the return type.
6888 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
6889
6890 /// If we are processing a decltype type, a set of temporary binding
6891 /// expressions for which we have deferred checking the destructor.
6892 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
6893
6894 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
6895
6896 /// Expressions appearing as the LHS of a volatile assignment in this
6897 /// context. We produce a warning for these when popping the context if
6898 /// they are not discarded-value expressions nor unevaluated operands.
6899 SmallVector<Expr *, 2> VolatileAssignmentLHSs;
6900
6901 /// Set of candidates for starting an immediate invocation.
6902 llvm::SmallVector<ImmediateInvocationCandidate, 4>
6903 ImmediateInvocationCandidates;
6904
6905 /// Set of DeclRefExprs referencing a consteval function when used in a
6906 /// context not already known to be immediately invoked.
6907 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
6908
6909 /// P2718R0 - Lifetime extension in range-based for loops.
6910 /// MaterializeTemporaryExprs in for-range-init expressions which need to
6911 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6912 /// InLifetimeExtendingContext is true.
6913 SmallVector<MaterializeTemporaryExpr *, 8> ForRangeLifetimeExtendTemps;
6914
6915 /// Small set of gathered accesses to potentially misaligned members
6916 /// due to the packed attribute.
6917 SmallVector<MisalignedMember, 4> MisalignedMembers;
6918
6919 /// \brief Describes whether we are in an expression constext which we have
6920 /// to handle differently.
6921 enum ExpressionKind {
6922 EK_Decltype,
6923 EK_TemplateArgument,
6924 EK_AttrArgument,
6925 EK_VariableInit,
6926 EK_Other
6927 } ExprContext;
6928
6929 // A context can be nested in both a discarded statement context and
6930 // an immediate function context, so they need to be tracked independently.
6931 bool InDiscardedStatement;
6932 bool InImmediateFunctionContext;
6933 bool InImmediateEscalatingFunctionContext;
6934
6935 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
6936
6937 // We are in a constant context, but we also allow
6938 // non constant expressions, for example for array bounds (which may be
6939 // VLAs).
6940 bool InConditionallyConstantEvaluateContext = false;
6941
6942 /// Whether we are currently in a context in which all temporaries must be
6943 /// lifetime-extended, even if they're not bound to a reference (for
6944 /// example, in a for-range initializer).
6945 bool InLifetimeExtendingContext = false;
6946
6947 /// Whether evaluating an expression for a switch case label.
6948 bool IsCaseExpr = false;
6949
6950 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
6951 bool RebuildDefaultArgOrDefaultInit = false;
6952
6953 // When evaluating immediate functions in the initializer of a default
6954 // argument or default member initializer, this is the declaration whose
6955 // default initializer is being evaluated and the location of the call
6956 // or constructor definition.
6957 struct InitializationContext {
6958 InitializationContext(SourceLocation Loc, ValueDecl *Decl,
6959 DeclContext *Context)
6960 : Loc(Loc), Decl(Decl), Context(Context) {
6961 assert(Decl && Context && "invalid initialization context");
6962 }
6963
6964 SourceLocation Loc;
6965 ValueDecl *Decl = nullptr;
6966 DeclContext *Context = nullptr;
6967 };
6968 std::optional<InitializationContext> DelayedDefaultInitializationContext;
6969
6970 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
6971 unsigned NumCleanupObjects,
6972 CleanupInfo ParentCleanup,
6973 Decl *ManglingContextDecl,
6974 ExpressionKind ExprContext)
6975 : Context(Context), ParentCleanup(ParentCleanup),
6976 NumCleanupObjects(NumCleanupObjects),
6977 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
6978 InDiscardedStatement(false), InImmediateFunctionContext(false),
6979 InImmediateEscalatingFunctionContext(false) {}
6980
6981 bool isUnevaluated() const {
6982 return Context == ExpressionEvaluationContext::Unevaluated ||
6983 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
6984 Context == ExpressionEvaluationContext::UnevaluatedList;
6985 }
6986
6987 bool isPotentiallyEvaluated() const {
6988 return Context == ExpressionEvaluationContext::PotentiallyEvaluated ||
6989 Context ==
6990 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed ||
6991 Context == ExpressionEvaluationContext::ConstantEvaluated;
6992 }
6993
6994 bool isConstantEvaluated() const {
6995 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
6996 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
6997 }
6998
6999 bool isImmediateFunctionContext() const {
7000 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
7001 (Context == ExpressionEvaluationContext::DiscardedStatement &&
7002 InImmediateFunctionContext) ||
7003 // C++23 [expr.const]p14:
7004 // An expression or conversion is in an immediate function
7005 // context if it is potentially evaluated and either:
7006 // * its innermost enclosing non-block scope is a function
7007 // parameter scope of an immediate function, or
7008 // * its enclosing statement is enclosed by the compound-
7009 // statement of a consteval if statement.
7010 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
7011 InImmediateFunctionContext);
7012 }
7013
7014 bool isDiscardedStatementContext() const {
7015 return Context == ExpressionEvaluationContext::DiscardedStatement ||
7016 ((Context ==
7017 ExpressionEvaluationContext::ImmediateFunctionContext ||
7018 isPotentiallyEvaluated()) &&
7019 InDiscardedStatement);
7020 }
7021 };
7022
7023 const ExpressionEvaluationContextRecord &currentEvaluationContext() const {
7024 assert(!ExprEvalContexts.empty() &&
7025 "Must be in an expression evaluation context");
7026 return ExprEvalContexts.back();
7027 }
7028
7029 ExpressionEvaluationContextRecord &currentEvaluationContext() {
7030 assert(!ExprEvalContexts.empty() &&
7031 "Must be in an expression evaluation context");
7032 return ExprEvalContexts.back();
7033 }
7034
7035 ExpressionEvaluationContextRecord &parentEvaluationContext() {
7036 assert(ExprEvalContexts.size() >= 2 &&
7037 "Must be in an expression evaluation context");
7038 return ExprEvalContexts[ExprEvalContexts.size() - 2];
7039 }
7040
7041 const ExpressionEvaluationContextRecord &parentEvaluationContext() const {
7042 return const_cast<Sema *>(this)->parentEvaluationContext();
7043 }
7044
7045 bool isAttrContext() const {
7046 return ExprEvalContexts.back().ExprContext ==
7047 ExpressionEvaluationContextRecord::ExpressionKind::EK_AttrArgument;
7048 }
7049
7050 /// Increment when we find a reference; decrement when we find an ignored
7051 /// assignment. Ultimately the value is 0 if every reference is an ignored
7052 /// assignment.
7053 ///
7054 /// Uses canonical VarDecl as key so in-class decls and out-of-class defs of
7055 /// static data members get tracked as a single entry.
7056 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
7057
7058 /// Used to control the generation of ExprWithCleanups.
7059 CleanupInfo Cleanup;
7060
7061 /// ExprCleanupObjects - This is the stack of objects requiring
7062 /// cleanup that are created by the current full expression.
7063 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
7064
7065 /// Determine whether the use of this declaration is valid, without
7066 /// emitting diagnostics.
7067 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
7068 // A version of DiagnoseUseOfDecl that should be used if overload resolution
7069 // has been used to find this declaration, which means we don't have to bother
7070 // checking the trailing requires clause.
7071 bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) {
7072 return DiagnoseUseOfDecl(
7073 D, Locs: Loc, /*UnknownObjCClass=*/UnknownObjCClass: nullptr, /*ObjCPropertyAccess=*/ObjCPropertyAccess: false,
7074 /*AvoidPartialAvailabilityChecks=*/AvoidPartialAvailabilityChecks: false, /*ClassReceiver=*/ClassReceiver: nullptr,
7075 /*SkipTrailingRequiresClause=*/SkipTrailingRequiresClause: true);
7076 }
7077
7078 /// Determine whether the use of this declaration is valid, and
7079 /// emit any corresponding diagnostics.
7080 ///
7081 /// This routine diagnoses various problems with referencing
7082 /// declarations that can occur when using a declaration. For example,
7083 /// it might warn if a deprecated or unavailable declaration is being
7084 /// used, or produce an error (and return true) if a C++0x deleted
7085 /// function is being used.
7086 ///
7087 /// \returns true if there was an error (this declaration cannot be
7088 /// referenced), false otherwise.
7089 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
7090 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
7091 bool ObjCPropertyAccess = false,
7092 bool AvoidPartialAvailabilityChecks = false,
7093 ObjCInterfaceDecl *ClassReceiver = nullptr,
7094 bool SkipTrailingRequiresClause = false);
7095
7096 /// Emit a note explaining that this function is deleted.
7097 void NoteDeletedFunction(FunctionDecl *FD);
7098
7099 /// DiagnoseSentinelCalls - This routine checks whether a call or
7100 /// message-send is to a declaration with the sentinel attribute, and
7101 /// if so, it checks that the requirements of the sentinel are
7102 /// satisfied.
7103 void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
7104 ArrayRef<Expr *> Args);
7105
7106 void PushExpressionEvaluationContext(
7107 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
7108 ExpressionEvaluationContextRecord::ExpressionKind Type =
7109 ExpressionEvaluationContextRecord::EK_Other);
7110
7111 void PushExpressionEvaluationContextForFunction(
7112 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
7113
7114 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
7115 void PushExpressionEvaluationContext(
7116 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
7117 ExpressionEvaluationContextRecord::ExpressionKind Type =
7118 ExpressionEvaluationContextRecord::EK_Other);
7119 void PopExpressionEvaluationContext();
7120
7121 void DiscardCleanupsInEvaluationContext();
7122
7123 ExprResult TransformToPotentiallyEvaluated(Expr *E);
7124 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
7125 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
7126
7127 /// Check whether E, which is either a discarded-value expression or an
7128 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
7129 /// lvalue, and if so, remove it from the list of volatile-qualified
7130 /// assignments that we are going to warn are deprecated.
7131 void CheckUnusedVolatileAssignment(Expr *E);
7132
7133 ExprResult ActOnConstantExpression(ExprResult Res);
7134
7135 // Functions for marking a declaration referenced. These functions also
7136 // contain the relevant logic for marking if a reference to a function or
7137 // variable is an odr-use (in the C++11 sense). There are separate variants
7138 // for expressions referring to a decl; these exist because odr-use marking
7139 // needs to be delayed for some constant variables when we build one of the
7140 // named expressions.
7141 //
7142 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7143 // should usually be true. This only needs to be set to false if the lack of
7144 // odr-use cannot be determined from the current context (for instance,
7145 // because the name denotes a virtual function and was written without an
7146 // explicit nested-name-specifier).
7147 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7148
7149 /// Mark a function referenced, and check whether it is odr-used
7150 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7151 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
7152 bool MightBeOdrUse = true);
7153
7154 /// Mark a variable referenced, and check whether it is odr-used
7155 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7156 /// used directly for normal expressions referring to VarDecl.
7157 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
7158
7159 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7160 ///
7161 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7162 /// be handled with care if the DeclRefExpr is not newly-created.
7163 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7164
7165 /// Perform reference-marking and odr-use handling for a MemberExpr.
7166 void MarkMemberReferenced(MemberExpr *E);
7167
7168 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7169 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
7170 void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc,
7171 unsigned CapturingScopeIndex);
7172
7173 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
7174 void CleanupVarDeclMarking();
7175
7176 /// Try to capture the given variable.
7177 ///
7178 /// \param Var The variable to capture.
7179 ///
7180 /// \param Loc The location at which the capture occurs.
7181 ///
7182 /// \param Kind The kind of capture, which may be implicit (for either a
7183 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7184 ///
7185 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7186 /// an explicit lambda capture.
7187 ///
7188 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7189 /// captures or diagnose errors. If false, this routine merely check whether
7190 /// the capture can occur without performing the capture itself or complaining
7191 /// if the variable cannot be captured.
7192 ///
7193 /// \param CaptureType Will be set to the type of the field used to capture
7194 /// this variable in the innermost block or lambda. Only valid when the
7195 /// variable can be captured.
7196 ///
7197 /// \param DeclRefType Will be set to the type of a reference to the capture
7198 /// from within the current scope. Only valid when the variable can be
7199 /// captured.
7200 ///
7201 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7202 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7203 /// This is useful when enclosing lambdas must speculatively capture
7204 /// variables that may or may not be used in certain specializations of
7205 /// a nested generic lambda.
7206 ///
7207 /// \returns true if an error occurred (i.e., the variable cannot be
7208 /// captured) and false if the capture succeeded.
7209 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7210 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7211 bool BuildAndDiagnose, QualType &CaptureType,
7212 QualType &DeclRefType,
7213 const unsigned *const FunctionScopeIndexToStopAt);
7214
7215 /// Try to capture the given variable.
7216 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7217 TryCaptureKind Kind = TryCaptureKind::Implicit,
7218 SourceLocation EllipsisLoc = SourceLocation());
7219
7220 /// Checks if the variable must be captured.
7221 bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc);
7222
7223 /// Given a variable, determine the type that a reference to that
7224 /// variable will have in the given scope.
7225 QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc);
7226
7227 /// Mark all of the declarations referenced within a particular AST node as
7228 /// referenced. Used when template instantiation instantiates a non-dependent
7229 /// type -- entities referenced by the type are now referenced.
7230 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
7231
7232 /// Mark any declarations that appear within this expression or any
7233 /// potentially-evaluated subexpressions as "referenced".
7234 ///
7235 /// \param SkipLocalVariables If true, don't mark local variables as
7236 /// 'referenced'.
7237 /// \param StopAt Subexpressions that we shouldn't recurse into.
7238 void MarkDeclarationsReferencedInExpr(Expr *E,
7239 bool SkipLocalVariables = false,
7240 ArrayRef<const Expr *> StopAt = {});
7241
7242 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7243 /// conversion.
7244 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7245
7246 /// Conditionally issue a diagnostic based on the statements's reachability
7247 /// analysis.
7248 ///
7249 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7250 /// the function body is parsed, and then do a basic reachability analysis to
7251 /// determine if the statement is reachable. If it is unreachable, the
7252 /// diagnostic will not be emitted.
7253 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7254 const PartialDiagnostic &PD);
7255
7256 /// Conditionally issue a diagnostic based on the current
7257 /// evaluation context.
7258 ///
7259 /// \param Statement If Statement is non-null, delay reporting the
7260 /// diagnostic until the function body is parsed, and then do a basic
7261 /// reachability analysis to determine if the statement is reachable.
7262 /// If it is unreachable, the diagnostic will not be emitted.
7263 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7264 const PartialDiagnostic &PD);
7265 /// Similar, but diagnostic is only produced if all the specified statements
7266 /// are reachable.
7267 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7268 const PartialDiagnostic &PD);
7269
7270 // Primary Expressions.
7271 SourceRange getExprRange(Expr *E) const;
7272
7273 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7274 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7275 bool HasTrailingLParen, bool IsAddressOfOperand,
7276 CorrectionCandidateCallback *CCC = nullptr,
7277 bool IsInlineAsmIdentifier = false);
7278
7279 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7280 /// possibly a list of template arguments.
7281 ///
7282 /// If this produces template arguments, it is permitted to call
7283 /// DecomposeTemplateName.
7284 ///
7285 /// This actually loses a lot of source location information for
7286 /// non-standard name kinds; we should consider preserving that in
7287 /// some way.
7288 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7289 TemplateArgumentListInfo &Buffer,
7290 DeclarationNameInfo &NameInfo,
7291 const TemplateArgumentListInfo *&TemplateArgs);
7292
7293 /// Diagnose a lookup that found results in an enclosing class during error
7294 /// recovery. This usually indicates that the results were found in a
7295 /// dependent base class that could not be searched as part of a template
7296 /// definition. Always issues a diagnostic (though this may be only a warning
7297 /// in MS compatibility mode).
7298 ///
7299 /// Return \c true if the error is unrecoverable, or \c false if the caller
7300 /// should attempt to recover using these lookup results.
7301 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7302
7303 /// Diagnose an empty lookup.
7304 ///
7305 /// \return false if new lookup candidates were found
7306 bool
7307 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7308 CorrectionCandidateCallback &CCC,
7309 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7310 ArrayRef<Expr *> Args = {},
7311 DeclContext *LookupCtx = nullptr);
7312
7313 /// If \p D cannot be odr-used in the current expression evaluation context,
7314 /// return a reason explaining why. Otherwise, return NOUR_None.
7315 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
7316
7317 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7318 SourceLocation Loc,
7319 const CXXScopeSpec *SS = nullptr);
7320 DeclRefExpr *
7321 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7322 const DeclarationNameInfo &NameInfo,
7323 const CXXScopeSpec *SS = nullptr,
7324 NamedDecl *FoundD = nullptr,
7325 SourceLocation TemplateKWLoc = SourceLocation(),
7326 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7327
7328 /// BuildDeclRefExpr - Build an expression that references a
7329 /// declaration that does not require a closure capture.
7330 DeclRefExpr *
7331 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7332 const DeclarationNameInfo &NameInfo,
7333 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7334 SourceLocation TemplateKWLoc = SourceLocation(),
7335 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7336
7337 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7338 bool HasTrailingLParen);
7339
7340 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7341 /// declaration name, generally during template instantiation.
7342 /// There's a large number of things which don't need to be done along
7343 /// this path.
7344 ExprResult BuildQualifiedDeclarationNameExpr(
7345 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7346 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7347
7348 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7349 bool NeedsADL,
7350 bool AcceptInvalidDecl = false);
7351
7352 /// Complete semantic analysis for a reference to the given declaration.
7353 ExprResult BuildDeclarationNameExpr(
7354 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7355 NamedDecl *FoundD = nullptr,
7356 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7357 bool AcceptInvalidDecl = false);
7358
7359 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7360 // where Tokens representing function local predefined macros (such as
7361 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7362 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7363
7364 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7365 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7366 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7367
7368 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7369
7370 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7371 ExprResult ActOnCharacterConstant(const Token &Tok,
7372 Scope *UDLScope = nullptr);
7373 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7374 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7375 MultiExprArg Val);
7376 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7377 unsigned NumUserSpecifiedExprs,
7378 SourceLocation InitLoc,
7379 SourceLocation LParenLoc,
7380 SourceLocation RParenLoc);
7381
7382 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7383 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7384 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7385 /// from multiple tokens. However, the common case is that StringToks points
7386 /// to one string.
7387 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7388 Scope *UDLScope = nullptr);
7389
7390 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7391
7392 /// ControllingExprOrType is either an opaque pointer coming out of a
7393 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7394 /// into two so we don't take a void *, but that's awkward because one of
7395 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7396 /// itself to generic code very well.
7397 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7398 SourceLocation DefaultLoc,
7399 SourceLocation RParenLoc,
7400 bool PredicateIsExpr,
7401 void *ControllingExprOrType,
7402 ArrayRef<ParsedType> ArgTypes,
7403 ArrayRef<Expr *> ArgExprs);
7404 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7405 /// it'd be better to split this interface into two so we don't take a
7406 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7407 /// isn't a trivial change.
7408 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7409 SourceLocation DefaultLoc,
7410 SourceLocation RParenLoc,
7411 bool PredicateIsExpr,
7412 void *ControllingExprOrType,
7413 ArrayRef<TypeSourceInfo *> Types,
7414 ArrayRef<Expr *> Exprs);
7415
7416 // Binary/Unary Operators. 'Tok' is the token for the operator.
7417 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7418 Expr *InputExpr, bool IsAfterAmp = false);
7419 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7420 Expr *Input, bool IsAfterAmp = false);
7421
7422 /// Unary Operators. 'Tok' is the token for the operator.
7423 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7424 Expr *Input, bool IsAfterAmp = false);
7425
7426 /// Determine whether the given expression is a qualified member
7427 /// access expression, of a form that could be turned into a pointer to member
7428 /// with the address-of operator.
7429 bool isQualifiedMemberAccess(Expr *E);
7430 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7431 const Expr *Op,
7432 const CXXMethodDecl *MD);
7433
7434 /// CheckAddressOfOperand - The operand of & must be either a function
7435 /// designator or an lvalue designating an object. If it is an lvalue, the
7436 /// object cannot be declared with storage class register or be a bit field.
7437 /// Note: The usual conversions are *not* applied to the operand of the &
7438 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7439 /// In C++, the operand might be an overloaded function name, in which case
7440 /// we allow the '&' but retain the overloaded-function type.
7441 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7442
7443 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7444 /// _Alignas(type-name) .
7445 /// [dcl.align] An alignment-specifier of the form
7446 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7447 ///
7448 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7449 /// _Alignas(_Alignof(type-name)).
7450 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7451 SourceLocation OpLoc, SourceRange R);
7452 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7453 SourceLocation OpLoc, SourceRange R);
7454
7455 /// Build a sizeof or alignof expression given a type operand.
7456 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7457 SourceLocation OpLoc,
7458 UnaryExprOrTypeTrait ExprKind,
7459 SourceRange R);
7460
7461 /// Build a sizeof or alignof expression given an expression
7462 /// operand.
7463 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7464 UnaryExprOrTypeTrait ExprKind);
7465
7466 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7467 /// expr and the same for @c alignof and @c __alignof
7468 /// Note that the ArgRange is invalid if isType is false.
7469 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7470 UnaryExprOrTypeTrait ExprKind,
7471 bool IsType, void *TyOrEx,
7472 SourceRange ArgRange);
7473
7474 /// Check for operands with placeholder types and complain if found.
7475 /// Returns ExprError() if there was an error and no recovery was possible.
7476 ExprResult CheckPlaceholderExpr(Expr *E);
7477 bool CheckVecStepExpr(Expr *E);
7478
7479 /// Check the constraints on expression operands to unary type expression
7480 /// and type traits.
7481 ///
7482 /// Completes any types necessary and validates the constraints on the operand
7483 /// expression. The logic mostly mirrors the type-based overload, but may
7484 /// modify the expression as it completes the type for that expression through
7485 /// template instantiation, etc.
7486 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
7487
7488 /// Check the constraints on operands to unary expression and type
7489 /// traits.
7490 ///
7491 /// This will complete any types necessary, and validate the various
7492 /// constraints on those operands.
7493 ///
7494 /// The UsualUnaryConversions() function is *not* called by this routine.
7495 /// C99 6.3.2.1p[2-4] all state:
7496 /// Except when it is the operand of the sizeof operator ...
7497 ///
7498 /// C++ [expr.sizeof]p4
7499 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7500 /// standard conversions are not applied to the operand of sizeof.
7501 ///
7502 /// This policy is followed for all of the unary trait expressions.
7503 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7504 SourceRange ExprRange,
7505 UnaryExprOrTypeTrait ExprKind,
7506 StringRef KWName);
7507
7508 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7509 tok::TokenKind Kind, Expr *Input);
7510
7511 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7512 MultiExprArg ArgExprs,
7513 SourceLocation RLoc);
7514 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7515 Expr *Idx, SourceLocation RLoc);
7516
7517 ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx,
7518 SourceLocation RBLoc);
7519
7520 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7521 Expr *ColumnIdx,
7522 SourceLocation RBLoc);
7523
7524 /// ConvertArgumentsForCall - Converts the arguments specified in
7525 /// Args/NumArgs to the parameter types of the function FDecl with
7526 /// function prototype Proto. Call is the call expression itself, and
7527 /// Fn is the function expression. For a C++ member function, this
7528 /// routine does not attempt to convert the object argument. Returns
7529 /// true if the call is ill-formed.
7530 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7531 const FunctionProtoType *Proto,
7532 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7533 bool ExecConfig = false);
7534
7535 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7536 /// array parameter, check that it is non-null, and that if it is formed by
7537 /// array-to-pointer decay, the underlying array is sufficiently large.
7538 ///
7539 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7540 /// the array type derivation, then for each call to the function, the value
7541 /// of the corresponding actual argument shall provide access to the first
7542 /// element of an array with at least as many elements as specified by the
7543 /// size expression.
7544 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7545 const Expr *ArgExpr);
7546
7547 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7548 /// This provides the location of the left/right parens and a list of comma
7549 /// locations.
7550 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7551 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7552 Expr *ExecConfig = nullptr);
7553
7554 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7555 /// This provides the location of the left/right parens and a list of comma
7556 /// locations.
7557 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7558 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7559 Expr *ExecConfig = nullptr,
7560 bool IsExecConfig = false,
7561 bool AllowRecovery = false);
7562
7563 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7564 // with the specified CallArgs
7565 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7566 MultiExprArg CallArgs);
7567
7568 using ADLCallKind = CallExpr::ADLCallKind;
7569
7570 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7571 /// i.e. an expression not of \p OverloadTy. The expression should
7572 /// unary-convert to an expression of function-pointer or
7573 /// block-pointer type.
7574 ///
7575 /// \param NDecl the declaration being called, if available
7576 ExprResult
7577 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7578 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7579 Expr *Config = nullptr, bool IsExecConfig = false,
7580 ADLCallKind UsesADL = ADLCallKind::NotADL);
7581
7582 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D,
7583 ParsedType &Ty, SourceLocation RParenLoc,
7584 Expr *CastExpr);
7585
7586 /// Prepares for a scalar cast, performing all the necessary stages
7587 /// except the final cast and returning the kind required.
7588 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
7589
7590 /// Build an altivec or OpenCL literal.
7591 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
7592 SourceLocation RParenLoc, Expr *E,
7593 TypeSourceInfo *TInfo);
7594
7595 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7596 /// the ParenListExpr into a sequence of comma binary operators.
7597 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
7598
7599 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7600 SourceLocation RParenLoc, Expr *InitExpr);
7601
7602 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
7603 TypeSourceInfo *TInfo,
7604 SourceLocation RParenLoc,
7605 Expr *LiteralExpr);
7606
7607 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7608 SourceLocation RBraceLoc);
7609
7610 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7611 SourceLocation RBraceLoc, bool IsExplicit);
7612
7613 /// Binary Operators. 'Tok' is the token for the operator.
7614 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind,
7615 Expr *LHSExpr, Expr *RHSExpr);
7616 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7617 Expr *LHSExpr, Expr *RHSExpr,
7618 bool ForFoldExpression = false);
7619
7620 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7621 /// operator @p Opc at location @c TokLoc. This routine only supports
7622 /// built-in operations; ActOnBinOp handles overloaded operators.
7623 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
7624 Expr *LHSExpr, Expr *RHSExpr,
7625 bool ForFoldExpression = false);
7626 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7627 UnresolvedSetImpl &Functions);
7628
7629 /// Look for instances where it is likely the comma operator is confused with
7630 /// another operator. There is an explicit list of acceptable expressions for
7631 /// the left hand side of the comma operator, otherwise emit a warning.
7632 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7633
7634 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7635 /// in the case of a the GNU conditional expr extension.
7636 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
7637 SourceLocation ColonLoc, Expr *CondExpr,
7638 Expr *LHSExpr, Expr *RHSExpr);
7639
7640 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7641 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
7642 LabelDecl *TheDecl);
7643
7644 void ActOnStartStmtExpr();
7645 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7646 SourceLocation RPLoc);
7647 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
7648 SourceLocation RPLoc, unsigned TemplateDepth);
7649 // Handle the final expression in a statement expression.
7650 ExprResult ActOnStmtExprResult(ExprResult E);
7651 void ActOnStmtExprError();
7652
7653 /// __builtin_offsetof(type, a.b[123][456].c)
7654 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
7655 TypeSourceInfo *TInfo,
7656 const Designation &Desig,
7657 SourceLocation RParenLoc);
7658 ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
7659 SourceLocation TypeLoc,
7660 ParsedType ParsedArgTy,
7661 const Designation &Desig,
7662 SourceLocation RParenLoc);
7663
7664 // __builtin_choose_expr(constExpr, expr1, expr2)
7665 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7666 Expr *LHSExpr, Expr *RHSExpr,
7667 SourceLocation RPLoc);
7668
7669 // __builtin_va_arg(expr, type)
7670 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
7671 SourceLocation RPLoc);
7672 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
7673 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7674
7675 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7676 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7677 ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind,
7678 SourceLocation BuiltinLoc,
7679 SourceLocation RPLoc);
7680
7681 // #embed
7682 ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
7683 StringLiteral *BinaryData, StringRef FileName);
7684
7685 // Build a potentially resolved SourceLocExpr.
7686 ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
7687 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7688 DeclContext *ParentContext);
7689
7690 // __null
7691 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
7692
7693 bool CheckCaseExpression(Expr *E);
7694
7695 //===------------------------- "Block" Extension ------------------------===//
7696
7697 /// ActOnBlockStart - This callback is invoked when a block literal is
7698 /// started.
7699 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7700
7701 /// ActOnBlockArguments - This callback allows processing of block arguments.
7702 /// If there are no arguments, this is still invoked.
7703 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7704 Scope *CurScope);
7705
7706 /// ActOnBlockError - If there is an error parsing a block, this callback
7707 /// is invoked to pop the information about the block from the action impl.
7708 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7709
7710 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7711 /// literal was successfully completed. ^(int x){...}
7712 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
7713 Scope *CurScope);
7714
7715 //===---------------------------- Clang Extensions ----------------------===//
7716
7717 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7718 /// provided arguments.
7719 ///
7720 /// __builtin_convertvector( value, dst type )
7721 ///
7722 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7723 SourceLocation BuiltinLoc,
7724 SourceLocation RParenLoc);
7725
7726 //===---------------------------- OpenCL Features -----------------------===//
7727
7728 /// Parse a __builtin_astype expression.
7729 ///
7730 /// __builtin_astype( value, dst type )
7731 ///
7732 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7733 SourceLocation BuiltinLoc,
7734 SourceLocation RParenLoc);
7735
7736 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7737 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
7738 SourceLocation BuiltinLoc,
7739 SourceLocation RParenLoc);
7740
7741 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7742 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
7743 ArrayRef<Expr *> SubExprs,
7744 QualType T = QualType());
7745
7746 /// Cast a base object to a member's actual type.
7747 ///
7748 /// There are two relevant checks:
7749 ///
7750 /// C++ [class.access.base]p7:
7751 ///
7752 /// If a class member access operator [...] is used to access a non-static
7753 /// data member or non-static member function, the reference is ill-formed
7754 /// if the left operand [...] cannot be implicitly converted to a pointer to
7755 /// the naming class of the right operand.
7756 ///
7757 /// C++ [expr.ref]p7:
7758 ///
7759 /// If E2 is a non-static data member or a non-static member function, the
7760 /// program is ill-formed if the class of which E2 is directly a member is
7761 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7762 ///
7763 /// Note that the latter check does not consider access; the access of the
7764 /// "real" base class is checked as appropriate when checking the access of
7765 /// the member name.
7766 ExprResult PerformObjectMemberConversion(Expr *From,
7767 NestedNameSpecifier Qualifier,
7768 NamedDecl *FoundDecl,
7769 NamedDecl *Member);
7770
7771 /// CheckCallReturnType - Checks that a call expression's return type is
7772 /// complete. Returns true on failure. The location passed in is the location
7773 /// that best represents the call.
7774 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7775 CallExpr *CE, FunctionDecl *FD);
7776
7777 /// Emit a warning for all pending noderef expressions that we recorded.
7778 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
7779
7780 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
7781
7782 /// Instantiate or parse a C++ default argument expression as necessary.
7783 /// Return true on error.
7784 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7785 ParmVarDecl *Param, Expr *Init = nullptr,
7786 bool SkipImmediateInvocations = true);
7787
7788 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7789 /// the default expr if needed.
7790 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7791 ParmVarDecl *Param, Expr *Init = nullptr);
7792
7793 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7794 /// invocation.
7795 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
7796
7797 void MarkExpressionAsImmediateEscalating(Expr *E);
7798
7799 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7800 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7801
7802 /// Abstract base class used for diagnosing integer constant
7803 /// expression violations.
7804 class VerifyICEDiagnoser {
7805 public:
7806 bool Suppress;
7807
7808 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) {}
7809
7810 virtual SemaDiagnosticBuilder
7811 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7812 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7813 SourceLocation Loc) = 0;
7814 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
7815 virtual ~VerifyICEDiagnoser() {}
7816 };
7817
7818 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7819 /// and reports the appropriate diagnostics. Returns false on success.
7820 /// Can optionally return the value of the expression.
7821 ExprResult
7822 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7823 VerifyICEDiagnoser &Diagnoser,
7824 AllowFoldKind CanFold = AllowFoldKind::No);
7825 ExprResult
7826 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7827 unsigned DiagID,
7828 AllowFoldKind CanFold = AllowFoldKind::No);
7829 ExprResult
7830 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7831 AllowFoldKind CanFold = AllowFoldKind::No);
7832 ExprResult
7833 VerifyIntegerConstantExpression(Expr *E,
7834 AllowFoldKind CanFold = AllowFoldKind::No) {
7835 return VerifyIntegerConstantExpression(E, Result: nullptr, CanFold);
7836 }
7837
7838 /// DiagnoseAssignmentAsCondition - Given that an expression is
7839 /// being used as a boolean condition, warn if it's an assignment.
7840 void DiagnoseAssignmentAsCondition(Expr *E);
7841
7842 /// Redundant parentheses over an equality comparison can indicate
7843 /// that the user intended an assignment used as condition.
7844 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7845
7846 class FullExprArg {
7847 public:
7848 FullExprArg() : E(nullptr) {}
7849 FullExprArg(Sema &actions) : E(nullptr) {}
7850
7851 ExprResult release() { return E; }
7852
7853 Expr *get() const { return E; }
7854
7855 Expr *operator->() { return E; }
7856
7857 private:
7858 // FIXME: No need to make the entire Sema class a friend when it's just
7859 // Sema::MakeFullExpr that needs access to the constructor below.
7860 friend class Sema;
7861
7862 explicit FullExprArg(Expr *expr) : E(expr) {}
7863
7864 Expr *E;
7865 };
7866
7867 FullExprArg MakeFullExpr(Expr *Arg) {
7868 return MakeFullExpr(Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation());
7869 }
7870 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
7871 return FullExprArg(
7872 ActOnFinishFullExpr(Expr: Arg, CC, /*DiscardedValue*/ DiscardedValue: false).get());
7873 }
7874 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
7875 ExprResult FE =
7876 ActOnFinishFullExpr(Expr: Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation(),
7877 /*DiscardedValue*/ DiscardedValue: true);
7878 return FullExprArg(FE.get());
7879 }
7880
7881 class ConditionResult {
7882 Decl *ConditionVar;
7883 ExprResult Condition;
7884 bool Invalid;
7885 std::optional<bool> KnownValue;
7886
7887 friend class Sema;
7888 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7889 bool IsConstexpr)
7890 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7891 if (IsConstexpr && Condition.get()) {
7892 if (std::optional<llvm::APSInt> Val =
7893 Condition.get()->getIntegerConstantExpr(Ctx: S.Context)) {
7894 KnownValue = !!(*Val);
7895 }
7896 }
7897 }
7898 explicit ConditionResult(bool Invalid)
7899 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7900 KnownValue(std::nullopt) {}
7901
7902 public:
7903 ConditionResult() : ConditionResult(false) {}
7904 bool isInvalid() const { return Invalid; }
7905 std::pair<VarDecl *, Expr *> get() const {
7906 return std::make_pair(x: cast_or_null<VarDecl>(Val: ConditionVar),
7907 y: Condition.get());
7908 }
7909 std::optional<bool> getKnownValue() const { return KnownValue; }
7910 };
7911 static ConditionResult ConditionError() { return ConditionResult(true); }
7912
7913 /// CheckBooleanCondition - Diagnose problems involving the use of
7914 /// the given expression as a boolean condition (e.g. in an if
7915 /// statement). Also performs the standard function and array
7916 /// decays, possibly changing the input variable.
7917 ///
7918 /// \param Loc - A location associated with the condition, e.g. the
7919 /// 'if' keyword.
7920 /// \return true iff there were any errors
7921 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
7922 bool IsConstexpr = false);
7923
7924 enum class ConditionKind {
7925 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
7926 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
7927 Switch ///< An integral condition for a 'switch' statement.
7928 };
7929
7930 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
7931 ConditionKind CK, bool MissingOK = false);
7932
7933 QualType CheckConditionalOperands( // C99 6.5.15
7934 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
7935 ExprObjectKind &OK, SourceLocation QuestionLoc);
7936
7937 /// Emit a specialized diagnostic when one expression is a null pointer
7938 /// constant and the other is not a pointer. Returns true if a diagnostic is
7939 /// emitted.
7940 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7941 SourceLocation QuestionLoc);
7942
7943 /// type checking for vector binary operators.
7944 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7945 SourceLocation Loc, bool IsCompAssign,
7946 bool AllowBothBool, bool AllowBoolConversion,
7947 bool AllowBoolOperation, bool ReportInvalid);
7948
7949 /// Return a signed ext_vector_type that is of identical size and number of
7950 /// elements. For floating point vectors, return an integer type of identical
7951 /// size and number of elements. In the non ext_vector_type case, search from
7952 /// the largest type to the smallest type to avoid cases where long long ==
7953 /// long, where long gets picked over long long.
7954 QualType GetSignedVectorType(QualType V);
7955 QualType GetSignedSizelessVectorType(QualType V);
7956
7957 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7958 /// operates on extended vector types. Instead of producing an IntTy result,
7959 /// like a scalar comparison, a vector comparison produces a vector of integer
7960 /// types.
7961 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7962 SourceLocation Loc,
7963 BinaryOperatorKind Opc);
7964 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7965 SourceLocation Loc,
7966 BinaryOperatorKind Opc);
7967 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7968 SourceLocation Loc,
7969 BinaryOperatorKind Opc);
7970 QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7971 SourceLocation Loc,
7972 BinaryOperatorKind Opc);
7973 // type checking for sizeless vector binary operators.
7974 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
7975 SourceLocation Loc, bool IsCompAssign,
7976 ArithConvKind OperationKind);
7977
7978 /// Type checking for matrix binary operators.
7979 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
7980 SourceLocation Loc,
7981 bool IsCompAssign);
7982 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
7983 SourceLocation Loc, bool IsCompAssign);
7984
7985 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
7986 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
7987 /// VLST) allowed?
7988 ///
7989 /// This will also return false if the two given types do not make sense from
7990 /// the perspective of SVE bitcasts.
7991 bool isValidSveBitcast(QualType srcType, QualType destType);
7992
7993 /// Are the two types matrix types and do they have the same dimensions i.e.
7994 /// do they have the same number of rows and the same number of columns?
7995 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
7996
7997 bool areVectorTypesSameSize(QualType srcType, QualType destType);
7998
7999 /// Are the two types lax-compatible vector types? That is, given
8000 /// that one of them is a vector, do they have equal storage sizes,
8001 /// where the storage size is the number of elements times the element
8002 /// size?
8003 ///
8004 /// This will also return false if either of the types is neither a
8005 /// vector nor a real type.
8006 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
8007
8008 /// Is this a legal conversion between two types, one of which is
8009 /// known to be a vector type?
8010 bool isLaxVectorConversion(QualType srcType, QualType destType);
8011
8012 // This returns true if at least one of the types is an altivec vector.
8013 bool anyAltivecTypes(QualType srcType, QualType destType);
8014
8015 // type checking C++ declaration initializers (C++ [dcl.init]).
8016
8017 /// Check a cast of an unknown-any type. We intentionally only
8018 /// trigger this for C-style casts.
8019 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8020 Expr *CastExpr, CastKind &CastKind,
8021 ExprValueKind &VK, CXXCastPath &Path);
8022
8023 /// Force an expression with unknown-type to an expression of the
8024 /// given type.
8025 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8026
8027 /// Type-check an expression that's being passed to an
8028 /// __unknown_anytype parameter.
8029 ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result,
8030 QualType &paramType);
8031
8032 // CheckMatrixCast - Check type constraints for matrix casts.
8033 // We allow casting between matrixes of the same dimensions i.e. when they
8034 // have the same number of rows and column. Returns true if the cast is
8035 // invalid.
8036 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8037 CastKind &Kind);
8038
8039 // CheckVectorCast - check type constraints for vectors.
8040 // Since vectors are an extension, there are no C standard reference for this.
8041 // We allow casting between vectors and integer datatypes of the same size.
8042 // returns true if the cast is invalid
8043 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8044 CastKind &Kind);
8045
8046 /// Prepare `SplattedExpr` for a vector splat operation, adding
8047 /// implicit casts if necessary.
8048 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8049
8050 /// Prepare `SplattedExpr` for a matrix splat operation, adding
8051 /// implicit casts if necessary.
8052 ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr);
8053
8054 // CheckExtVectorCast - check type constraints for extended vectors.
8055 // Since vectors are an extension, there are no C standard reference for this.
8056 // We allow casting between vectors and integer datatypes of the same size,
8057 // or vectors and the element type of that vector.
8058 // returns the cast expr
8059 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8060 CastKind &Kind);
8061
8062 QualType PreferredConditionType(ConditionKind K) const {
8063 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
8064 }
8065
8066 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
8067 // functions and arrays to their respective pointers (C99 6.3.2.1), and
8068 // promotes floating-piont types according to the language semantics.
8069 ExprResult UsualUnaryConversions(Expr *E);
8070
8071 // UsualUnaryFPConversions - promotes floating-point types according to the
8072 // current language semantics.
8073 ExprResult UsualUnaryFPConversions(Expr *E);
8074
8075 /// CallExprUnaryConversions - a special case of an unary conversion
8076 /// performed on a function designator of a call expression.
8077 ExprResult CallExprUnaryConversions(Expr *E);
8078
8079 // DefaultFunctionArrayConversion - converts functions and arrays
8080 // to their respective pointers (C99 6.3.2.1).
8081 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8082
8083 // DefaultFunctionArrayLvalueConversion - converts functions and
8084 // arrays to their respective pointers and performs the
8085 // lvalue-to-rvalue conversion.
8086 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8087 bool Diagnose = true);
8088
8089 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8090 // the operand. This function is a no-op if the operand has a function type
8091 // or an array type.
8092 ExprResult DefaultLvalueConversion(Expr *E);
8093
8094 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8095 // do not have a prototype. Integer promotions are performed on each
8096 // argument, and arguments that have type float are promoted to double.
8097 ExprResult DefaultArgumentPromotion(Expr *E);
8098
8099 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8100 const FunctionProtoType *Proto,
8101 Expr *Fn);
8102
8103 /// Determine the degree of POD-ness for an expression.
8104 /// Incomplete types are considered POD, since this check can be performed
8105 /// when we're in an unevaluated context.
8106 VarArgKind isValidVarArgType(const QualType &Ty);
8107
8108 /// Check to see if the given expression is a valid argument to a variadic
8109 /// function, issuing a diagnostic if not.
8110 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8111
8112 /// GatherArgumentsForCall - Collector argument expressions for various
8113 /// form of call prototypes.
8114 bool GatherArgumentsForCall(
8115 SourceLocation CallLoc, FunctionDecl *FDecl,
8116 const FunctionProtoType *Proto, unsigned FirstParam,
8117 ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs,
8118 VariadicCallType CallType = VariadicCallType::DoesNotApply,
8119 bool AllowExplicit = false, bool IsListInitialization = false);
8120
8121 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8122 // will create a runtime trap if the resulting type is not a POD type.
8123 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8124 FunctionDecl *FDecl);
8125
8126 // Check that the usual arithmetic conversions can be performed on this pair
8127 // of expressions that might be of enumeration type.
8128 void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc,
8129 ArithConvKind ACK);
8130
8131 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8132 // operands and then handles various conversions that are common to binary
8133 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8134 // routine returns the first non-arithmetic type found. The client is
8135 // responsible for emitting appropriate error diagnostics.
8136 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8137 SourceLocation Loc, ArithConvKind ACK);
8138
8139 bool IsAssignConvertCompatible(AssignConvertType ConvTy) {
8140 switch (ConvTy) {
8141 default:
8142 return false;
8143 case AssignConvertType::Compatible:
8144 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
8145 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
8146 return true;
8147 }
8148 llvm_unreachable("impossible");
8149 }
8150
8151 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8152 /// assignment conversion type specified by ConvTy. This returns true if the
8153 /// conversion was invalid or false if the conversion was accepted.
8154 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc,
8155 QualType DstType, QualType SrcType,
8156 Expr *SrcExpr, AssignmentAction Action,
8157 bool *Complained = nullptr);
8158
8159 /// CheckAssignmentConstraints - Perform type checking for assignment,
8160 /// argument passing, variable initialization, and function return values.
8161 /// C99 6.5.16.
8162 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8163 QualType LHSType,
8164 QualType RHSType);
8165
8166 /// Check assignment constraints and optionally prepare for a conversion of
8167 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8168 /// is true.
8169 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8170 ExprResult &RHS, CastKind &Kind,
8171 bool ConvertRHS = true);
8172
8173 /// Check assignment constraints for an assignment of RHS to LHSType.
8174 ///
8175 /// \param LHSType The destination type for the assignment.
8176 /// \param RHS The source expression for the assignment.
8177 /// \param Diagnose If \c true, diagnostics may be produced when checking
8178 /// for assignability. If a diagnostic is produced, \p RHS will be
8179 /// set to ExprError(). Note that this function may still return
8180 /// without producing a diagnostic, even for an invalid assignment.
8181 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8182 /// in an audited Core Foundation API and does not need to be checked
8183 /// for ARC retain issues.
8184 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8185 /// conversions necessary to perform the assignment. If \c false,
8186 /// \p Diagnose must also be \c false.
8187 AssignConvertType CheckSingleAssignmentConstraints(
8188 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8189 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8190
8191 // If the lhs type is a transparent union, check whether we
8192 // can initialize the transparent union with the given expression.
8193 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8194 ExprResult &RHS);
8195
8196 /// the following "Check" methods will return a valid/converted QualType
8197 /// or a null QualType (indicating an error diagnostic was issued).
8198
8199 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8200 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8201 ExprResult &RHS);
8202
8203 /// Diagnose cases where a scalar was implicitly converted to a vector and
8204 /// diagnose the underlying types. Otherwise, diagnose the error
8205 /// as invalid vector logical operands for non-C++ cases.
8206 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8207 ExprResult &RHS);
8208
8209 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8210 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8211 BinaryOperatorKind Opc);
8212 QualType CheckRemainderOperands( // C99 6.5.5
8213 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8214 bool IsCompAssign = false);
8215 QualType CheckAdditionOperands( // C99 6.5.6
8216 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8217 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8218 QualType CheckSubtractionOperands( // C99 6.5.6
8219 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8220 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8221 QualType CheckShiftOperands( // C99 6.5.7
8222 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8223 BinaryOperatorKind Opc, bool IsCompAssign = false);
8224 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
8225 QualType CheckCompareOperands( // C99 6.5.8/9
8226 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8227 BinaryOperatorKind Opc);
8228 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8229 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8230 BinaryOperatorKind Opc);
8231 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8232 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8233 BinaryOperatorKind Opc);
8234 // CheckAssignmentOperands is used for both simple and compound assignment.
8235 // For simple assignment, pass both expressions and a null converted type.
8236 // For compound assignment, pass both expressions and the converted type.
8237 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8238 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8239 BinaryOperatorKind Opc);
8240
8241 /// To be used for checking whether the arguments being passed to
8242 /// function exceeds the number of parameters expected for it.
8243 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8244 bool PartialOverloading = false) {
8245 // We check whether we're just after a comma in code-completion.
8246 if (NumArgs > 0 && PartialOverloading)
8247 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8248 return NumArgs > NumParams;
8249 }
8250
8251 /// Whether the AST is currently being rebuilt to correct immediate
8252 /// invocations. Immediate invocation candidates and references to consteval
8253 /// functions aren't tracked when this is set.
8254 bool RebuildingImmediateInvocation = false;
8255
8256 bool isAlwaysConstantEvaluatedContext() const {
8257 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8258 return (Ctx.isConstantEvaluated() || isConstantEvaluatedOverride) &&
8259 !Ctx.InConditionallyConstantEvaluateContext;
8260 }
8261
8262 /// Determines whether we are currently in a context that
8263 /// is not evaluated as per C++ [expr] p5.
8264 bool isUnevaluatedContext() const {
8265 return currentEvaluationContext().isUnevaluated();
8266 }
8267
8268 bool isImmediateFunctionContext() const {
8269 return currentEvaluationContext().isImmediateFunctionContext();
8270 }
8271
8272 bool isInLifetimeExtendingContext() const {
8273 return currentEvaluationContext().InLifetimeExtendingContext;
8274 }
8275
8276 bool needsRebuildOfDefaultArgOrInit() const {
8277 return currentEvaluationContext().RebuildDefaultArgOrDefaultInit;
8278 }
8279
8280 bool isCheckingDefaultArgumentOrInitializer() const {
8281 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8282 return (Ctx.Context ==
8283 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) ||
8284 Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
8285 }
8286
8287 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8288 InnermostDeclarationWithDelayedImmediateInvocations() const {
8289 assert(!ExprEvalContexts.empty() &&
8290 "Must be in an expression evaluation context");
8291 for (const auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8292 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8293 Ctx.DelayedDefaultInitializationContext)
8294 return Ctx.DelayedDefaultInitializationContext;
8295 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8296 Ctx.isUnevaluated())
8297 break;
8298 }
8299 return std::nullopt;
8300 }
8301
8302 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8303 OutermostDeclarationWithDelayedImmediateInvocations() const {
8304 assert(!ExprEvalContexts.empty() &&
8305 "Must be in an expression evaluation context");
8306 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8307 for (auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8308 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8309 !Ctx.DelayedDefaultInitializationContext && Res)
8310 break;
8311 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8312 Ctx.isUnevaluated())
8313 break;
8314 Res = Ctx.DelayedDefaultInitializationContext;
8315 }
8316 return Res;
8317 }
8318
8319 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
8320 return getDefaultedFunctionKind(FD).asComparison();
8321 }
8322
8323 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8324 /// SelfAssigned when inside a CXXMethodDecl.
8325 const FieldDecl *
8326 getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
8327
8328 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
8329
8330 template <typename... Ts>
8331 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
8332 const Ts &...Args) {
8333 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8334 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8335 }
8336
8337 template <typename... Ts>
8338 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8339 const Ts &...Args) {
8340 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8341 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
8342 }
8343
8344 /// Abstract class used to diagnose incomplete types.
8345 struct TypeDiagnoser {
8346 TypeDiagnoser() {}
8347
8348 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8349 virtual ~TypeDiagnoser() {}
8350 };
8351
8352 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8353 protected:
8354 unsigned DiagID;
8355 std::tuple<const Ts &...> Args;
8356
8357 template <std::size_t... Is>
8358 void emit(const SemaDiagnosticBuilder &DB,
8359 std::index_sequence<Is...>) const {
8360 // Apply all tuple elements to the builder in order.
8361 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8362 (void)Dummy;
8363 }
8364
8365 public:
8366 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8367 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8368 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8369 }
8370
8371 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8372 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8373 emit(DB, std::index_sequence_for<Ts...>());
8374 DB << T;
8375 }
8376 };
8377
8378 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8379 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8380 /// For example, a diagnostic with no other parameters would generally have
8381 /// the form "...%select{incomplete|sizeless}0 type %1...".
8382 template <typename... Ts>
8383 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
8384 public:
8385 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8386 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8387
8388 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8389 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8390 this->emit(DB, std::index_sequence_for<Ts...>());
8391 DB << T->isSizelessType() << T;
8392 }
8393 };
8394
8395 /// Check an argument list for placeholders that we won't try to
8396 /// handle later.
8397 bool CheckArgsForPlaceholders(MultiExprArg args);
8398
8399 /// The C++ "std::source_location::__impl" struct, defined in
8400 /// \<source_location>.
8401 RecordDecl *StdSourceLocationImplDecl;
8402
8403 /// A stack of expression evaluation contexts.
8404 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
8405
8406 // Set of failed immediate invocations to avoid double diagnosing.
8407 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
8408
8409 /// List of SourceLocations where 'self' is implicitly retained inside a
8410 /// block.
8411 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
8412 ImplicitlyRetainedSelfLocs;
8413
8414 /// Do an explicit extend of the given block pointer if we're in ARC.
8415 void maybeExtendBlockObject(ExprResult &E);
8416
8417 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8418 SourceLocation LocationOfExcessPrecisionNotSatisfied;
8419 void DiagnosePrecisionLossInComplexDivision();
8420
8421private:
8422 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8423
8424 /// Methods for marking which expressions involve dereferencing a pointer
8425 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8426 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8427 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8428 /// `*p`, but need to check that `address of` is called on it. This requires
8429 /// keeping a container of all pending expressions and checking if the address
8430 /// of them are eventually taken.
8431 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8432 void CheckAddressOfNoDeref(const Expr *E);
8433
8434 ///@}
8435
8436 //
8437 //
8438 // -------------------------------------------------------------------------
8439 //
8440 //
8441
8442 /// \name C++ Expressions
8443 /// Implementations are in SemaExprCXX.cpp
8444 ///@{
8445
8446public:
8447 /// The C++ "std::bad_alloc" class, which is defined by the C++
8448 /// standard library.
8449 LazyDeclPtr StdBadAlloc;
8450
8451 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8452 /// standard library.
8453 LazyDeclPtr StdAlignValT;
8454
8455 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
8456 RecordDecl *CXXTypeInfoDecl;
8457
8458 /// A flag to remember whether the implicit forms of operator new and delete
8459 /// have been declared.
8460 bool GlobalNewDeleteDeclared;
8461
8462 /// Delete-expressions to be analyzed at the end of translation unit
8463 ///
8464 /// This list contains class members, and locations of delete-expressions
8465 /// that could not be proven as to whether they mismatch with new-expression
8466 /// used in initializer of the field.
8467 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8468
8469 /// Handle the result of the special case name lookup for inheriting
8470 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8471 /// constructor names in member using declarations, even if 'X' is not the
8472 /// name of the corresponding type.
8473 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
8474 SourceLocation NameLoc,
8475 const IdentifierInfo &Name);
8476
8477 ParsedType getConstructorName(const IdentifierInfo &II,
8478 SourceLocation NameLoc, Scope *S,
8479 CXXScopeSpec &SS, bool EnteringContext);
8480 ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc,
8481 Scope *S, CXXScopeSpec &SS,
8482 ParsedType ObjectType, bool EnteringContext);
8483
8484 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
8485 ParsedType ObjectType);
8486
8487 /// Build a C++ typeid expression with a type operand.
8488 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8489 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8490
8491 /// Build a C++ typeid expression with an expression operand.
8492 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8493 Expr *Operand, SourceLocation RParenLoc);
8494
8495 /// ActOnCXXTypeid - Parse typeid( something ).
8496 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
8497 bool isType, void *TyOrExpr,
8498 SourceLocation RParenLoc);
8499
8500 /// Build a Microsoft __uuidof expression with a type operand.
8501 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8502 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8503
8504 /// Build a Microsoft __uuidof expression with an expression operand.
8505 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8506 Expr *Operand, SourceLocation RParenLoc);
8507
8508 /// ActOnCXXUuidof - Parse __uuidof( something ).
8509 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
8510 bool isType, void *TyOrExpr,
8511 SourceLocation RParenLoc);
8512
8513 //// ActOnCXXThis - Parse 'this' pointer.
8514 ExprResult ActOnCXXThis(SourceLocation Loc);
8515
8516 /// Check whether the type of 'this' is valid in the current context.
8517 bool CheckCXXThisType(SourceLocation Loc, QualType Type);
8518
8519 /// Build a CXXThisExpr and mark it referenced in the current context.
8520 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8521 void MarkThisReferenced(CXXThisExpr *This);
8522
8523 /// Try to retrieve the type of the 'this' pointer.
8524 ///
8525 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8526 QualType getCurrentThisType();
8527
8528 /// When non-NULL, the C++ 'this' expression is allowed despite the
8529 /// current context not being a non-static member function. In such cases,
8530 /// this provides the type used for 'this'.
8531 QualType CXXThisTypeOverride;
8532
8533 /// RAII object used to temporarily allow the C++ 'this' expression
8534 /// to be used, with the given qualifiers on the current class type.
8535 class CXXThisScopeRAII {
8536 Sema &S;
8537 QualType OldCXXThisTypeOverride;
8538 bool Enabled;
8539
8540 public:
8541 /// Introduce a new scope where 'this' may be allowed (when enabled),
8542 /// using the given declaration (which is either a class template or a
8543 /// class) along with the given qualifiers.
8544 /// along with the qualifiers placed on '*this'.
8545 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8546 bool Enabled = true);
8547
8548 ~CXXThisScopeRAII();
8549 CXXThisScopeRAII(const CXXThisScopeRAII &) = delete;
8550 CXXThisScopeRAII &operator=(const CXXThisScopeRAII &) = delete;
8551 };
8552
8553 /// Make sure the value of 'this' is actually available in the current
8554 /// context, if it is a potentially evaluated context.
8555 ///
8556 /// \param Loc The location at which the capture of 'this' occurs.
8557 ///
8558 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8559 /// capture list.
8560 ///
8561 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8562 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8563 /// This is useful when enclosing lambdas must speculatively capture
8564 /// 'this' that may or may not be used in certain specializations of
8565 /// a nested generic lambda (depending on whether the name resolves to
8566 /// a non-static member function or a static function).
8567 /// \return returns 'true' if failed, 'false' if success.
8568 bool CheckCXXThisCapture(
8569 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8570 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8571 bool ByCopy = false);
8572
8573 /// Determine whether the given type is the type of *this that is used
8574 /// outside of the body of a member function for a type that is currently
8575 /// being defined.
8576 bool isThisOutsideMemberFunctionBody(QualType BaseType);
8577
8578 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8579 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
8580
8581 /// Build a boolean-typed literal expression.
8582 ExprResult BuildBoolLiteral(SourceLocation Loc, bool Value);
8583
8584 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8585 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
8586
8587 //// ActOnCXXThrow - Parse throw expressions.
8588 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
8589 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
8590 bool IsThrownVarInScope);
8591
8592 /// CheckCXXThrowOperand - Validate the operand of a throw.
8593 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8594
8595 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8596 /// Can be interpreted either as function-style casting ("int(x)")
8597 /// or class type construction ("ClassType(x,y,z)")
8598 /// or creation of a value-initialized type ("int()").
8599 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
8600 SourceLocation LParenOrBraceLoc,
8601 MultiExprArg Exprs,
8602 SourceLocation RParenOrBraceLoc,
8603 bool ListInitialization);
8604
8605 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
8606 SourceLocation LParenLoc,
8607 MultiExprArg Exprs,
8608 SourceLocation RParenLoc,
8609 bool ListInitialization);
8610
8611 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8612 ///
8613 /// E.g.:
8614 /// @code new (memory) int[size][4] @endcode
8615 /// or
8616 /// @code ::new Foo(23, "hello") @endcode
8617 ///
8618 /// \param StartLoc The first location of the expression.
8619 /// \param UseGlobal True if 'new' was prefixed with '::'.
8620 /// \param PlacementLParen Opening paren of the placement arguments.
8621 /// \param PlacementArgs Placement new arguments.
8622 /// \param PlacementRParen Closing paren of the placement arguments.
8623 /// \param TypeIdParens If the type is in parens, the source range.
8624 /// \param D The type to be allocated, as well as array dimensions.
8625 /// \param Initializer The initializing expression or initializer-list, or
8626 /// null if there is none.
8627 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8628 SourceLocation PlacementLParen,
8629 MultiExprArg PlacementArgs,
8630 SourceLocation PlacementRParen,
8631 SourceRange TypeIdParens, Declarator &D,
8632 Expr *Initializer);
8633 ExprResult
8634 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8635 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8636 SourceRange TypeIdParens, QualType AllocType,
8637 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8638 SourceRange DirectInitRange, Expr *Initializer);
8639
8640 /// Determine whether \p FD is an aligned allocation or deallocation
8641 /// function that is unavailable.
8642 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
8643
8644 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8645 /// function that is unavailable.
8646 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
8647 SourceLocation Loc);
8648
8649 /// Checks that a type is suitable as the allocated type
8650 /// in a new-expression.
8651 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8652 SourceRange R);
8653
8654 /// Finds the overloads of operator new and delete that are appropriate
8655 /// for the allocation.
8656 bool FindAllocationFunctions(
8657 SourceLocation StartLoc, SourceRange Range,
8658 AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope,
8659 QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP,
8660 MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew,
8661 FunctionDecl *&OperatorDelete, bool Diagnose = true);
8662
8663 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8664 /// delete. These are:
8665 /// @code
8666 /// // C++03:
8667 /// void* operator new(std::size_t) throw(std::bad_alloc);
8668 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8669 /// void operator delete(void *) throw();
8670 /// void operator delete[](void *) throw();
8671 /// // C++11:
8672 /// void* operator new(std::size_t);
8673 /// void* operator new[](std::size_t);
8674 /// void operator delete(void *) noexcept;
8675 /// void operator delete[](void *) noexcept;
8676 /// // C++1y:
8677 /// void* operator new(std::size_t);
8678 /// void* operator new[](std::size_t);
8679 /// void operator delete(void *) noexcept;
8680 /// void operator delete[](void *) noexcept;
8681 /// void operator delete(void *, std::size_t) noexcept;
8682 /// void operator delete[](void *, std::size_t) noexcept;
8683 /// @endcode
8684 /// Note that the placement and nothrow forms of new are *not* implicitly
8685 /// declared. Their use requires including \<new\>.
8686 void DeclareGlobalNewDelete();
8687 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
8688 ArrayRef<QualType> Params);
8689
8690 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
8691 DeclarationName Name, FunctionDecl *&Operator,
8692 ImplicitDeallocationParameters,
8693 bool Diagnose = true);
8694 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
8695 ImplicitDeallocationParameters,
8696 DeclarationName Name,
8697 bool Diagnose = true);
8698 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
8699 CXXRecordDecl *RD,
8700 bool Diagnose,
8701 bool LookForGlobal,
8702 DeclarationName Name);
8703
8704 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8705 /// @code ::delete ptr; @endcode
8706 /// or
8707 /// @code delete [] ptr; @endcode
8708 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8709 bool ArrayForm, Expr *Operand);
8710 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
8711 bool IsDelete, bool CallCanBeVirtual,
8712 bool WarnOnNonAbstractTypes,
8713 SourceLocation DtorLoc);
8714
8715 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
8716 Expr *Operand, SourceLocation RParen);
8717 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8718 SourceLocation RParen);
8719
8720 ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base,
8721 SourceLocation OpLoc,
8722 tok::TokenKind OpKind,
8723 ParsedType &ObjectType,
8724 bool &MayBePseudoDestructor);
8725
8726 ExprResult BuildPseudoDestructorExpr(
8727 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8728 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8729 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8730
8731 ExprResult ActOnPseudoDestructorExpr(
8732 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8733 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8734 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8735
8736 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
8737 SourceLocation OpLoc,
8738 tok::TokenKind OpKind,
8739 SourceLocation TildeLoc,
8740 const DeclSpec &DS);
8741
8742 /// MaybeCreateExprWithCleanups - If the current full-expression
8743 /// requires any cleanups, surround it with a ExprWithCleanups node.
8744 /// Otherwise, just returns the passed-in expression.
8745 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
8746 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
8747 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
8748
8749 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8750 return ActOnFinishFullExpr(
8751 Expr, CC: Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8752 }
8753 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
8754 bool DiscardedValue, bool IsConstexpr = false,
8755 bool IsTemplateArgument = false);
8756 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
8757
8758 /// Process the expression contained within a decltype. For such expressions,
8759 /// certain semantic checks on temporaries are delayed until this point, and
8760 /// are omitted for the 'topmost' call in the decltype expression. If the
8761 /// topmost call bound a temporary, strip that temporary off the expression.
8762 ExprResult ActOnDecltypeExpression(Expr *E);
8763
8764 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8765 bool IsUDSuffix);
8766
8767 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
8768
8769 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8770 SourceLocation StmtLoc,
8771 ConditionKind CK);
8772
8773 /// Check the use of the given variable as a C++ condition in an if,
8774 /// while, do-while, or switch statement.
8775 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
8776 SourceLocation StmtLoc, ConditionKind CK);
8777
8778 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8779 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8780
8781 /// Helper function to determine whether this is the (deprecated) C++
8782 /// conversion from a string literal to a pointer to non-const char or
8783 /// non-const wchar_t (for narrow and wide string literals,
8784 /// respectively).
8785 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8786
8787 /// PerformImplicitConversion - Perform an implicit conversion of the
8788 /// expression From to the type ToType using the pre-computed implicit
8789 /// conversion sequence ICS. Returns the converted
8790 /// expression. Action is the kind of conversion we're performing,
8791 /// used in the error message.
8792 ExprResult PerformImplicitConversion(
8793 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8794 AssignmentAction Action,
8795 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
8796
8797 /// PerformImplicitConversion - Perform an implicit conversion of the
8798 /// expression From to the type ToType by following the standard
8799 /// conversion sequence SCS. Returns the converted
8800 /// expression. Flavor is the context in which we're performing this
8801 /// conversion, for use in error messages.
8802 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8803 const StandardConversionSequence &SCS,
8804 AssignmentAction Action,
8805 CheckedConversionKind CCK);
8806
8807 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8808
8809 /// Parsed one of the type trait support pseudo-functions.
8810 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8811 ArrayRef<ParsedType> Args,
8812 SourceLocation RParenLoc);
8813 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8814 ArrayRef<TypeSourceInfo *> Args,
8815 SourceLocation RParenLoc);
8816
8817 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8818 /// pseudo-functions.
8819 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8820 ParsedType LhsTy, Expr *DimExpr,
8821 SourceLocation RParen);
8822
8823 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8824 TypeSourceInfo *TSInfo, Expr *DimExpr,
8825 SourceLocation RParen);
8826
8827 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8828 /// pseudo-functions.
8829 ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8830 Expr *Queried, SourceLocation RParen);
8831
8832 ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8833 Expr *Queried, SourceLocation RParen);
8834
8835 QualType CheckPointerToMemberOperands( // C++ 5.5
8836 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc,
8837 bool isIndirect);
8838 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
8839 ExprResult &RHS,
8840 SourceLocation QuestionLoc);
8841
8842 //// Determines if a type is trivially relocatable
8843 /// according to the C++26 rules.
8844 // FIXME: This is in Sema because it requires
8845 // overload resolution, can we move to ASTContext?
8846 bool IsCXXTriviallyRelocatableType(QualType T);
8847 bool IsCXXTriviallyRelocatableType(const CXXRecordDecl &RD);
8848
8849 /// Check the operands of ?: under C++ semantics.
8850 ///
8851 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8852 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8853 ///
8854 /// This function also implements GCC's vector extension and the
8855 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8856 /// permit the use of a?b:c where the type of a is that of a integer vector
8857 /// with the same number of elements and size as the vectors of b and c. If
8858 /// one of either b or c is a scalar it is implicitly converted to match the
8859 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8860 /// c are scalars, then b and c are checked and converted to the type of a if
8861 /// possible.
8862 ///
8863 /// The expressions are evaluated differently for GCC's and OpenCL's
8864 /// extensions. For the GCC extension, the ?: operator is evaluated as
8865 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8866 /// For the OpenCL extensions, the ?: operator is evaluated as
8867 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8868 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8869 QualType CXXCheckConditionalOperands( // C++ 5.16
8870 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8871 ExprObjectKind &OK, SourceLocation questionLoc);
8872
8873 /// Find a merged pointer type and convert the two expressions to it.
8874 ///
8875 /// This finds the composite pointer type for \p E1 and \p E2 according to
8876 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8877 /// it. It does not emit diagnostics (FIXME: that's not true if \p
8878 /// ConvertArgs is \c true).
8879 ///
8880 /// \param Loc The location of the operator requiring these two expressions to
8881 /// be converted to the composite pointer type.
8882 ///
8883 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8884 /// type.
8885 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8886 bool ConvertArgs = true);
8887 QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1,
8888 ExprResult &E2, bool ConvertArgs = true) {
8889 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8890 QualType Composite =
8891 FindCompositePointerType(Loc, E1&: E1Tmp, E2&: E2Tmp, ConvertArgs);
8892 E1 = E1Tmp;
8893 E2 = E2Tmp;
8894 return Composite;
8895 }
8896
8897 /// MaybeBindToTemporary - If the passed in expression has a record type with
8898 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8899 /// it simply returns the passed in expression.
8900 ExprResult MaybeBindToTemporary(Expr *E);
8901
8902 /// IgnoredValueConversions - Given that an expression's result is
8903 /// syntactically ignored, perform any conversions that are
8904 /// required.
8905 ExprResult IgnoredValueConversions(Expr *E);
8906
8907 ExprResult CheckUnevaluatedOperand(Expr *E);
8908
8909 IfExistsResult
8910 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
8911 const DeclarationNameInfo &TargetNameInfo);
8912
8913 IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S,
8914 SourceLocation KeywordLoc,
8915 bool IsIfExists, CXXScopeSpec &SS,
8916 UnqualifiedId &Name);
8917
8918 RequiresExprBodyDecl *
8919 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8920 ArrayRef<ParmVarDecl *> LocalParameters,
8921 Scope *BodyScope);
8922 void ActOnFinishRequiresExpr();
8923 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8924 concepts::Requirement *ActOnTypeRequirement(SourceLocation TypenameKWLoc,
8925 CXXScopeSpec &SS,
8926 SourceLocation NameLoc,
8927 const IdentifierInfo *TypeName,
8928 TemplateIdAnnotation *TemplateId);
8929 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8930 SourceLocation NoexceptLoc);
8931 concepts::Requirement *ActOnCompoundRequirement(
8932 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8933 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8934 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8935 concepts::ExprRequirement *BuildExprRequirement(
8936 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8937 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8938 concepts::ExprRequirement *BuildExprRequirement(
8939 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8940 bool IsSatisfied, SourceLocation NoexceptLoc,
8941 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8942 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8943 concepts::TypeRequirement *BuildTypeRequirement(
8944 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8945 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8946 concepts::NestedRequirement *
8947 BuildNestedRequirement(StringRef InvalidConstraintEntity,
8948 const ASTConstraintSatisfaction &Satisfaction);
8949 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8950 RequiresExprBodyDecl *Body,
8951 SourceLocation LParenLoc,
8952 ArrayRef<ParmVarDecl *> LocalParameters,
8953 SourceLocation RParenLoc,
8954 ArrayRef<concepts::Requirement *> Requirements,
8955 SourceLocation ClosingBraceLoc);
8956
8957private:
8958 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
8959 bool IsDelete);
8960
8961 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8962 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8963 bool DeleteWasArrayForm);
8964
8965 ///@}
8966
8967 //
8968 //
8969 // -------------------------------------------------------------------------
8970 //
8971 //
8972
8973 /// \name Member Access Expressions
8974 /// Implementations are in SemaExprMember.cpp
8975 ///@{
8976
8977public:
8978 /// Check whether an expression might be an implicit class member access.
8979 bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R,
8980 bool IsAddressOfOperand);
8981
8982 /// Builds an expression which might be an implicit member expression.
8983 ExprResult BuildPossibleImplicitMemberExpr(
8984 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
8985 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
8986
8987 /// Builds an implicit member access expression. The current context
8988 /// is known to be an instance method, and the given unqualified lookup
8989 /// set is known to contain only instance members, at least one of which
8990 /// is from an appropriate type.
8991 ExprResult
8992 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8993 LookupResult &R,
8994 const TemplateArgumentListInfo *TemplateArgs,
8995 bool IsDefiniteInstance, const Scope *S);
8996
8997 ExprResult ActOnDependentMemberExpr(
8998 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
8999 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9000 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9001 const TemplateArgumentListInfo *TemplateArgs);
9002
9003 /// The main callback when the parser finds something like
9004 /// expression . [nested-name-specifier] identifier
9005 /// expression -> [nested-name-specifier] identifier
9006 /// where 'identifier' encompasses a fairly broad spectrum of
9007 /// possibilities, including destructor and operator references.
9008 ///
9009 /// \param OpKind either tok::arrow or tok::period
9010 /// \param ObjCImpDecl the current Objective-C \@implementation
9011 /// decl; this is an ugly hack around the fact that Objective-C
9012 /// \@implementations aren't properly put in the context chain
9013 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
9014 tok::TokenKind OpKind, CXXScopeSpec &SS,
9015 SourceLocation TemplateKWLoc,
9016 UnqualifiedId &Member, Decl *ObjCImpDecl);
9017
9018 MemberExpr *
9019 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
9020 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
9021 ValueDecl *Member, DeclAccessPair FoundDecl,
9022 bool HadMultipleCandidates,
9023 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
9024 ExprValueKind VK, ExprObjectKind OK,
9025 const TemplateArgumentListInfo *TemplateArgs = nullptr);
9026
9027 // Check whether the declarations we found through a nested-name
9028 // specifier in a member expression are actually members of the base
9029 // type. The restriction here is:
9030 //
9031 // C++ [expr.ref]p2:
9032 // ... In these cases, the id-expression shall name a
9033 // member of the class or of one of its base classes.
9034 //
9035 // So it's perfectly legitimate for the nested-name specifier to name
9036 // an unrelated class, and for us to find an overload set including
9037 // decls from classes which are not superclasses, as long as the decl
9038 // we actually pick through overload resolution is from a superclass.
9039 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
9040 const CXXScopeSpec &SS,
9041 const LookupResult &R);
9042
9043 // This struct is for use by ActOnMemberAccess to allow
9044 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
9045 // changing the access operator from a '.' to a '->' (to see if that is the
9046 // change needed to fix an error about an unknown member, e.g. when the class
9047 // defines a custom operator->).
9048 struct ActOnMemberAccessExtraArgs {
9049 Scope *S;
9050 UnqualifiedId &Id;
9051 Decl *ObjCImpDecl;
9052 };
9053
9054 ExprResult BuildMemberReferenceExpr(
9055 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
9056 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9057 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9058 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
9059 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9060
9061 ExprResult
9062 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
9063 bool IsArrow, const CXXScopeSpec &SS,
9064 SourceLocation TemplateKWLoc,
9065 NamedDecl *FirstQualifierInScope, LookupResult &R,
9066 const TemplateArgumentListInfo *TemplateArgs,
9067 const Scope *S, bool SuppressQualifierCheck = false,
9068 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9069
9070 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
9071 SourceLocation OpLoc,
9072 const CXXScopeSpec &SS, FieldDecl *Field,
9073 DeclAccessPair FoundDecl,
9074 const DeclarationNameInfo &MemberNameInfo);
9075
9076 /// Perform conversions on the LHS of a member access expression.
9077 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
9078
9079 ExprResult BuildAnonymousStructUnionMemberReference(
9080 const CXXScopeSpec &SS, SourceLocation nameLoc,
9081 IndirectFieldDecl *indirectField,
9082 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none),
9083 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
9084
9085private:
9086 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
9087
9088 ///@}
9089
9090 //
9091 //
9092 // -------------------------------------------------------------------------
9093 //
9094 //
9095
9096 /// \name Initializers
9097 /// Implementations are in SemaInit.cpp
9098 ///@{
9099
9100public:
9101 /// Stack of types that correspond to the parameter entities that are
9102 /// currently being copy-initialized. Can be empty.
9103 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
9104
9105 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9106 AggregateDeductionCandidates;
9107
9108 bool IsStringInit(Expr *Init, const ArrayType *AT);
9109
9110 /// Determine whether we can perform aggregate initialization for the purposes
9111 /// of overload resolution.
9112 bool CanPerformAggregateInitializationForOverloadResolution(
9113 const InitializedEntity &Entity, InitListExpr *From);
9114
9115 ExprResult ActOnDesignatedInitializer(Designation &Desig,
9116 SourceLocation EqualOrColonLoc,
9117 bool GNUSyntax, ExprResult Init);
9118
9119 /// Check that the lifetime of the initializer (and its subobjects) is
9120 /// sufficient for initializing the entity, and perform lifetime extension
9121 /// (when permitted) if not.
9122 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
9123
9124 MaterializeTemporaryExpr *
9125 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
9126 bool BoundToLvalueReference);
9127
9128 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9129 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9130 /// we don't have xvalues there.
9131 ExprResult TemporaryMaterializationConversion(Expr *E);
9132
9133 ExprResult PerformQualificationConversion(
9134 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
9135 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
9136
9137 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
9138 ExprResult Init);
9139 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
9140 SourceLocation EqualLoc, ExprResult Init,
9141 bool TopLevelOfInitList = false,
9142 bool AllowExplicit = false);
9143
9144 QualType DeduceTemplateSpecializationFromInitializer(
9145 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9146 const InitializationKind &Kind, MultiExprArg Init);
9147
9148 ///@}
9149
9150 //
9151 //
9152 // -------------------------------------------------------------------------
9153 //
9154 //
9155
9156 /// \name C++ Lambda Expressions
9157 /// Implementations are in SemaLambda.cpp
9158 ///@{
9159
9160public:
9161 /// Create a new lambda closure type.
9162 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
9163 TypeSourceInfo *Info,
9164 unsigned LambdaDependencyKind,
9165 LambdaCaptureDefault CaptureDefault);
9166
9167 /// Number lambda for linkage purposes if necessary.
9168 void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method,
9169 std::optional<CXXRecordDecl::LambdaNumbering>
9170 NumberingOverride = std::nullopt);
9171
9172 /// Endow the lambda scope info with the relevant properties.
9173 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9174 SourceRange IntroducerRange,
9175 LambdaCaptureDefault CaptureDefault,
9176 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9177 bool Mutable);
9178
9179 CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange,
9180 CXXRecordDecl *Class);
9181
9182 void AddTemplateParametersToLambdaCallOperator(
9183 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9184 TemplateParameterList *TemplateParams);
9185
9186 void
9187 CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc,
9188 SourceLocation CallOperatorLoc,
9189 const AssociatedConstraint &TrailingRequiresClause,
9190 TypeSourceInfo *MethodTyInfo,
9191 ConstexprSpecKind ConstexprKind, StorageClass SC,
9192 ArrayRef<ParmVarDecl *> Params,
9193 bool HasExplicitResultType);
9194
9195 /// Returns true if the explicit object parameter was invalid.
9196 bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method,
9197 SourceLocation CallLoc);
9198
9199 /// Perform initialization analysis of the init-capture and perform
9200 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9201 /// not being used to initialize a reference.
9202 ParsedType actOnLambdaInitCaptureInitialization(
9203 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9204 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9205 return ParsedType::make(P: buildLambdaInitCaptureInitialization(
9206 Loc, ByRef, EllipsisLoc, NumExpansions: std::nullopt, Id,
9207 DirectInit: InitKind != LambdaCaptureInitKind::CopyInit, Init));
9208 }
9209 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
9210 SourceLocation EllipsisLoc,
9211 UnsignedOrNone NumExpansions,
9212 IdentifierInfo *Id,
9213 bool DirectInit, Expr *&Init);
9214
9215 /// Create a dummy variable within the declcontext of the lambda's
9216 /// call operator, for name lookup purposes for a lambda init capture.
9217 ///
9218 /// CodeGen handles emission of lambda captures, ignoring these dummy
9219 /// variables appropriately.
9220 VarDecl *createLambdaInitCaptureVarDecl(
9221 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9222 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9223
9224 /// Add an init-capture to a lambda scope.
9225 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9226
9227 /// Note that we have finished the explicit captures for the
9228 /// given lambda.
9229 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
9230
9231 /// Deduce a block or lambda's return type based on the return
9232 /// statements present in the body.
9233 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
9234
9235 /// Once the Lambdas capture are known, we can start to create the closure,
9236 /// call operator method, and keep track of the captures.
9237 /// We do the capture lookup here, but they are not actually captured until
9238 /// after we know what the qualifiers of the call operator are.
9239 void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
9240 Scope *CurContext);
9241
9242 /// This is called after parsing the explicit template parameter list
9243 /// on a lambda (if it exists) in C++2a.
9244 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
9245 SourceLocation LAngleLoc,
9246 ArrayRef<NamedDecl *> TParams,
9247 SourceLocation RAngleLoc,
9248 ExprResult RequiresClause);
9249
9250 void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
9251 SourceLocation MutableLoc);
9252
9253 void ActOnLambdaClosureParameters(
9254 Scope *LambdaScope,
9255 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo);
9256
9257 /// ActOnStartOfLambdaDefinition - This is called just before we start
9258 /// parsing the body of a lambda; it analyzes the explicit captures and
9259 /// arguments, and sets up various data-structures for the body of the
9260 /// lambda.
9261 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
9262 Declarator &ParamInfo, const DeclSpec &DS);
9263
9264 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9265 /// is invoked to pop the information about the lambda.
9266 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9267 bool IsInstantiation = false);
9268
9269 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9270 /// was successfully completed.
9271 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body);
9272
9273 /// Does copying/destroying the captured variable have side effects?
9274 bool CaptureHasSideEffects(const sema::Capture &From);
9275
9276 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9277 /// diagnostic is emitted.
9278 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9279 SourceRange FixItRange,
9280 const sema::Capture &From);
9281
9282 /// Build a FieldDecl suitable to hold the given capture.
9283 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
9284
9285 /// Initialize the given capture with a suitable expression.
9286 ExprResult BuildCaptureInit(const sema::Capture &Capture,
9287 SourceLocation ImplicitCaptureLoc,
9288 bool IsOpenMPMapping = false);
9289
9290 /// Complete a lambda-expression having processed and attached the
9291 /// lambda body.
9292 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc);
9293
9294 /// Get the return type to use for a lambda's conversion function(s) to
9295 /// function pointer type, given the type of the call operator.
9296 QualType
9297 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
9298 CallingConv CC);
9299
9300 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
9301 SourceLocation ConvLocation,
9302 CXXConversionDecl *Conv, Expr *Src);
9303
9304 class LambdaScopeForCallOperatorInstantiationRAII
9305 : private FunctionScopeRAII {
9306 public:
9307 LambdaScopeForCallOperatorInstantiationRAII(
9308 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9309 LocalInstantiationScope &Scope,
9310 bool ShouldAddDeclsFromParentScope = true);
9311 };
9312
9313 /// Compute the mangling number context for a lambda expression or
9314 /// block literal. Also return the extra mangling decl if any.
9315 ///
9316 /// \param DC - The DeclContext containing the lambda expression or
9317 /// block literal.
9318 std::tuple<MangleNumberingContext *, Decl *>
9319 getCurrentMangleNumberContext(const DeclContext *DC);
9320
9321 ///@}
9322
9323 //
9324 //
9325 // -------------------------------------------------------------------------
9326 //
9327 //
9328
9329 /// \name Name Lookup
9330 ///
9331 /// These routines provide name lookup that is used during semantic
9332 /// analysis to resolve the various kinds of names (identifiers,
9333 /// overloaded operator names, constructor names, etc.) into zero or
9334 /// more declarations within a particular scope. The major entry
9335 /// points are LookupName, which performs unqualified name lookup,
9336 /// and LookupQualifiedName, which performs qualified name lookup.
9337 ///
9338 /// All name lookup is performed based on some specific criteria,
9339 /// which specify what names will be visible to name lookup and how
9340 /// far name lookup should work. These criteria are important both
9341 /// for capturing language semantics (certain lookups will ignore
9342 /// certain names, for example) and for performance, since name
9343 /// lookup is often a bottleneck in the compilation of C++. Name
9344 /// lookup criteria is specified via the LookupCriteria enumeration.
9345 ///
9346 /// The results of name lookup can vary based on the kind of name
9347 /// lookup performed, the current language, and the translation
9348 /// unit. In C, for example, name lookup will either return nothing
9349 /// (no entity found) or a single declaration. In C++, name lookup
9350 /// can additionally refer to a set of overloaded functions or
9351 /// result in an ambiguity. All of the possible results of name
9352 /// lookup are captured by the LookupResult class, which provides
9353 /// the ability to distinguish among them.
9354 ///
9355 /// Implementations are in SemaLookup.cpp
9356 ///@{
9357
9358public:
9359 /// Tracks whether we are in a context where typo correction is
9360 /// disabled.
9361 bool DisableTypoCorrection;
9362
9363 /// The number of typos corrected by CorrectTypo.
9364 unsigned TyposCorrected;
9365
9366 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9367 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9368
9369 /// A cache containing identifiers for which typo correction failed and
9370 /// their locations, so that repeated attempts to correct an identifier in a
9371 /// given location are ignored if typo correction already failed for it.
9372 IdentifierSourceLocations TypoCorrectionFailures;
9373
9374 /// SpecialMemberOverloadResult - The overloading result for a special member
9375 /// function.
9376 ///
9377 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9378 /// integer are used to determine whether overload resolution succeeded.
9379 class SpecialMemberOverloadResult {
9380 public:
9381 enum Kind { NoMemberOrDeleted, Ambiguous, Success };
9382
9383 private:
9384 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9385
9386 public:
9387 SpecialMemberOverloadResult() {}
9388 SpecialMemberOverloadResult(CXXMethodDecl *MD)
9389 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9390
9391 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9392 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9393
9394 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9395 void setKind(Kind K) { Pair.setInt(K); }
9396 };
9397
9398 class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode,
9399 public SpecialMemberOverloadResult {
9400 public:
9401 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
9402 : FastFoldingSetNode(ID) {}
9403 };
9404
9405 /// A cache of special member function overload resolution results
9406 /// for C++ records.
9407 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
9408
9409 enum class AcceptableKind { Visible, Reachable };
9410
9411 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9412 // TODO: make this is a typesafe union.
9413 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
9414 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
9415
9416 /// Describes the kind of name lookup to perform.
9417 enum LookupNameKind {
9418 /// Ordinary name lookup, which finds ordinary names (functions,
9419 /// variables, typedefs, etc.) in C and most kinds of names
9420 /// (functions, variables, members, types, etc.) in C++.
9421 LookupOrdinaryName = 0,
9422 /// Tag name lookup, which finds the names of enums, classes,
9423 /// structs, and unions.
9424 LookupTagName,
9425 /// Label name lookup.
9426 LookupLabel,
9427 /// Member name lookup, which finds the names of
9428 /// class/struct/union members.
9429 LookupMemberName,
9430 /// Look up of an operator name (e.g., operator+) for use with
9431 /// operator overloading. This lookup is similar to ordinary name
9432 /// lookup, but will ignore any declarations that are class members.
9433 LookupOperatorName,
9434 /// Look up a name following ~ in a destructor name. This is an ordinary
9435 /// lookup, but prefers tags to typedefs.
9436 LookupDestructorName,
9437 /// Look up of a name that precedes the '::' scope resolution
9438 /// operator in C++. This lookup completely ignores operator, object,
9439 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9440 LookupNestedNameSpecifierName,
9441 /// Look up a namespace name within a C++ using directive or
9442 /// namespace alias definition, ignoring non-namespace names (C++
9443 /// [basic.lookup.udir]p1).
9444 LookupNamespaceName,
9445 /// Look up all declarations in a scope with the given name,
9446 /// including resolved using declarations. This is appropriate
9447 /// for checking redeclarations for a using declaration.
9448 LookupUsingDeclName,
9449 /// Look up an ordinary name that is going to be redeclared as a
9450 /// name with linkage. This lookup ignores any declarations that
9451 /// are outside of the current scope unless they have linkage. See
9452 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9453 LookupRedeclarationWithLinkage,
9454 /// Look up a friend of a local class. This lookup does not look
9455 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9456 LookupLocalFriendName,
9457 /// Look up the name of an Objective-C protocol.
9458 LookupObjCProtocolName,
9459 /// Look up implicit 'self' parameter of an objective-c method.
9460 LookupObjCImplicitSelfParam,
9461 /// Look up the name of an OpenMP user-defined reduction operation.
9462 LookupOMPReductionName,
9463 /// Look up the name of an OpenMP user-defined mapper.
9464 LookupOMPMapperName,
9465 /// Look up any declaration with any name.
9466 LookupAnyName
9467 };
9468
9469 /// The possible outcomes of name lookup for a literal operator.
9470 enum LiteralOperatorLookupResult {
9471 /// The lookup resulted in an error.
9472 LOLR_Error,
9473 /// The lookup found no match but no diagnostic was issued.
9474 LOLR_ErrorNoDiagnostic,
9475 /// The lookup found a single 'cooked' literal operator, which
9476 /// expects a normal literal to be built and passed to it.
9477 LOLR_Cooked,
9478 /// The lookup found a single 'raw' literal operator, which expects
9479 /// a string literal containing the spelling of the literal token.
9480 LOLR_Raw,
9481 /// The lookup found an overload set of literal operator templates,
9482 /// which expect the characters of the spelling of the literal token to be
9483 /// passed as a non-type template argument pack.
9484 LOLR_Template,
9485 /// The lookup found an overload set of literal operator templates,
9486 /// which expect the character type and characters of the spelling of the
9487 /// string literal token to be passed as template arguments.
9488 LOLR_StringTemplatePack,
9489 };
9490
9491 SpecialMemberOverloadResult
9492 LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg,
9493 bool VolatileArg, bool RValueThis, bool ConstThis,
9494 bool VolatileThis);
9495
9496 RedeclarationKind forRedeclarationInCurContext() const;
9497
9498 /// Look up a name, looking for a single declaration. Return
9499 /// null if the results were absent, ambiguous, or overloaded.
9500 ///
9501 /// It is preferable to use the elaborated form and explicitly handle
9502 /// ambiguity and overloaded.
9503 NamedDecl *LookupSingleName(
9504 Scope *S, DeclarationName Name, SourceLocation Loc,
9505 LookupNameKind NameKind,
9506 RedeclarationKind Redecl = RedeclarationKind::NotForRedeclaration);
9507
9508 /// Lookup a builtin function, when name lookup would otherwise
9509 /// fail.
9510 bool LookupBuiltin(LookupResult &R);
9511 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9512
9513 /// Perform unqualified name lookup starting from a given
9514 /// scope.
9515 ///
9516 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9517 /// used to find names within the current scope. For example, 'x' in
9518 /// @code
9519 /// int x;
9520 /// int f() {
9521 /// return x; // unqualified name look finds 'x' in the global scope
9522 /// }
9523 /// @endcode
9524 ///
9525 /// Different lookup criteria can find different names. For example, a
9526 /// particular scope can have both a struct and a function of the same
9527 /// name, and each can be found by certain lookup criteria. For more
9528 /// information about lookup criteria, see the documentation for the
9529 /// class LookupCriteria.
9530 ///
9531 /// @param S The scope from which unqualified name lookup will
9532 /// begin. If the lookup criteria permits, name lookup may also search
9533 /// in the parent scopes.
9534 ///
9535 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9536 /// look up and the lookup kind), and is updated with the results of lookup
9537 /// including zero or more declarations and possibly additional information
9538 /// used to diagnose ambiguities.
9539 ///
9540 /// @returns \c true if lookup succeeded and false otherwise.
9541 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9542 bool ForceNoCPlusPlus = false);
9543
9544 /// Perform qualified name lookup into a given context.
9545 ///
9546 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9547 /// names when the context of those names is explicit specified, e.g.,
9548 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9549 ///
9550 /// Different lookup criteria can find different names. For example, a
9551 /// particular scope can have both a struct and a function of the same
9552 /// name, and each can be found by certain lookup criteria. For more
9553 /// information about lookup criteria, see the documentation for the
9554 /// class LookupCriteria.
9555 ///
9556 /// \param R captures both the lookup criteria and any lookup results found.
9557 ///
9558 /// \param LookupCtx The context in which qualified name lookup will
9559 /// search. If the lookup criteria permits, name lookup may also search
9560 /// in the parent contexts or (for C++ classes) base classes.
9561 ///
9562 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9563 /// occurs as part of unqualified name lookup.
9564 ///
9565 /// \returns true if lookup succeeded, false if it failed.
9566 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9567 bool InUnqualifiedLookup = false);
9568
9569 /// Performs qualified name lookup or special type of lookup for
9570 /// "__super::" scope specifier.
9571 ///
9572 /// This routine is a convenience overload meant to be called from contexts
9573 /// that need to perform a qualified name lookup with an optional C++ scope
9574 /// specifier that might require special kind of lookup.
9575 ///
9576 /// \param R captures both the lookup criteria and any lookup results found.
9577 ///
9578 /// \param LookupCtx The context in which qualified name lookup will
9579 /// search.
9580 ///
9581 /// \param SS An optional C++ scope-specifier.
9582 ///
9583 /// \returns true if lookup succeeded, false if it failed.
9584 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9585 CXXScopeSpec &SS);
9586
9587 /// Performs name lookup for a name that was parsed in the
9588 /// source code, and may contain a C++ scope specifier.
9589 ///
9590 /// This routine is a convenience routine meant to be called from
9591 /// contexts that receive a name and an optional C++ scope specifier
9592 /// (e.g., "N::M::x"). It will then perform either qualified or
9593 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9594 /// respectively) on the given name and return those results. It will
9595 /// perform a special type of lookup for "__super::" scope specifier.
9596 ///
9597 /// @param S The scope from which unqualified name lookup will
9598 /// begin.
9599 ///
9600 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9601 ///
9602 /// @param EnteringContext Indicates whether we are going to enter the
9603 /// context of the scope-specifier SS (if present).
9604 ///
9605 /// @returns True if any decls were found (but possibly ambiguous)
9606 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
9607 QualType ObjectType, bool AllowBuiltinCreation = false,
9608 bool EnteringContext = false);
9609
9610 /// Perform qualified name lookup into all base classes of the given
9611 /// class.
9612 ///
9613 /// \param R captures both the lookup criteria and any lookup results found.
9614 ///
9615 /// \param Class The context in which qualified name lookup will
9616 /// search. Name lookup will search in all base classes merging the results.
9617 ///
9618 /// @returns True if any decls were found (but possibly ambiguous)
9619 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
9620
9621 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
9622 UnresolvedSetImpl &Functions);
9623
9624 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9625 /// If GnuLabelLoc is a valid source location, then this is a definition
9626 /// of an __label__ label name, otherwise it is a normal label definition
9627 /// or use. If IsLabelStmt is true, then this is the label of a
9628 /// labeled-statement.
9629 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
9630 SourceLocation GnuLabelLoc = SourceLocation(),
9631 bool IsLabelStmt = false);
9632
9633 /// Perform a name lookup for a label with the specified name; this does not
9634 /// create a new label if the lookup fails.
9635 LabelDecl *LookupExistingLabel(IdentifierInfo *II, SourceLocation IdentLoc);
9636
9637 /// Look up the constructors for the given class.
9638 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
9639
9640 /// Look up the default constructor for the given class.
9641 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
9642
9643 /// Look up the copying constructor for the given class.
9644 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
9645 unsigned Quals);
9646
9647 /// Look up the copying assignment operator for the given class.
9648 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
9649 bool RValueThis, unsigned ThisQuals);
9650
9651 /// Look up the moving constructor for the given class.
9652 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
9653 unsigned Quals);
9654
9655 /// Look up the moving assignment operator for the given class.
9656 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
9657 bool RValueThis, unsigned ThisQuals);
9658
9659 /// Look for the destructor of the given class.
9660 ///
9661 /// During semantic analysis, this routine should be used in lieu of
9662 /// CXXRecordDecl::getDestructor().
9663 ///
9664 /// \returns The destructor for this class.
9665 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
9666
9667 /// Force the declaration of any implicitly-declared members of this
9668 /// class.
9669 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
9670
9671 /// Make a merged definition of an existing hidden definition \p ND
9672 /// visible at the specified location.
9673 void makeMergedDefinitionVisible(NamedDecl *ND);
9674
9675 /// Check ODR hashes for C/ObjC when merging types from modules.
9676 /// Differently from C++, actually parse the body and reject in case
9677 /// of a mismatch.
9678 template <typename T,
9679 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9680 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
9681 if (Duplicate->getODRHash() != Previous->getODRHash())
9682 return false;
9683
9684 // Make the previous decl visible.
9685 makeMergedDefinitionVisible(ND: Previous);
9686 return true;
9687 }
9688
9689 /// Get the set of additional modules that should be checked during
9690 /// name lookup. A module and its imports become visible when instanting a
9691 /// template defined within it.
9692 llvm::DenseSet<Module *> &getLookupModules();
9693
9694 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9695 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
9696
9697 /// Determine if the template parameter \p D has a visible default argument.
9698 bool
9699 hasVisibleDefaultArgument(const NamedDecl *D,
9700 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9701 /// Determine if the template parameter \p D has a reachable default argument.
9702 bool hasReachableDefaultArgument(
9703 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9704 /// Determine if the template parameter \p D has a reachable default argument.
9705 bool hasAcceptableDefaultArgument(const NamedDecl *D,
9706 llvm::SmallVectorImpl<Module *> *Modules,
9707 Sema::AcceptableKind Kind);
9708
9709 /// Determine if there is a visible declaration of \p D that is an explicit
9710 /// specialization declaration for a specialization of a template. (For a
9711 /// member specialization, use hasVisibleMemberSpecialization.)
9712 bool hasVisibleExplicitSpecialization(
9713 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9714 /// Determine if there is a reachable declaration of \p D that is an explicit
9715 /// specialization declaration for a specialization of a template. (For a
9716 /// member specialization, use hasReachableMemberSpecialization.)
9717 bool hasReachableExplicitSpecialization(
9718 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9719
9720 /// Determine if there is a visible declaration of \p D that is a member
9721 /// specialization declaration (as opposed to an instantiated declaration).
9722 bool hasVisibleMemberSpecialization(
9723 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9724 /// Determine if there is a reachable declaration of \p D that is a member
9725 /// specialization declaration (as opposed to an instantiated declaration).
9726 bool hasReachableMemberSpecialization(
9727 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9728
9729 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9730
9731 /// Determine whether any declaration of an entity is visible.
9732 bool
9733 hasVisibleDeclaration(const NamedDecl *D,
9734 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9735 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9736 }
9737
9738 bool hasVisibleDeclarationSlow(const NamedDecl *D,
9739 llvm::SmallVectorImpl<Module *> *Modules);
9740 /// Determine whether any declaration of an entity is reachable.
9741 bool
9742 hasReachableDeclaration(const NamedDecl *D,
9743 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9744 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9745 }
9746 bool hasReachableDeclarationSlow(
9747 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9748
9749 void diagnoseTypo(const TypoCorrection &Correction,
9750 const PartialDiagnostic &TypoDiag,
9751 bool ErrorRecovery = true);
9752
9753 /// Diagnose a successfully-corrected typo. Separated from the correction
9754 /// itself to allow external validation of the result, etc.
9755 ///
9756 /// \param Correction The result of performing typo correction.
9757 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9758 /// string added to it (and usually also a fixit).
9759 /// \param PrevNote A note to use when indicating the location of the entity
9760 /// to which we are correcting. Will have the correction string added
9761 /// to it.
9762 /// \param ErrorRecovery If \c true (the default), the caller is going to
9763 /// recover from the typo as if the corrected string had been typed.
9764 /// In this case, \c PDiag must be an error, and we will attach a fixit
9765 /// to it.
9766 void diagnoseTypo(const TypoCorrection &Correction,
9767 const PartialDiagnostic &TypoDiag,
9768 const PartialDiagnostic &PrevNote,
9769 bool ErrorRecovery = true);
9770
9771 /// Find the associated classes and namespaces for
9772 /// argument-dependent lookup for a call with the given set of
9773 /// arguments.
9774 ///
9775 /// This routine computes the sets of associated classes and associated
9776 /// namespaces searched by argument-dependent lookup
9777 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9778 void FindAssociatedClassesAndNamespaces(
9779 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9780 AssociatedNamespaceSet &AssociatedNamespaces,
9781 AssociatedClassSet &AssociatedClasses);
9782
9783 /// Produce a diagnostic describing the ambiguity that resulted
9784 /// from name lookup.
9785 ///
9786 /// \param Result The result of the ambiguous lookup to be diagnosed.
9787 void DiagnoseAmbiguousLookup(LookupResult &Result);
9788
9789 /// LookupLiteralOperator - Determine which literal operator should be used
9790 /// for a user-defined literal, per C++11 [lex.ext].
9791 ///
9792 /// Normal overload resolution is not used to select which literal operator to
9793 /// call for a user-defined literal. Look up the provided literal operator
9794 /// name, and filter the results to the appropriate set for the given argument
9795 /// types.
9796 LiteralOperatorLookupResult
9797 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
9798 bool AllowRaw, bool AllowTemplate,
9799 bool AllowStringTemplate, bool DiagnoseMissing,
9800 StringLiteral *StringLit = nullptr);
9801
9802 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
9803 ArrayRef<Expr *> Args, ADLResult &Functions);
9804
9805 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9806 VisibleDeclConsumer &Consumer,
9807 bool IncludeGlobalScope = true,
9808 bool LoadExternal = true);
9809 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9810 VisibleDeclConsumer &Consumer,
9811 bool IncludeGlobalScope = true,
9812 bool IncludeDependentBases = false,
9813 bool LoadExternal = true);
9814
9815 /// Try to "correct" a typo in the source code by finding
9816 /// visible declarations whose names are similar to the name that was
9817 /// present in the source code.
9818 ///
9819 /// \param TypoName the \c DeclarationNameInfo structure that contains
9820 /// the name that was present in the source code along with its location.
9821 ///
9822 /// \param LookupKind the name-lookup criteria used to search for the name.
9823 ///
9824 /// \param S the scope in which name lookup occurs.
9825 ///
9826 /// \param SS the nested-name-specifier that precedes the name we're
9827 /// looking for, if present.
9828 ///
9829 /// \param CCC A CorrectionCandidateCallback object that provides further
9830 /// validation of typo correction candidates. It also provides flags for
9831 /// determining the set of keywords permitted.
9832 ///
9833 /// \param MemberContext if non-NULL, the context in which to look for
9834 /// a member access expression.
9835 ///
9836 /// \param EnteringContext whether we're entering the context described by
9837 /// the nested-name-specifier SS.
9838 ///
9839 /// \param OPT when non-NULL, the search for visible declarations will
9840 /// also walk the protocols in the qualified interfaces of \p OPT.
9841 ///
9842 /// \returns a \c TypoCorrection containing the corrected name if the typo
9843 /// along with information such as the \c NamedDecl where the corrected name
9844 /// was declared, and any additional \c NestedNameSpecifier needed to access
9845 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9846 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
9847 Sema::LookupNameKind LookupKind, Scope *S,
9848 CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9849 CorrectTypoKind Mode,
9850 DeclContext *MemberContext = nullptr,
9851 bool EnteringContext = false,
9852 const ObjCObjectPointerType *OPT = nullptr,
9853 bool RecordFailure = true);
9854
9855 /// Kinds of missing import. Note, the values of these enumerators correspond
9856 /// to %select values in diagnostics.
9857 enum class MissingImportKind {
9858 Declaration,
9859 Definition,
9860 DefaultArgument,
9861 ExplicitSpecialization,
9862 PartialSpecialization
9863 };
9864
9865 /// Diagnose that the specified declaration needs to be visible but
9866 /// isn't, and suggest a module import that would resolve the problem.
9867 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9868 MissingImportKind MIK, bool Recover = true);
9869 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9870 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9871 MissingImportKind MIK, bool Recover);
9872
9873 /// Called on #pragma clang __debug dump II
9874 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9875
9876 /// Called on #pragma clang __debug dump E
9877 void ActOnPragmaDump(Expr *E);
9878
9879private:
9880 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9881 //
9882 // The boolean value will be true to indicate that the namespace was loaded
9883 // from an AST/PCH file, or false otherwise.
9884 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9885
9886 /// Whether we have already loaded known namespaces from an extenal
9887 /// source.
9888 bool LoadedExternalKnownNamespaces;
9889
9890 bool CppLookupName(LookupResult &R, Scope *S);
9891
9892 /// Determine if we could use all the declarations in the module.
9893 bool isUsableModule(const Module *M);
9894
9895 /// Helper for CorrectTypo used to create and populate a new
9896 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
9897 /// skipped entirely.
9898 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
9899 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
9900 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9901 DeclContext *MemberContext, bool EnteringContext,
9902 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
9903
9904 /// Cache for module units which is usable for current module.
9905 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
9906
9907 /// Record the typo correction failure and return an empty correction.
9908 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
9909 bool RecordFailure = true) {
9910 if (RecordFailure)
9911 TypoCorrectionFailures[Typo].insert(V: TypoLoc);
9912 return TypoCorrection();
9913 }
9914
9915 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
9916
9917 /// Determine whether two declarations should be linked together, given that
9918 /// the old declaration might not be visible and the new declaration might
9919 /// not have external linkage.
9920 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
9921 const NamedDecl *New) {
9922 if (isVisible(D: Old))
9923 return true;
9924 // See comment in below overload for why it's safe to compute the linkage
9925 // of the new declaration here.
9926 if (New->isExternallyDeclarable()) {
9927 assert(Old->isExternallyDeclarable() &&
9928 "should not have found a non-externally-declarable previous decl");
9929 return true;
9930 }
9931 return false;
9932 }
9933 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
9934
9935 ///@}
9936
9937 //
9938 //
9939 // -------------------------------------------------------------------------
9940 //
9941 //
9942
9943 /// \name Modules
9944 /// Implementations are in SemaModule.cpp
9945 ///@{
9946
9947public:
9948 /// Get the module unit whose scope we are currently within.
9949 Module *getCurrentModule() const {
9950 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
9951 }
9952
9953 /// Is the module scope we are an implementation unit?
9954 bool currentModuleIsImplementation() const {
9955 if (ModuleScopes.empty())
9956 return false;
9957 const Module *M = ModuleScopes.back().Module;
9958 return M->isModuleImplementation() || M->isModulePartitionImplementation();
9959 }
9960
9961 // When loading a non-modular PCH files, this is used to restore module
9962 // visibility.
9963 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
9964 VisibleModules.setVisible(M: Mod, Loc: ImportLoc);
9965 }
9966
9967 enum class ModuleDeclKind {
9968 Interface, ///< 'export module X;'
9969 Implementation, ///< 'module X;'
9970 PartitionInterface, ///< 'export module X:Y;'
9971 PartitionImplementation, ///< 'module X:Y;'
9972 };
9973
9974 /// An enumeration to represent the transition of states in parsing module
9975 /// fragments and imports. If we are not parsing a C++20 TU, or we find
9976 /// an error in state transition, the state is set to NotACXX20Module.
9977 enum class ModuleImportState {
9978 FirstDecl, ///< Parsing the first decl in a TU.
9979 GlobalFragment, ///< after 'module;' but before 'module X;'
9980 ImportAllowed, ///< after 'module X;' but before any non-import decl.
9981 ImportFinished, ///< after any non-import decl.
9982 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
9983 ///< non-import decl.
9984 PrivateFragmentImportFinished, ///< after 'module :private;' but a
9985 ///< non-import decl has already been seen.
9986 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
9987 };
9988
9989 /// The parser has processed a module-declaration that begins the definition
9990 /// of a module interface or implementation.
9991 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
9992 SourceLocation ModuleLoc, ModuleDeclKind MDK,
9993 ModuleIdPath Path, ModuleIdPath Partition,
9994 ModuleImportState &ImportState,
9995 bool SeenNoTrivialPPDirective);
9996
9997 /// The parser has processed a global-module-fragment declaration that begins
9998 /// the definition of the global module fragment of the current module unit.
9999 /// \param ModuleLoc The location of the 'module' keyword.
10000 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
10001
10002 /// The parser has processed a private-module-fragment declaration that begins
10003 /// the definition of the private module fragment of the current module unit.
10004 /// \param ModuleLoc The location of the 'module' keyword.
10005 /// \param PrivateLoc The location of the 'private' keyword.
10006 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
10007 SourceLocation PrivateLoc);
10008
10009 /// The parser has processed a module import declaration.
10010 ///
10011 /// \param StartLoc The location of the first token in the declaration. This
10012 /// could be the location of an '@', 'export', or 'import'.
10013 /// \param ExportLoc The location of the 'export' keyword, if any.
10014 /// \param ImportLoc The location of the 'import' keyword.
10015 /// \param Path The module toplevel name as an access path.
10016 /// \param IsPartition If the name is for a partition.
10017 DeclResult ActOnModuleImport(SourceLocation StartLoc,
10018 SourceLocation ExportLoc,
10019 SourceLocation ImportLoc, ModuleIdPath Path,
10020 bool IsPartition = false);
10021 DeclResult ActOnModuleImport(SourceLocation StartLoc,
10022 SourceLocation ExportLoc,
10023 SourceLocation ImportLoc, Module *M,
10024 ModuleIdPath Path = {});
10025
10026 /// The parser has processed a module import translated from a
10027 /// #include or similar preprocessing directive.
10028 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10029 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10030
10031 /// The parsed has entered a submodule.
10032 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
10033 /// The parser has left a submodule.
10034 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
10035
10036 /// Create an implicit import of the given module at the given
10037 /// source location, for error recovery, if possible.
10038 ///
10039 /// This routine is typically used when an entity found by name lookup
10040 /// is actually hidden within a module that we know about but the user
10041 /// has forgotten to import.
10042 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
10043 Module *Mod);
10044
10045 /// We have parsed the start of an export declaration, including the '{'
10046 /// (if present).
10047 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
10048 SourceLocation LBraceLoc);
10049
10050 /// Complete the definition of an export declaration.
10051 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
10052 SourceLocation RBraceLoc);
10053
10054private:
10055 /// The parser has begun a translation unit to be compiled as a C++20
10056 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
10057 void HandleStartOfHeaderUnit();
10058
10059 struct ModuleScope {
10060 SourceLocation BeginLoc;
10061 clang::Module *Module = nullptr;
10062 VisibleModuleSet OuterVisibleModules;
10063 };
10064 /// The modules we're currently parsing.
10065 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
10066
10067 /// For an interface unit, this is the implicitly imported interface unit.
10068 clang::Module *ThePrimaryInterface = nullptr;
10069
10070 /// The explicit global module fragment of the current translation unit.
10071 /// The explicit Global Module Fragment, as specified in C++
10072 /// [module.global.frag].
10073 clang::Module *TheGlobalModuleFragment = nullptr;
10074
10075 /// The implicit global module fragments of the current translation unit.
10076 ///
10077 /// The contents in the implicit global module fragment can't be discarded.
10078 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
10079
10080 /// Namespace definitions that we will export when they finish.
10081 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
10082
10083 /// In a C++ standard module, inline declarations require a definition to be
10084 /// present at the end of a definition domain. This set holds the decls to
10085 /// be checked at the end of the TU.
10086 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
10087
10088 /// Helper function to judge if we are in module purview.
10089 /// Return false if we are not in a module.
10090 bool isCurrentModulePurview() const;
10091
10092 /// Enter the scope of the explicit global module fragment.
10093 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
10094 /// Leave the scope of the explicit global module fragment.
10095 void PopGlobalModuleFragment();
10096
10097 /// Enter the scope of an implicit global module fragment.
10098 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
10099 /// Leave the scope of an implicit global module fragment.
10100 void PopImplicitGlobalModuleFragment();
10101
10102 VisibleModuleSet VisibleModules;
10103
10104 /// Whether we had imported any named modules.
10105 bool HadImportedNamedModules = false;
10106 /// The set of instantiations we need to check if they references TU-local
10107 /// entity from TUs. This only makes sense if we imported any named modules.
10108 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
10109 PendingCheckReferenceForTULocal;
10110 /// Implement [basic.link]p18, which requires that we can't use TU-local
10111 /// entities from other TUs (ignoring header units).
10112 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
10113 SourceLocation PointOfInstantiation);
10114 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
10115 /// module interface or module partition.
10116 void checkExposure(const TranslationUnitDecl *TU);
10117
10118 ///@}
10119
10120 //
10121 //
10122 // -------------------------------------------------------------------------
10123 //
10124 //
10125
10126 /// \name C++ Overloading
10127 /// Implementations are in SemaOverload.cpp
10128 ///@{
10129
10130public:
10131 /// Whether deferrable diagnostics should be deferred.
10132 bool DeferDiags = false;
10133
10134 /// RAII class to control scope of DeferDiags.
10135 class DeferDiagsRAII {
10136 Sema &S;
10137 bool SavedDeferDiags = false;
10138
10139 public:
10140 DeferDiagsRAII(Sema &S, bool DeferDiags)
10141 : S(S), SavedDeferDiags(S.DeferDiags) {
10142 S.DeferDiags = SavedDeferDiags || DeferDiags;
10143 }
10144 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10145 DeferDiagsRAII(const DeferDiagsRAII &) = delete;
10146 DeferDiagsRAII &operator=(const DeferDiagsRAII &) = delete;
10147 };
10148
10149 /// Flag indicating if Sema is building a recovery call expression.
10150 ///
10151 /// This flag is used to avoid building recovery call expressions
10152 /// if Sema is already doing so, which would cause infinite recursions.
10153 bool IsBuildingRecoveryCallExpr;
10154
10155 /// Determine whether the given New declaration is an overload of the
10156 /// declarations in Old. This routine returns OverloadKind::Match or
10157 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10158 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10159 /// Old declarations aren't functions (or function templates) at all. When it
10160 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10161 /// will point to the decl that New cannot be overloaded with. This decl may
10162 /// be a UsingShadowDecl on top of the underlying declaration.
10163 ///
10164 /// Example: Given the following input:
10165 ///
10166 /// void f(int, float); // #1
10167 /// void f(int, int); // #2
10168 /// int f(int, int); // #3
10169 ///
10170 /// When we process #1, there is no previous declaration of "f", so IsOverload
10171 /// will not be used.
10172 ///
10173 /// When we process #2, Old contains only the FunctionDecl for #1. By
10174 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10175 /// they have different signatures), so this routine returns
10176 /// OverloadKind::Overload; MatchedDecl is unchanged.
10177 ///
10178 /// When we process #3, Old is an overload set containing #1 and #2. We
10179 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10180 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10181 /// types of functions are not part of the signature), IsOverload returns
10182 /// OverloadKind::Match and MatchedDecl will be set to point to the
10183 /// FunctionDecl for #2.
10184 ///
10185 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10186 /// class by a using declaration. The rules for whether to hide shadow
10187 /// declarations ignore some properties which otherwise figure into a function
10188 /// template's signature.
10189 OverloadKind CheckOverload(Scope *S, FunctionDecl *New,
10190 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10191 bool UseMemberUsingDeclRules);
10192 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
10193 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10194
10195 // Checks whether MD constitutes an override the base class method BaseMD.
10196 // When checking for overrides, the object object members are ignored.
10197 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10198 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10199
10200 enum class AllowedExplicit {
10201 /// Allow no explicit functions to be used.
10202 None,
10203 /// Allow explicit conversion functions but not explicit constructors.
10204 Conversions,
10205 /// Allow both explicit conversion functions and explicit constructors.
10206 All
10207 };
10208
10209 ImplicitConversionSequence TryImplicitConversion(
10210 Expr *From, QualType ToType, bool SuppressUserConversions,
10211 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10212 bool AllowObjCWritebackConversion);
10213
10214 /// PerformImplicitConversion - Perform an implicit conversion of the
10215 /// expression From to the type ToType. Returns the
10216 /// converted expression. Flavor is the kind of conversion we're
10217 /// performing, used in the error message. If @p AllowExplicit,
10218 /// explicit user-defined conversions are permitted.
10219 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10220 AssignmentAction Action,
10221 bool AllowExplicit = false);
10222
10223 /// IsIntegralPromotion - Determines whether the conversion from the
10224 /// expression From (whose potentially-adjusted type is FromType) to
10225 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10226 /// sets PromotedType to the promoted type.
10227 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10228
10229 /// IsFloatingPointPromotion - Determines whether the conversion from
10230 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10231 /// returns true and sets PromotedType to the promoted type.
10232 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10233
10234 /// Determine if a conversion is a complex promotion.
10235 ///
10236 /// A complex promotion is defined as a complex -> complex conversion
10237 /// where the conversion between the underlying real types is a
10238 /// floating-point or integral promotion.
10239 bool IsComplexPromotion(QualType FromType, QualType ToType);
10240
10241 /// IsOverflowBehaviorTypePromotion - Determines whether the conversion from
10242 /// FromType to ToType involves an OverflowBehaviorType FromType being
10243 /// promoted to an OverflowBehaviorType ToType which has a larger bitwidth.
10244 /// If so, returns true and sets FromType to ToType.
10245 bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType);
10246
10247 /// IsOverflowBehaviorTypeConversion - Determines whether the conversion from
10248 /// FromType to ToType necessarily involves both an OverflowBehaviorType and
10249 /// a non-OverflowBehaviorType. If so, returns true and sets FromType to
10250 /// ToType.
10251 bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType);
10252
10253 /// IsPointerConversion - Determines whether the conversion of the
10254 /// expression From, which has the (possibly adjusted) type FromType,
10255 /// can be converted to the type ToType via a pointer conversion (C++
10256 /// 4.10). If so, returns true and places the converted type (that
10257 /// might differ from ToType in its cv-qualifiers at some level) into
10258 /// ConvertedType.
10259 ///
10260 /// This routine also supports conversions to and from block pointers
10261 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10262 /// pointers to interfaces. FIXME: Once we've determined the
10263 /// appropriate overloading rules for Objective-C, we may want to
10264 /// split the Objective-C checks into a different routine; however,
10265 /// GCC seems to consider all of these conversions to be pointer
10266 /// conversions, so for now they live here. IncompatibleObjC will be
10267 /// set if the conversion is an allowed Objective-C conversion that
10268 /// should result in a warning.
10269 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10270 bool InOverloadResolution, QualType &ConvertedType,
10271 bool &IncompatibleObjC);
10272
10273 /// isObjCPointerConversion - Determines whether this is an
10274 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10275 /// with the same arguments and return values.
10276 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10277 QualType &ConvertedType, bool &IncompatibleObjC);
10278 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10279 QualType &ConvertedType);
10280
10281 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10282 /// for equality of their parameter types. Caller has already checked that
10283 /// they have same number of parameters. If the parameters are different,
10284 /// ArgPos will have the parameter index of the first different parameter.
10285 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10286 /// reverse order. That's useful if one of the functions is being used as a
10287 /// C++20 synthesized operator overload with a reversed parameter order.
10288 bool FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
10289 ArrayRef<QualType> New,
10290 unsigned *ArgPos = nullptr,
10291 bool Reversed = false);
10292
10293 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
10294 const FunctionProtoType *NewType,
10295 unsigned *ArgPos = nullptr,
10296 bool Reversed = false);
10297
10298 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10299 const FunctionDecl *NewFunction,
10300 unsigned *ArgPos = nullptr,
10301 bool Reversed = false);
10302
10303 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10304 /// function types. Catches different number of parameter, mismatch in
10305 /// parameter types, and different return types.
10306 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType,
10307 QualType ToType);
10308
10309 /// CheckPointerConversion - Check the pointer conversion from the
10310 /// expression From to the type ToType. This routine checks for
10311 /// ambiguous or inaccessible derived-to-base pointer
10312 /// conversions for which IsPointerConversion has already returned
10313 /// true. It returns true and produces a diagnostic if there was an
10314 /// error, or returns false otherwise.
10315 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10316 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10317 bool Diagnose = true);
10318
10319 /// IsMemberPointerConversion - Determines whether the conversion of the
10320 /// expression From, which has the (possibly adjusted) type FromType, can be
10321 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10322 /// If so, returns true and places the converted type (that might differ from
10323 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10324 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10325 bool InOverloadResolution,
10326 QualType &ConvertedType);
10327
10328 enum class MemberPointerConversionResult {
10329 Success,
10330 DifferentPointee,
10331 NotDerived,
10332 Ambiguous,
10333 Virtual,
10334 Inaccessible
10335 };
10336 enum class MemberPointerConversionDirection : bool { Downcast, Upcast };
10337 /// CheckMemberPointerConversion - Check the member pointer conversion from
10338 /// the expression From to the type ToType. This routine checks for ambiguous
10339 /// or virtual or inaccessible base-to-derived member pointer conversions for
10340 /// which IsMemberPointerConversion has already returned true. It produces a
10341 // diagnostic if there was an error.
10342 MemberPointerConversionResult CheckMemberPointerConversion(
10343 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10344 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10345 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10346
10347 /// IsQualificationConversion - Determines whether the conversion from
10348 /// an rvalue of type FromType to ToType is a qualification conversion
10349 /// (C++ 4.4).
10350 ///
10351 /// \param ObjCLifetimeConversion Output parameter that will be set to
10352 /// indicate when the qualification conversion involves a change in the
10353 /// Objective-C object lifetime.
10354 bool IsQualificationConversion(QualType FromType, QualType ToType,
10355 bool CStyle, bool &ObjCLifetimeConversion);
10356
10357 /// Determine whether the conversion from FromType to ToType is a valid
10358 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10359 /// More precisely, this method checks whether FromType can be transformed
10360 /// into an exact match for ToType, by transforming its extended function
10361 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10362 /// or "noexcept", or by stripping "noescape" for arguments).
10363 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10364
10365 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10366 /// `ResultTy` to `ToType`.
10367 bool TryFunctionConversion(QualType FromType, QualType ToType,
10368 QualType &ResultTy) const;
10369
10370 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
10371 void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
10372 DeclarationName Name,
10373 OverloadCandidateSet &CandidateSet,
10374 FunctionDecl *Fn, MultiExprArg Args,
10375 bool IsMember = false);
10376
10377 ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
10378 FunctionDecl *Fun);
10379 ExprResult PerformImplicitObjectArgumentInitialization(
10380 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10381 CXXMethodDecl *Method);
10382
10383 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10384 /// of the expression From to bool (C++0x [conv]p3).
10385 ExprResult PerformContextuallyConvertToBool(Expr *From);
10386
10387 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10388 /// conversion of the expression From to an Objective-C pointer type.
10389 /// Returns a valid but null ExprResult if no conversion sequence exists.
10390 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
10391
10392 ExprResult BuildConvertedConstantExpression(Expr *From, QualType T,
10393 CCEKind CCE,
10394 NamedDecl *Dest = nullptr);
10395
10396 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10397 llvm::APSInt &Value, CCEKind CCE);
10398 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10399 APValue &Value, CCEKind CCE,
10400 NamedDecl *Dest = nullptr);
10401
10402 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10403 /// That is a converted constant expression
10404 /// (which was built with BuildConvertedConstantExpression)
10405 ExprResult
10406 EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
10407 CCEKind CCE, bool RequireInt,
10408 const APValue &PreNarrowingValue);
10409
10410 /// Abstract base class used to perform a contextual implicit
10411 /// conversion from an expression to any type passing a filter.
10412 class ContextualImplicitConverter {
10413 public:
10414 bool Suppress;
10415 bool SuppressConversion;
10416
10417 ContextualImplicitConverter(bool Suppress = false,
10418 bool SuppressConversion = false)
10419 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
10420
10421 /// Determine whether the specified type is a valid destination type
10422 /// for this conversion.
10423 virtual bool match(QualType T) = 0;
10424
10425 /// Emits a diagnostic complaining that the expression does not have
10426 /// integral or enumeration type.
10427 virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10428 QualType T) = 0;
10429
10430 /// Emits a diagnostic when the expression has incomplete class type.
10431 virtual SemaDiagnosticBuilder
10432 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
10433
10434 /// Emits a diagnostic when the only matching conversion function
10435 /// is explicit.
10436 virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S,
10437 SourceLocation Loc,
10438 QualType T,
10439 QualType ConvTy) = 0;
10440
10441 /// Emits a note for the explicit conversion function.
10442 virtual SemaDiagnosticBuilder
10443 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10444
10445 /// Emits a diagnostic when there are multiple possible conversion
10446 /// functions.
10447 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10448 QualType T) = 0;
10449
10450 /// Emits a note for one of the candidate conversions.
10451 virtual SemaDiagnosticBuilder
10452 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10453
10454 /// Emits a diagnostic when we picked a conversion function
10455 /// (for cases when we are not allowed to pick a conversion function).
10456 virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S,
10457 SourceLocation Loc,
10458 QualType T,
10459 QualType ConvTy) = 0;
10460
10461 virtual ~ContextualImplicitConverter() {}
10462 };
10463
10464 class ICEConvertDiagnoser : public ContextualImplicitConverter {
10465 bool AllowScopedEnumerations;
10466
10467 public:
10468 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10469 bool SuppressConversion)
10470 : ContextualImplicitConverter(Suppress, SuppressConversion),
10471 AllowScopedEnumerations(AllowScopedEnumerations) {}
10472
10473 /// Match an integral or (possibly scoped) enumeration type.
10474 bool match(QualType T) override;
10475
10476 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10477 QualType T) override {
10478 return diagnoseNotInt(S, Loc, T);
10479 }
10480
10481 /// Emits a diagnostic complaining that the expression does not have
10482 /// integral or enumeration type.
10483 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10484 QualType T) = 0;
10485 };
10486
10487 /// Perform a contextual implicit conversion.
10488 ExprResult
10489 PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE,
10490 ContextualImplicitConverter &Converter);
10491
10492 /// ReferenceCompareResult - Expresses the result of comparing two
10493 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10494 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10495 enum ReferenceCompareResult {
10496 /// Ref_Incompatible - The two types are incompatible, so direct
10497 /// reference binding is not possible.
10498 Ref_Incompatible = 0,
10499 /// Ref_Related - The two types are reference-related, which means
10500 /// that their unqualified forms (T1 and T2) are either the same
10501 /// or T1 is a base class of T2.
10502 Ref_Related,
10503 /// Ref_Compatible - The two types are reference-compatible.
10504 Ref_Compatible
10505 };
10506
10507 // Fake up a scoped enumeration that still contextually converts to bool.
10508 struct ReferenceConversionsScope {
10509 /// The conversions that would be performed on an lvalue of type T2 when
10510 /// binding a reference of type T1 to it, as determined when evaluating
10511 /// whether T1 is reference-compatible with T2.
10512 enum ReferenceConversions {
10513 Qualification = 0x1,
10514 NestedQualification = 0x2,
10515 Function = 0x4,
10516 DerivedToBase = 0x8,
10517 ObjC = 0x10,
10518 ObjCLifetime = 0x20,
10519
10520 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
10521 };
10522 };
10523 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
10524
10525 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10526 /// determine whether they are reference-compatible,
10527 /// reference-related, or incompatible, for use in C++ initialization by
10528 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10529 /// type, and the first type (T1) is the pointee type of the reference
10530 /// type being initialized.
10531 ReferenceCompareResult
10532 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10533 ReferenceConversions *Conv = nullptr);
10534
10535 /// AddOverloadCandidate - Adds the given function to the set of
10536 /// candidate functions, using the given function call arguments. If
10537 /// @p SuppressUserConversions, then don't allow user-defined
10538 /// conversions via constructors or conversion operators.
10539 ///
10540 /// \param PartialOverloading true if we are performing "partial" overloading
10541 /// based on an incomplete set of function arguments. This feature is used by
10542 /// code completion.
10543 void AddOverloadCandidate(
10544 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
10545 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10546 bool PartialOverloading = false, bool AllowExplicit = true,
10547 bool AllowExplicitConversion = false,
10548 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10549 ConversionSequenceList EarlyConversions = {},
10550 OverloadCandidateParamOrder PO = {},
10551 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10552
10553 /// Add all of the function declarations in the given function set to
10554 /// the overload candidate set.
10555 void AddFunctionCandidates(
10556 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10557 OverloadCandidateSet &CandidateSet,
10558 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10559 bool SuppressUserConversions = false, bool PartialOverloading = false,
10560 bool FirstArgumentIsBase = false);
10561
10562 /// AddMethodCandidate - Adds a named decl (which is some kind of
10563 /// method) as a method candidate to the given overload set.
10564 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10565 Expr::Classification ObjectClassification,
10566 ArrayRef<Expr *> Args,
10567 OverloadCandidateSet &CandidateSet,
10568 bool SuppressUserConversion = false,
10569 OverloadCandidateParamOrder PO = {});
10570
10571 /// AddMethodCandidate - Adds the given C++ member function to the set
10572 /// of candidate functions, using the given function call arguments
10573 /// and the object argument (@c Object). For example, in a call
10574 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10575 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10576 /// allow user-defined conversions via constructors or conversion
10577 /// operators.
10578 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10579 CXXRecordDecl *ActingContext, QualType ObjectType,
10580 Expr::Classification ObjectClassification,
10581 ArrayRef<Expr *> Args,
10582 OverloadCandidateSet &CandidateSet,
10583 bool SuppressUserConversions = false,
10584 bool PartialOverloading = false,
10585 ConversionSequenceList EarlyConversions = {},
10586 OverloadCandidateParamOrder PO = {},
10587 bool StrictPackMatch = false);
10588
10589 /// Add a C++ member function template as a candidate to the candidate
10590 /// set, using template argument deduction to produce an appropriate member
10591 /// function template specialization.
10592 void AddMethodTemplateCandidate(
10593 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10594 CXXRecordDecl *ActingContext,
10595 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10596 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10597 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10598 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10599
10600 /// Add a C++ function template specialization as a candidate
10601 /// in the candidate set, using template argument deduction to produce
10602 /// an appropriate function template specialization.
10603 void AddTemplateOverloadCandidate(
10604 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10605 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10606 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10607 bool PartialOverloading = false, bool AllowExplicit = true,
10608 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10609 OverloadCandidateParamOrder PO = {},
10610 bool AggregateCandidateDeduction = false);
10611
10612 struct CheckNonDependentConversionsFlag {
10613 /// Do not consider any user-defined conversions when constructing the
10614 /// initializing sequence.
10615 bool SuppressUserConversions;
10616
10617 /// Before constructing the initializing sequence, we check whether the
10618 /// parameter type and argument type contain any user defined conversions.
10619 /// If so, do not initialize them. This effectively bypasses some undesired
10620 /// instantiation before checking constaints, which might otherwise result
10621 /// in non-SFINAE errors e.g. recursive constraints.
10622 bool OnlyInitializeNonUserDefinedConversions;
10623
10624 CheckNonDependentConversionsFlag(
10625 bool SuppressUserConversions,
10626 bool OnlyInitializeNonUserDefinedConversions)
10627 : SuppressUserConversions(SuppressUserConversions),
10628 OnlyInitializeNonUserDefinedConversions(
10629 OnlyInitializeNonUserDefinedConversions) {}
10630 };
10631
10632 /// Check that implicit conversion sequences can be formed for each argument
10633 /// whose corresponding parameter has a non-dependent type, per DR1391's
10634 /// [temp.deduct.call]p10.
10635 bool CheckNonDependentConversions(
10636 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
10637 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10638 ConversionSequenceList &Conversions,
10639 CheckNonDependentConversionsFlag UserConversionFlag,
10640 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10641 Expr::Classification ObjectClassification = {},
10642 OverloadCandidateParamOrder PO = {});
10643
10644 /// AddConversionCandidate - Add a C++ conversion function as a
10645 /// candidate in the candidate set (C++ [over.match.conv],
10646 /// C++ [over.match.copy]). From is the expression we're converting from,
10647 /// and ToType is the type that we're eventually trying to convert to
10648 /// (which may or may not be the same type as the type that the
10649 /// conversion function produces).
10650 void AddConversionCandidate(
10651 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10652 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10653 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10654 bool AllowExplicit, bool AllowResultConversion = true,
10655 bool StrictPackMatch = false);
10656
10657 /// Adds a conversion function template specialization
10658 /// candidate to the overload set, using template argument deduction
10659 /// to deduce the template arguments of the conversion function
10660 /// template from the type that we are converting to (C++
10661 /// [temp.deduct.conv]).
10662 void AddTemplateConversionCandidate(
10663 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10664 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10665 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10666 bool AllowExplicit, bool AllowResultConversion = true);
10667
10668 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10669 /// converts the given @c Object to a function pointer via the
10670 /// conversion function @c Conversion, and then attempts to call it
10671 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10672 /// the type of function that we'll eventually be calling.
10673 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10674 DeclAccessPair FoundDecl,
10675 CXXRecordDecl *ActingContext,
10676 const FunctionProtoType *Proto, Expr *Object,
10677 ArrayRef<Expr *> Args,
10678 OverloadCandidateSet &CandidateSet);
10679
10680 /// Add all of the non-member operator function declarations in the given
10681 /// function set to the overload candidate set.
10682 void AddNonMemberOperatorCandidates(
10683 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10684 OverloadCandidateSet &CandidateSet,
10685 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10686
10687 /// Add overload candidates for overloaded operators that are
10688 /// member functions.
10689 ///
10690 /// Add the overloaded operator candidates that are member functions
10691 /// for the operator Op that was used in an operator expression such
10692 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10693 /// CandidateSet will store the added overload candidates. (C++
10694 /// [over.match.oper]).
10695 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
10696 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10697 OverloadCandidateSet &CandidateSet,
10698 OverloadCandidateParamOrder PO = {});
10699
10700 /// AddBuiltinCandidate - Add a candidate for a built-in
10701 /// operator. ResultTy and ParamTys are the result and parameter types
10702 /// of the built-in candidate, respectively. Args and NumArgs are the
10703 /// arguments being passed to the candidate. IsAssignmentOperator
10704 /// should be true when this built-in candidate is an assignment
10705 /// operator. NumContextualBoolArguments is the number of arguments
10706 /// (at the beginning of the argument list) that will be contextually
10707 /// converted to bool.
10708 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10709 OverloadCandidateSet &CandidateSet,
10710 bool IsAssignmentOperator = false,
10711 unsigned NumContextualBoolArguments = 0);
10712
10713 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10714 /// operator overloads to the candidate set (C++ [over.built]), based
10715 /// on the operator @p Op and the arguments given. For example, if the
10716 /// operator is a binary '+', this routine might add "int
10717 /// operator+(int, int)" to cover integer addition.
10718 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10719 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10720 OverloadCandidateSet &CandidateSet);
10721
10722 /// Add function candidates found via argument-dependent lookup
10723 /// to the set of overloading candidates.
10724 ///
10725 /// This routine performs argument-dependent name lookup based on the
10726 /// given function name (which may also be an operator name) and adds
10727 /// all of the overload candidates found by ADL to the overload
10728 /// candidate set (C++ [basic.lookup.argdep]).
10729 void AddArgumentDependentLookupCandidates(
10730 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10731 TemplateArgumentListInfo *ExplicitTemplateArgs,
10732 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10733
10734 /// Check the enable_if expressions on the given function. Returns the first
10735 /// failing attribute, or NULL if they were all successful.
10736 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10737 ArrayRef<Expr *> Args,
10738 bool MissingImplicitThis = false);
10739
10740 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10741 /// non-ArgDependent DiagnoseIfAttrs.
10742 ///
10743 /// Argument-dependent diagnose_if attributes should be checked each time a
10744 /// function is used as a direct callee of a function call.
10745 ///
10746 /// Returns true if any errors were emitted.
10747 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10748 const Expr *ThisArg,
10749 ArrayRef<const Expr *> Args,
10750 SourceLocation Loc);
10751
10752 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10753 /// ArgDependent DiagnoseIfAttrs.
10754 ///
10755 /// Argument-independent diagnose_if attributes should be checked on every use
10756 /// of a function.
10757 ///
10758 /// Returns true if any errors were emitted.
10759 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10760 SourceLocation Loc);
10761
10762 /// Determine if \p A and \p B are equivalent internal linkage declarations
10763 /// from different modules, and thus an ambiguity error can be downgraded to
10764 /// an extension warning.
10765 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10766 const NamedDecl *B);
10767 void diagnoseEquivalentInternalLinkageDeclarations(
10768 SourceLocation Loc, const NamedDecl *D,
10769 ArrayRef<const NamedDecl *> Equiv);
10770
10771 // Emit as a 'note' the specific overload candidate
10772 void NoteOverloadCandidate(
10773 const NamedDecl *Found, const FunctionDecl *Fn,
10774 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
10775 QualType DestType = QualType(), bool TakingAddress = false);
10776
10777 // Emit as a series of 'note's all template and non-templates identified by
10778 // the expression Expr
10779 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10780 bool TakingAddress = false);
10781
10782 /// Returns whether the given function's address can be taken or not,
10783 /// optionally emitting a diagnostic if the address can't be taken.
10784 ///
10785 /// Returns false if taking the address of the function is illegal.
10786 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10787 bool Complain = false,
10788 SourceLocation Loc = SourceLocation());
10789
10790 // [PossiblyAFunctionType] --> [Return]
10791 // NonFunctionType --> NonFunctionType
10792 // R (A) --> R(A)
10793 // R (*)(A) --> R (A)
10794 // R (&)(A) --> R (A)
10795 // R (S::*)(A) --> R (A)
10796 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10797
10798 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10799 /// an overloaded function (C++ [over.over]), where @p From is an
10800 /// expression with overloaded function type and @p ToType is the type
10801 /// we're trying to resolve to. For example:
10802 ///
10803 /// @code
10804 /// int f(double);
10805 /// int f(int);
10806 ///
10807 /// int (*pfd)(double) = f; // selects f(double)
10808 /// @endcode
10809 ///
10810 /// This routine returns the resulting FunctionDecl if it could be
10811 /// resolved, and NULL otherwise. When @p Complain is true, this
10812 /// routine will emit diagnostics if there is an error.
10813 FunctionDecl *
10814 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10815 bool Complain, DeclAccessPair &Found,
10816 bool *pHadMultipleCandidates = nullptr);
10817
10818 /// Given an expression that refers to an overloaded function, try to
10819 /// resolve that function to a single function that can have its address
10820 /// taken. This will modify `Pair` iff it returns non-null.
10821 ///
10822 /// This routine can only succeed if from all of the candidates in the
10823 /// overload set for SrcExpr that can have their addresses taken, there is one
10824 /// candidate that is more constrained than the rest.
10825 FunctionDecl *
10826 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10827
10828 /// Given an overloaded function, tries to turn it into a non-overloaded
10829 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10830 /// will perform access checks, diagnose the use of the resultant decl, and,
10831 /// if requested, potentially perform a function-to-pointer decay.
10832 ///
10833 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10834 /// Otherwise, returns true. This may emit diagnostics and return true.
10835 bool resolveAndFixAddressOfSingleOverloadCandidate(
10836 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10837
10838 /// Given an expression that refers to an overloaded function, try to
10839 /// resolve that overloaded function expression down to a single function.
10840 ///
10841 /// This routine can only resolve template-ids that refer to a single function
10842 /// template, where that template-id refers to a single template whose
10843 /// template arguments are either provided by the template-id or have
10844 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10845 ///
10846 /// If no template-ids are found, no diagnostics are emitted and NULL is
10847 /// returned.
10848 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(
10849 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10850 TemplateSpecCandidateSet *FailedTSC = nullptr,
10851 bool ForTypeDeduction = false);
10852
10853 // Resolve and fix an overloaded expression that can be resolved
10854 // because it identifies a single function template specialization.
10855 //
10856 // Last three arguments should only be supplied if Complain = true
10857 //
10858 // Return true if it was logically possible to so resolve the
10859 // expression, regardless of whether or not it succeeded. Always
10860 // returns true if 'complain' is set.
10861 bool ResolveAndFixSingleFunctionTemplateSpecialization(
10862 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10863 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10864 QualType DestTypeForComplaining = QualType(),
10865 unsigned DiagIDForComplaining = 0);
10866
10867 /// Add the overload candidates named by callee and/or found by argument
10868 /// dependent lookup to the given overload set.
10869 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10870 ArrayRef<Expr *> Args,
10871 OverloadCandidateSet &CandidateSet,
10872 bool PartialOverloading = false);
10873
10874 /// Add the call candidates from the given set of lookup results to the given
10875 /// overload set. Non-function lookup results are ignored.
10876 void AddOverloadedCallCandidates(
10877 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10878 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10879
10880 // An enum used to represent the different possible results of building a
10881 // range-based for loop.
10882 enum ForRangeStatus {
10883 FRS_Success,
10884 FRS_NoViableFunction,
10885 FRS_DiagnosticIssued
10886 };
10887
10888 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10889 /// given LookupResult is non-empty, it is assumed to describe a member which
10890 /// will be invoked. Otherwise, the function will be found via argument
10891 /// dependent lookup.
10892 /// CallExpr is set to a valid expression and FRS_Success returned on success,
10893 /// otherwise CallExpr is set to ExprError() and some non-success value
10894 /// is returned.
10895 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
10896 SourceLocation RangeLoc,
10897 const DeclarationNameInfo &NameInfo,
10898 LookupResult &MemberLookup,
10899 OverloadCandidateSet *CandidateSet,
10900 Expr *Range, ExprResult *CallExpr);
10901
10902 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10903 /// (which eventually refers to the declaration Func) and the call
10904 /// arguments Args/NumArgs, attempt to resolve the function call down
10905 /// to a specific function. If overload resolution succeeds, returns
10906 /// the call expression produced by overload resolution.
10907 /// Otherwise, emits diagnostics and returns ExprError.
10908 ExprResult BuildOverloadedCallExpr(
10909 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
10910 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
10911 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
10912
10913 /// Constructs and populates an OverloadedCandidateSet from
10914 /// the given function.
10915 /// \returns true when an the ExprResult output parameter has been set.
10916 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
10917 MultiExprArg Args, SourceLocation RParenLoc,
10918 OverloadCandidateSet *CandidateSet,
10919 ExprResult *Result);
10920
10921 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
10922 NestedNameSpecifierLoc NNSLoc,
10923 DeclarationNameInfo DNI,
10924 const UnresolvedSetImpl &Fns,
10925 bool PerformADL = true);
10926
10927 /// Perform lookup for an overloaded unary operator.
10928 void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet,
10929 OverloadedOperatorKind Op,
10930 const UnresolvedSetImpl &Fns,
10931 ArrayRef<Expr *> Args, bool RequiresADL = true);
10932
10933 /// Create a unary operation that may resolve to an overloaded
10934 /// operator.
10935 ///
10936 /// \param OpLoc The location of the operator itself (e.g., '*').
10937 ///
10938 /// \param Opc The UnaryOperatorKind that describes this operator.
10939 ///
10940 /// \param Fns The set of non-member functions that will be
10941 /// considered by overload resolution. The caller needs to build this
10942 /// set based on the context using, e.g.,
10943 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10944 /// set should not contain any member functions; those will be added
10945 /// by CreateOverloadedUnaryOp().
10946 ///
10947 /// \param Input The input argument.
10948 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
10949 UnaryOperatorKind Opc,
10950 const UnresolvedSetImpl &Fns, Expr *input,
10951 bool RequiresADL = true);
10952
10953 /// Perform lookup for an overloaded binary operator.
10954 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
10955 OverloadedOperatorKind Op,
10956 const UnresolvedSetImpl &Fns,
10957 ArrayRef<Expr *> Args, bool RequiresADL = true);
10958
10959 /// Create a binary operation that may resolve to an overloaded
10960 /// operator.
10961 ///
10962 /// \param OpLoc The location of the operator itself (e.g., '+').
10963 ///
10964 /// \param Opc The BinaryOperatorKind that describes this operator.
10965 ///
10966 /// \param Fns The set of non-member functions that will be
10967 /// considered by overload resolution. The caller needs to build this
10968 /// set based on the context using, e.g.,
10969 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10970 /// set should not contain any member functions; those will be added
10971 /// by CreateOverloadedBinOp().
10972 ///
10973 /// \param LHS Left-hand argument.
10974 /// \param RHS Right-hand argument.
10975 /// \param PerformADL Whether to consider operator candidates found by ADL.
10976 /// \param AllowRewrittenCandidates Whether to consider candidates found by
10977 /// C++20 operator rewrites.
10978 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
10979 /// the function in question. Such a function is never a candidate in
10980 /// our overload resolution. This also enables synthesizing a three-way
10981 /// comparison from < and == as described in C++20 [class.spaceship]p1.
10982 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
10983 const UnresolvedSetImpl &Fns, Expr *LHS,
10984 Expr *RHS, bool RequiresADL = true,
10985 bool AllowRewrittenCandidates = true,
10986 FunctionDecl *DefaultedFn = nullptr);
10987 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
10988 const UnresolvedSetImpl &Fns,
10989 Expr *LHS, Expr *RHS,
10990 FunctionDecl *DefaultedFn);
10991
10992 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10993 SourceLocation RLoc, Expr *Base,
10994 MultiExprArg Args);
10995
10996 /// BuildCallToMemberFunction - Build a call to a member
10997 /// function. MemExpr is the expression that refers to the member
10998 /// function (and includes the object parameter), Args/NumArgs are the
10999 /// arguments to the function call (not including the object
11000 /// parameter). The caller needs to validate that the member
11001 /// expression refers to a non-static member function or an overloaded
11002 /// member function.
11003 ExprResult BuildCallToMemberFunction(
11004 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
11005 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
11006 bool IsExecConfig = false, bool AllowRecovery = false);
11007
11008 /// BuildCallToObjectOfClassType - Build a call to an object of class
11009 /// type (C++ [over.call.object]), which can end up invoking an
11010 /// overloaded function call operator (@c operator()) or performing a
11011 /// user-defined conversion on the object argument.
11012 ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object,
11013 SourceLocation LParenLoc,
11014 MultiExprArg Args,
11015 SourceLocation RParenLoc);
11016
11017 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11018 /// (if one exists), where @c Base is an expression of class type and
11019 /// @c Member is the name of the member we're trying to find.
11020 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
11021 SourceLocation OpLoc,
11022 bool *NoArrowOperatorFound = nullptr);
11023
11024 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
11025 CXXConversionDecl *Method,
11026 bool HadMultipleCandidates);
11027
11028 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
11029 /// to a literal operator described by the provided lookup results.
11030 ExprResult BuildLiteralOperatorCall(
11031 LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args,
11032 SourceLocation LitEndLoc,
11033 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
11034
11035 /// FixOverloadedFunctionReference - E is an expression that refers to
11036 /// a C++ overloaded function (possibly with some parentheses and
11037 /// perhaps a '&' around it). We have resolved the overloaded function
11038 /// to the function declaration Fn, so patch up the expression E to
11039 /// refer (possibly indirectly) to Fn. Returns the new expr.
11040 ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl,
11041 FunctionDecl *Fn);
11042 ExprResult FixOverloadedFunctionReference(ExprResult,
11043 DeclAccessPair FoundDecl,
11044 FunctionDecl *Fn);
11045
11046 /// - Returns a selector which best matches given argument list or
11047 /// nullptr if none could be found
11048 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
11049 bool IsInstance,
11050 SmallVectorImpl<ObjCMethodDecl *> &Methods);
11051
11052 ///@}
11053
11054 //
11055 //
11056 // -------------------------------------------------------------------------
11057 //
11058 //
11059
11060 /// \name Statements
11061 /// Implementations are in SemaStmt.cpp
11062 ///@{
11063
11064public:
11065 /// Stack of active SEH __finally scopes. Can be empty.
11066 SmallVector<Scope *, 2> CurrentSEHFinally;
11067
11068 /// Stack of '_Defer' statements that are currently being parsed, as well
11069 /// as the locations of their '_Defer' keywords. Can be empty.
11070 SmallVector<std::pair<Scope *, SourceLocation>, 2> CurrentDefer;
11071
11072 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
11073 StmtResult ActOnExprStmtError();
11074
11075 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
11076 bool HasLeadingEmptyMacro = false);
11077
11078 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc,
11079 SourceLocation EndLoc);
11080 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
11081
11082 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
11083 /// whose result is unused, warn.
11084 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
11085
11086 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
11087 void ActOnAfterCompoundStatementLeadingPragmas();
11088 void ActOnFinishOfCompoundStmt();
11089 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
11090 ArrayRef<Stmt *> Elts, bool isStmtExpr);
11091
11092 sema::CompoundScopeInfo &getCurCompoundScope() const;
11093
11094 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
11095 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
11096 SourceLocation DotDotDotLoc, ExprResult RHS,
11097 SourceLocation ColonLoc);
11098
11099 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
11100 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
11101
11102 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
11103 SourceLocation ColonLoc, Stmt *SubStmt,
11104 Scope *CurScope);
11105 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
11106 SourceLocation ColonLoc, Stmt *SubStmt);
11107
11108 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
11109 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
11110 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
11111 Stmt *SubStmt);
11112
11113 /// Check whether the given statement can have musttail applied to it,
11114 /// issuing a diagnostic and returning false if not. In the success case,
11115 /// the statement is rewritten to remove implicit nodes from the return
11116 /// value.
11117 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11118
11119 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11120 SourceLocation LParenLoc, Stmt *InitStmt,
11121 ConditionResult Cond, SourceLocation RParenLoc,
11122 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11123 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11124 SourceLocation LParenLoc, Stmt *InitStmt,
11125 ConditionResult Cond, SourceLocation RParenLoc,
11126 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11127
11128 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11129
11130 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
11131 SourceLocation LParenLoc, Stmt *InitStmt,
11132 ConditionResult Cond,
11133 SourceLocation RParenLoc);
11134 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
11135 Stmt *Body);
11136
11137 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11138 /// integer not in the range of enum values.
11139 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11140 Expr *SrcExpr);
11141
11142 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
11143 ConditionResult Cond, SourceLocation RParenLoc,
11144 Stmt *Body);
11145 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
11146 SourceLocation WhileLoc, SourceLocation CondLParen,
11147 Expr *Cond, SourceLocation CondRParen);
11148
11149 StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
11150 Stmt *First, ConditionResult Second,
11151 FullExprArg Third, SourceLocation RParenLoc,
11152 Stmt *Body);
11153
11154 /// In an Objective C collection iteration statement:
11155 /// for (x in y)
11156 /// x can be an arbitrary l-value expression. Bind it up as a
11157 /// full-expression.
11158 StmtResult ActOnForEachLValueExpr(Expr *E);
11159
11160 enum BuildForRangeKind {
11161 /// Initial building of a for-range statement.
11162 BFRK_Build,
11163 /// Instantiation or recovery rebuild of a for-range statement. Don't
11164 /// attempt any typo-correction.
11165 BFRK_Rebuild,
11166 /// Determining whether a for-range statement could be built. Avoid any
11167 /// unnecessary or irreversible actions.
11168 BFRK_Check
11169 };
11170
11171 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11172 ///
11173 /// C++11 [stmt.ranged]:
11174 /// A range-based for statement is equivalent to
11175 ///
11176 /// {
11177 /// auto && __range = range-init;
11178 /// for ( auto __begin = begin-expr,
11179 /// __end = end-expr;
11180 /// __begin != __end;
11181 /// ++__begin ) {
11182 /// for-range-declaration = *__begin;
11183 /// statement
11184 /// }
11185 /// }
11186 ///
11187 /// The body of the loop is not available yet, since it cannot be analysed
11188 /// until we have determined the type of the for-range-declaration.
11189 StmtResult ActOnCXXForRangeStmt(
11190 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11191 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11192 SourceLocation RParenLoc, BuildForRangeKind Kind,
11193 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11194
11195 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11196 StmtResult BuildCXXForRangeStmt(
11197 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11198 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11199 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11200 BuildForRangeKind Kind,
11201 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11202
11203 /// Set the type of a for-range declaration whose for-range or expansion
11204 /// initialiser is dependent.
11205 void ActOnDependentForRangeInitializer(VarDecl *LoopVar,
11206 BuildForRangeKind BFRK);
11207
11208 /// Holds the 'begin' and 'end' variables of a range-based for loop or
11209 /// expansion statement; begin-expr and end-expr are also provided; the
11210 /// latter are used in some diagnostics.
11211 struct ForRangeBeginEndInfo {
11212 VarDecl *BeginVar = nullptr;
11213 VarDecl *EndVar = nullptr;
11214 Expr *BeginExpr = nullptr;
11215 Expr *EndExpr = nullptr;
11216 bool isValid() const { return BeginVar != nullptr && EndVar != nullptr; }
11217 };
11218
11219 /// Determine begin-expr and end-expr and build variable declarations for
11220 /// them as per [stmt.ranged].
11221 ForRangeBeginEndInfo BuildCXXForRangeBeginEndVars(
11222 Scope *S, VarDecl *RangeVar, SourceLocation ColonLoc,
11223 SourceLocation CoawaitLoc,
11224 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps,
11225 BuildForRangeKind Kind, bool IsConstexpr,
11226 StmtResult *RebuildResult = nullptr,
11227 llvm::function_ref<StmtResult()> RebuildWithDereference = {},
11228 IdentifierInfo *BeginName = nullptr, IdentifierInfo *EndName = nullptr);
11229
11230 /// Helper used by the expansion statements and for-range code to build
11231 /// a variable declaration for e.g. 'begin' and 'end'.
11232 VarDecl *BuildForRangeVarDecl(SourceLocation Loc, QualType Type,
11233 IdentifierInfo *Name, bool IsConstexpr);
11234
11235 /// Build the range variable of a range-based for loop or iterating
11236 /// expansion statement and return its DeclStmt.
11237 StmtResult BuildCXXForRangeRangeVar(Scope *S, Expr *Range, QualType Type,
11238 bool IsConstexpr = false);
11239
11240 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11241 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11242 /// body cannot be performed until after the type of the range variable is
11243 /// determined.
11244 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11245
11246 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11247 LabelDecl *TheDecl);
11248 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11249 SourceLocation StarLoc, Expr *DestExp);
11250 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11251 LabelDecl *Label, SourceLocation LabelLoc);
11252 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11253 LabelDecl *Label, SourceLocation LabelLoc);
11254
11255 void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope);
11256 void ActOnDeferStmtError(Scope *CurScope);
11257 StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope);
11258
11259 struct NamedReturnInfo {
11260 const VarDecl *Candidate;
11261
11262 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
11263 Status S;
11264
11265 bool isMoveEligible() const { return S != None; };
11266 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
11267 };
11268 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
11269
11270 /// Determine whether the given expression might be move-eligible or
11271 /// copy-elidable in either a (co_)return statement or throw expression,
11272 /// without considering function return type, if applicable.
11273 ///
11274 /// \param E The expression being returned from the function or block,
11275 /// being thrown, or being co_returned from a coroutine. This expression
11276 /// might be modified by the implementation.
11277 ///
11278 /// \param Mode Overrides detection of current language mode
11279 /// and uses the rules for C++23.
11280 ///
11281 /// \returns An aggregate which contains the Candidate and isMoveEligible
11282 /// and isCopyElidable methods. If Candidate is non-null, it means
11283 /// isMoveEligible() would be true under the most permissive language
11284 /// standard.
11285 NamedReturnInfo getNamedReturnInfo(
11286 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
11287
11288 /// Determine whether the given NRVO candidate variable is move-eligible or
11289 /// copy-elidable, without considering function return type.
11290 ///
11291 /// \param VD The NRVO candidate variable.
11292 ///
11293 /// \returns An aggregate which contains the Candidate and isMoveEligible
11294 /// and isCopyElidable methods. If Candidate is non-null, it means
11295 /// isMoveEligible() would be true under the most permissive language
11296 /// standard.
11297 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11298
11299 /// Updates given NamedReturnInfo's move-eligible and
11300 /// copy-elidable statuses, considering the function
11301 /// return type criteria as applicable to return statements.
11302 ///
11303 /// \param Info The NamedReturnInfo object to update.
11304 ///
11305 /// \param ReturnType This is the return type of the function.
11306 /// \returns The copy elision candidate, in case the initial return expression
11307 /// was copy elidable, or nullptr otherwise.
11308 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11309 QualType ReturnType);
11310
11311 /// Perform the initialization of a potentially-movable value, which
11312 /// is the result of return value.
11313 ///
11314 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11315 /// treat returned lvalues as rvalues in certain cases (to prefer move
11316 /// construction), then falls back to treating them as lvalues if that failed.
11317 ExprResult
11318 PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
11319 const NamedReturnInfo &NRInfo, Expr *Value,
11320 bool SupressSimplerImplicitMoves = false);
11321
11322 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
11323
11324 /// Deduce the return type for a function from a returned expression, per
11325 /// C++1y [dcl.spec.auto]p6.
11326 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
11327 SourceLocation ReturnLoc, Expr *RetExpr,
11328 const AutoType *AT);
11329
11330 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11331 Scope *CurScope);
11332 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11333 bool AllowRecovery = false);
11334
11335 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11336 /// for capturing scopes.
11337 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11338 NamedReturnInfo &NRInfo,
11339 bool SupressSimplerImplicitMoves);
11340
11341 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11342 /// and creates a proper catch handler from them.
11343 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
11344 Stmt *HandlerBlock);
11345
11346 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11347 /// handlers and creates a try statement from them.
11348 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
11349 ArrayRef<Stmt *> Handlers);
11350
11351 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11352
11353 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11354 SourceLocation TryLoc, Stmt *TryBlock,
11355 Stmt *Handler);
11356 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
11357 Stmt *Block);
11358 void ActOnStartSEHFinallyBlock();
11359 void ActOnAbortSEHFinallyBlock();
11360 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
11361 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
11362
11363 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
11364 bool IsIfExists,
11365 NestedNameSpecifierLoc QualifierLoc,
11366 DeclarationNameInfo NameInfo,
11367 Stmt *Nested);
11368 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
11369 bool IsIfExists, CXXScopeSpec &SS,
11370 UnqualifiedId &Name, Stmt *Nested);
11371
11372 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11373 CapturedRegionKind Kind, unsigned NumParams);
11374 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11375 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11376 CapturedRegionKind Kind,
11377 ArrayRef<CapturedParamNameType> Params,
11378 unsigned OpenMPCaptureLevel = 0);
11379 StmtResult ActOnCapturedRegionEnd(Stmt *S);
11380 void ActOnCapturedRegionError();
11381 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
11382 SourceLocation Loc,
11383 unsigned NumParams);
11384
11385 void ApplyForRangeOrExpansionStatementLifetimeExtension(
11386 VarDecl *RangeVar, ArrayRef<MaterializeTemporaryExpr *> Temporaries);
11387
11388private:
11389 /// Check whether the given statement can have musttail applied to it,
11390 /// issuing a diagnostic and returning false if not.
11391 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11392
11393 ///@}
11394
11395 //
11396 //
11397 // -------------------------------------------------------------------------
11398 //
11399 //
11400
11401 /// \name `inline asm` Statement
11402 /// Implementations are in SemaStmtAsm.cpp
11403 ///@{
11404
11405public:
11406 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11407 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11408 bool IsVolatile, unsigned NumOutputs,
11409 unsigned NumInputs, IdentifierInfo **Names,
11410 MultiExprArg Constraints, MultiExprArg Exprs,
11411 Expr *AsmString, MultiExprArg Clobbers,
11412 unsigned NumLabels, SourceLocation RParenLoc);
11413
11414 void FillInlineAsmIdentifierInfo(Expr *Res,
11415 llvm::InlineAsmIdentifierInfo &Info);
11416 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
11417 SourceLocation TemplateKWLoc,
11418 UnqualifiedId &Id,
11419 bool IsUnevaluatedContext);
11420 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11421 SourceLocation AsmLoc);
11422 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
11423 SourceLocation AsmLoc);
11424 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
11425 ArrayRef<Token> AsmToks, StringRef AsmString,
11426 unsigned NumOutputs, unsigned NumInputs,
11427 ArrayRef<StringRef> Constraints,
11428 ArrayRef<StringRef> Clobbers,
11429 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11430 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11431 SourceLocation Location, bool AlwaysCreate);
11432
11433 ///@}
11434
11435 //
11436 //
11437 // -------------------------------------------------------------------------
11438 //
11439 //
11440
11441 /// \name Statement Attribute Handling
11442 /// Implementations are in SemaStmtAttr.cpp
11443 ///@{
11444
11445public:
11446 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11447 const AttributeCommonInfo &A);
11448 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11449 const AttributeCommonInfo &A);
11450
11451 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11452 bool CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs);
11453
11454 /// Process the attributes before creating an attributed statement. Returns
11455 /// the semantic attributes that have been processed.
11456 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11457 SmallVectorImpl<const Attr *> &OutAttrs);
11458
11459 ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A,
11460 SourceRange Range);
11461 ExprResult BuildCXXAssumeExpr(Expr *Assumption,
11462 const IdentifierInfo *AttrName,
11463 SourceRange Range);
11464
11465 ///@}
11466
11467 //
11468 //
11469 // -------------------------------------------------------------------------
11470 //
11471 //
11472
11473 /// \name C++ Templates
11474 /// Implementations are in SemaTemplate.cpp
11475 ///@{
11476
11477public:
11478 // Saves the current floating-point pragma stack and clear it in this Sema.
11479 class FpPragmaStackSaveRAII {
11480 public:
11481 FpPragmaStackSaveRAII(Sema &S)
11482 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11483 S.FpPragmaStack.Stack.clear();
11484 }
11485 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11486 FpPragmaStackSaveRAII(const FpPragmaStackSaveRAII &) = delete;
11487 FpPragmaStackSaveRAII &operator=(const FpPragmaStackSaveRAII &) = delete;
11488
11489 private:
11490 Sema &S;
11491 PragmaStack<FPOptionsOverride> SavedStack;
11492 };
11493
11494 void resetFPOptions(FPOptions FPO) {
11495 CurFPFeatures = FPO;
11496 FpPragmaStack.CurrentValue = FPO.getChangesFrom(Base: FPOptions(LangOpts));
11497 }
11498
11499 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
11500 return llvm::ArrayRef(InventedParameterInfos.begin() +
11501 InventedParameterInfosStart,
11502 InventedParameterInfos.end());
11503 }
11504
11505 ArrayRef<sema::FunctionScopeInfo *> getFunctionScopes() const {
11506 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
11507 FunctionScopes.end());
11508 }
11509
11510 typedef llvm::MapVector<const FunctionDecl *,
11511 std::unique_ptr<LateParsedTemplate>>
11512 LateParsedTemplateMapT;
11513 LateParsedTemplateMapT LateParsedTemplateMap;
11514
11515 /// Determine the number of levels of enclosing template parameters. This is
11516 /// only usable while parsing. Note that this does not include dependent
11517 /// contexts in which no template parameters have yet been declared, such as
11518 /// in a terse function template or generic lambda before the first 'auto' is
11519 /// encountered.
11520 unsigned getTemplateDepth(Scope *S) const;
11521
11522 void FilterAcceptableTemplateNames(LookupResult &R,
11523 bool AllowFunctionTemplates = true,
11524 bool AllowDependent = true);
11525 bool hasAnyAcceptableTemplateNames(LookupResult &R,
11526 bool AllowFunctionTemplates = true,
11527 bool AllowDependent = true,
11528 bool AllowNonTemplateFunctions = false);
11529 /// Try to interpret the lookup result D as a template-name.
11530 ///
11531 /// \param D A declaration found by name lookup.
11532 /// \param AllowFunctionTemplates Whether function templates should be
11533 /// considered valid results.
11534 /// \param AllowDependent Whether unresolved using declarations (that might
11535 /// name templates) should be considered valid results.
11536 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
11537 bool AllowFunctionTemplates = true,
11538 bool AllowDependent = true);
11539
11540 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
11541 /// Whether and why a template name is required in this lookup.
11542 class RequiredTemplateKind {
11543 public:
11544 /// Template name is required if TemplateKWLoc is valid.
11545 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
11546 : TemplateKW(TemplateKWLoc) {}
11547 /// Template name is unconditionally required.
11548 RequiredTemplateKind(TemplateNameIsRequiredTag) {}
11549
11550 SourceLocation getTemplateKeywordLoc() const {
11551 return TemplateKW.value_or(u: SourceLocation());
11552 }
11553 bool hasTemplateKeyword() const {
11554 return getTemplateKeywordLoc().isValid();
11555 }
11556 bool isRequired() const { return TemplateKW != SourceLocation(); }
11557 explicit operator bool() const { return isRequired(); }
11558
11559 private:
11560 std::optional<SourceLocation> TemplateKW;
11561 };
11562
11563 enum class AssumedTemplateKind {
11564 /// This is not assumed to be a template name.
11565 None,
11566 /// This is assumed to be a template name because lookup found nothing.
11567 FoundNothing,
11568 /// This is assumed to be a template name because lookup found one or more
11569 /// functions (but no function templates).
11570 FoundFunctions,
11571 };
11572
11573 bool
11574 LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
11575 QualType ObjectType, bool EnteringContext,
11576 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11577 AssumedTemplateKind *ATK = nullptr,
11578 bool AllowTypoCorrection = true);
11579
11580 TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS,
11581 bool hasTemplateKeyword,
11582 const UnqualifiedId &Name,
11583 ParsedType ObjectType, bool EnteringContext,
11584 TemplateTy &Template,
11585 bool &MemberOfUnknownSpecialization,
11586 bool AllowTypoCorrection = true);
11587
11588 /// Try to resolve an undeclared template name as a type template.
11589 ///
11590 /// Sets II to the identifier corresponding to the template name, and updates
11591 /// Name to a corresponding (typo-corrected) type template name and TNK to
11592 /// the corresponding kind, if possible.
11593 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
11594 TemplateNameKind &TNK,
11595 SourceLocation NameLoc,
11596 IdentifierInfo *&II);
11597
11598 /// Determine whether a particular identifier might be the name in a C++1z
11599 /// deduction-guide declaration.
11600 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11601 SourceLocation NameLoc, CXXScopeSpec &SS,
11602 ParsedTemplateTy *Template = nullptr);
11603
11604 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
11605 SourceLocation IILoc, Scope *S,
11606 const CXXScopeSpec *SS,
11607 TemplateTy &SuggestedTemplate,
11608 TemplateNameKind &SuggestedKind);
11609
11610 /// Determine whether we would be unable to instantiate this template (because
11611 /// it either has no definition, or is in the process of being instantiated).
11612 bool DiagnoseUninstantiableTemplate(
11613 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11614 bool InstantiatedFromMember, const NamedDecl *Pattern,
11615 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11616 bool Complain = true, bool *Unreachable = nullptr);
11617
11618 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11619 /// that the template parameter 'PrevDecl' is being shadowed by a new
11620 /// declaration at location Loc. Returns true to indicate that this is
11621 /// an error, and false otherwise.
11622 ///
11623 /// \param Loc The location of the declaration that shadows a template
11624 /// parameter.
11625 ///
11626 /// \param PrevDecl The template parameter that the declaration shadows.
11627 ///
11628 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11629 /// a warning for compatibility with older versions of clang.
11630 /// Ignored when MSVC compatibility is enabled.
11631 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
11632 bool SupportedForCompatibility = false);
11633
11634 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11635 /// the parameter D to reference the templated declaration and return a
11636 /// pointer to the template declaration. Otherwise, do nothing to D and return
11637 /// null.
11638 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
11639
11640 /// ActOnTypeParameter - Called when a C++ template type parameter
11641 /// (e.g., "typename T") has been parsed. Typename specifies whether
11642 /// the keyword "typename" was used to declare the type parameter
11643 /// (otherwise, "class" was used), and KeyLoc is the location of the
11644 /// "class" or "typename" keyword. ParamName is the name of the
11645 /// parameter (NULL indicates an unnamed template parameter) and
11646 /// ParamNameLoc is the location of the parameter name (if any).
11647 /// If the type parameter has a default argument, it will be added
11648 /// later via ActOnTypeParameterDefault.
11649 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
11650 SourceLocation EllipsisLoc,
11651 SourceLocation KeyLoc,
11652 IdentifierInfo *ParamName,
11653 SourceLocation ParamNameLoc, unsigned Depth,
11654 unsigned Position, SourceLocation EqualLoc,
11655 ParsedType DefaultArg, bool HasTypeConstraint);
11656
11657 bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint);
11658
11659 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11660 TemplateIdAnnotation *TypeConstraint,
11661 TemplateTypeParmDecl *ConstrainedParameter,
11662 SourceLocation EllipsisLoc);
11663 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11664 TemplateIdAnnotation *TypeConstraint,
11665 TemplateTypeParmDecl *ConstrainedParameter,
11666 SourceLocation EllipsisLoc,
11667 bool AllowUnexpandedPack);
11668
11669 /// Attach a type-constraint to a template parameter.
11670 /// \returns true if an error occurred. This can happen if the
11671 /// immediately-declared constraint could not be formed (e.g. incorrect number
11672 /// of arguments for the named concept).
11673 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
11674 DeclarationNameInfo NameInfo,
11675 TemplateDecl *NamedConcept, NamedDecl *FoundDecl,
11676 const TemplateArgumentListInfo *TemplateArgs,
11677 TemplateTypeParmDecl *ConstrainedParameter,
11678 SourceLocation EllipsisLoc);
11679
11680 bool AttachTypeConstraint(AutoTypeLoc TL,
11681 NonTypeTemplateParmDecl *NewConstrainedParm,
11682 NonTypeTemplateParmDecl *OrigConstrainedParm,
11683 SourceLocation EllipsisLoc);
11684
11685 /// Require the given type to be a structural type, and diagnose if it is not.
11686 ///
11687 /// \return \c true if an error was produced.
11688 bool RequireStructuralType(QualType T, SourceLocation Loc);
11689
11690 /// Check that the type of a non-type template parameter is
11691 /// well-formed.
11692 ///
11693 /// \returns the (possibly-promoted) parameter type if valid;
11694 /// otherwise, produces a diagnostic and returns a NULL type.
11695 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
11696 SourceLocation Loc);
11697 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
11698
11699 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
11700 unsigned Depth, unsigned Position,
11701 SourceLocation EqualLoc,
11702 Expr *DefaultArg);
11703
11704 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11705 /// parameter (e.g. T in template <template \<typename> class T> class array)
11706 /// has been parsed. S is the current scope.
11707 NamedDecl *ActOnTemplateTemplateParameter(
11708 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11709 bool TypenameKeyword, TemplateParameterList *Params,
11710 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11711 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11712 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11713
11714 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11715 /// constrained by RequiresClause, that contains the template parameters in
11716 /// Params.
11717 TemplateParameterList *ActOnTemplateParameterList(
11718 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11719 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11720 SourceLocation RAngleLoc, Expr *RequiresClause);
11721
11722 /// The context in which we are checking a template parameter list.
11723 enum TemplateParamListContext {
11724 // For this context, Class, Variable, TypeAlias, and non-pack Template
11725 // Template Parameters are treated uniformly.
11726 TPC_Other,
11727
11728 TPC_FunctionTemplate,
11729 TPC_ClassTemplateMember,
11730 TPC_FriendClassTemplate,
11731 TPC_FriendFunctionTemplate,
11732 TPC_FriendFunctionTemplateDefinition,
11733 TPC_TemplateTemplateParameterPack,
11734 };
11735
11736 /// Checks the validity of a template parameter list, possibly
11737 /// considering the template parameter list from a previous
11738 /// declaration.
11739 ///
11740 /// If an "old" template parameter list is provided, it must be
11741 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11742 /// template parameter list.
11743 ///
11744 /// \param NewParams Template parameter list for a new template
11745 /// declaration. This template parameter list will be updated with any
11746 /// default arguments that are carried through from the previous
11747 /// template parameter list.
11748 ///
11749 /// \param OldParams If provided, template parameter list from a
11750 /// previous declaration of the same template. Default template
11751 /// arguments will be merged from the old template parameter list to
11752 /// the new template parameter list.
11753 ///
11754 /// \param TPC Describes the context in which we are checking the given
11755 /// template parameter list.
11756 ///
11757 /// \param SkipBody If we might have already made a prior merged definition
11758 /// of this template visible, the corresponding body-skipping information.
11759 /// Default argument redefinition is not an error when skipping such a body,
11760 /// because (under the ODR) we can assume the default arguments are the same
11761 /// as the prior merged definition.
11762 ///
11763 /// \returns true if an error occurred, false otherwise.
11764 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
11765 TemplateParameterList *OldParams,
11766 TemplateParamListContext TPC,
11767 SkipBodyInfo *SkipBody = nullptr);
11768
11769 /// Match the given template parameter lists to the given scope
11770 /// specifier, returning the template parameter list that applies to the
11771 /// name.
11772 ///
11773 /// \param DeclStartLoc the start of the declaration that has a scope
11774 /// specifier or a template parameter list.
11775 ///
11776 /// \param DeclLoc The location of the declaration itself.
11777 ///
11778 /// \param SS the scope specifier that will be matched to the given template
11779 /// parameter lists. This scope specifier precedes a qualified name that is
11780 /// being declared.
11781 ///
11782 /// \param TemplateId The template-id following the scope specifier, if there
11783 /// is one. Used to check for a missing 'template<>'.
11784 ///
11785 /// \param ParamLists the template parameter lists, from the outermost to the
11786 /// innermost template parameter lists.
11787 ///
11788 /// \param IsFriend Whether to apply the slightly different rules for
11789 /// matching template parameters to scope specifiers in friend
11790 /// declarations.
11791 ///
11792 /// \param IsMemberSpecialization will be set true if the scope specifier
11793 /// denotes a fully-specialized type, and therefore this is a declaration of
11794 /// a member specialization.
11795 ///
11796 /// \returns the template parameter list, if any, that corresponds to the
11797 /// name that is preceded by the scope specifier @p SS. This template
11798 /// parameter list may have template parameters (if we're declaring a
11799 /// template) or may have no template parameters (if we're declaring a
11800 /// template specialization), or may be NULL (if what we're declaring isn't
11801 /// itself a template).
11802 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
11803 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11804 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11805 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11806 bool &IsMemberSpecialization, bool &Invalid,
11807 bool SuppressDiagnostic = false);
11808
11809 /// Returns the template parameter list with all default template argument
11810 /// information.
11811 TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD);
11812
11813 DeclResult CheckClassTemplate(
11814 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11815 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11816 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11817 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11818 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11819 TemplateParameterList **OuterTemplateParamLists,
11820 bool IsMemberSpecialization, SkipBodyInfo *SkipBody = nullptr);
11821
11822 /// Translates template arguments as provided by the parser
11823 /// into template arguments used by semantic analysis.
11824 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
11825 TemplateArgumentListInfo &Out);
11826
11827 /// Convert a parsed type into a parsed template argument. This is mostly
11828 /// trivial, except that we may have parsed a C++17 deduced class template
11829 /// specialization type, in which case we should form a template template
11830 /// argument instead of a type template argument.
11831 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
11832
11833 void NoteAllFoundTemplates(TemplateName Name);
11834
11835 QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
11836 TemplateName Template,
11837 SourceLocation TemplateLoc,
11838 TemplateArgumentListInfo &TemplateArgs,
11839 Scope *Scope, bool ForNestedNameSpecifier);
11840
11841 TypeResult
11842 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11843 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11844 SourceLocation TemplateKWLoc, TemplateTy Template,
11845 const IdentifierInfo *TemplateII,
11846 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11847 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11848 bool IsCtorOrDtorName = false, bool IsClassName = false,
11849 ImplicitTypenameContext AllowImplicitTypename =
11850 ImplicitTypenameContext::No);
11851
11852 /// Parsed an elaborated-type-specifier that refers to a template-id,
11853 /// such as \c class T::template apply<U>.
11854 TypeResult ActOnTagTemplateIdType(
11855 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11856 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11857 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11858 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11859
11860 DeclResult ActOnVarTemplateSpecialization(
11861 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
11862 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11863 StorageClass SC, bool IsPartialSpecialization);
11864
11865 /// Get the specialization of the given variable template corresponding to
11866 /// the specified argument list, or a null-but-valid result if the arguments
11867 /// are dependent.
11868 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
11869 SourceLocation TemplateLoc,
11870 SourceLocation TemplateNameLoc,
11871 const TemplateArgumentListInfo &TemplateArgs,
11872 bool SetWrittenArgs);
11873
11874 /// Form a reference to the specialization of the given variable template
11875 /// corresponding to the specified argument list, or a null-but-valid result
11876 /// if the arguments are dependent.
11877 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
11878 const DeclarationNameInfo &NameInfo,
11879 VarTemplateDecl *Template, NamedDecl *FoundD,
11880 SourceLocation TemplateLoc,
11881 const TemplateArgumentListInfo *TemplateArgs);
11882
11883 ExprResult CheckVarOrConceptTemplateTemplateId(
11884 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
11885 TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc,
11886 const TemplateArgumentListInfo *TemplateArgs);
11887
11888 ExprResult
11889 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11890 const DeclarationNameInfo &ConceptNameInfo,
11891 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
11892 const TemplateArgumentListInfo *TemplateArgs,
11893 bool DoCheckConstraintSatisfaction = true);
11894
11895 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
11896 void diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
11897 bool TemplateKeyword, TemplateDecl *TD,
11898 SourceLocation Loc);
11899
11900 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
11901 SourceLocation TemplateKWLoc, LookupResult &R,
11902 bool RequiresADL,
11903 const TemplateArgumentListInfo *TemplateArgs);
11904
11905 // We actually only call this from template instantiation.
11906 ExprResult
11907 BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11908 const DeclarationNameInfo &NameInfo,
11909 const TemplateArgumentListInfo *TemplateArgs,
11910 bool IsAddressOfOperand);
11911
11912 UnsignedOrNone getPackIndex(TemplateArgument Pack) const {
11913 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
11914 }
11915
11916 TemplateArgument
11917 getPackSubstitutedTemplateArgument(TemplateArgument Arg) const {
11918 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
11919 if (Arg.isPackExpansion())
11920 Arg = Arg.getPackExpansionPattern();
11921 return Arg;
11922 }
11923
11924 ExprResult
11925 BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
11926 QualType ParamType, SourceLocation loc,
11927 TemplateArgument Replacement,
11928 UnsignedOrNone PackIndex, bool Final);
11929
11930 /// Form a template name from a name that is syntactically required to name a
11931 /// template, either due to use of the 'template' keyword or because a name in
11932 /// this syntactic context is assumed to name a template (C++
11933 /// [temp.names]p2-4).
11934 ///
11935 /// This action forms a template name given the name of the template and its
11936 /// optional scope specifier. This is used when the 'template' keyword is used
11937 /// or when the parsing context unambiguously treats a following '<' as
11938 /// introducing a template argument list. Note that this may produce a
11939 /// non-dependent template name if we can perform the lookup now and identify
11940 /// the named template.
11941 ///
11942 /// For example, given "x.MetaFun::template apply", the scope specifier
11943 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
11944 /// of the "template" keyword, and "apply" is the \p Name.
11945 TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS,
11946 SourceLocation TemplateKWLoc,
11947 const UnqualifiedId &Name,
11948 ParsedType ObjectType,
11949 bool EnteringContext, TemplateTy &Template,
11950 bool AllowInjectedClassName = false);
11951
11952 DeclResult ActOnClassTemplateSpecialization(
11953 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11954 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
11955 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
11956 MultiTemplateParamsArg TemplateParameterLists,
11957 SkipBodyInfo *SkipBody = nullptr);
11958
11959 /// Check the non-type template arguments of a class template
11960 /// partial specialization according to C++ [temp.class.spec]p9.
11961 ///
11962 /// \param TemplateNameLoc the location of the template name.
11963 /// \param PrimaryTemplate the template parameters of the primary class
11964 /// template.
11965 /// \param NumExplicit the number of explicitly-specified template arguments.
11966 /// \param TemplateArgs the template arguments of the class template
11967 /// partial specialization.
11968 ///
11969 /// \returns \c true if there was an error, \c false otherwise.
11970 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
11971 TemplateDecl *PrimaryTemplate,
11972 unsigned NumExplicitArgs,
11973 ArrayRef<TemplateArgument> Args);
11974 void CheckTemplatePartialSpecialization(
11975 ClassTemplatePartialSpecializationDecl *Partial);
11976 void CheckTemplatePartialSpecialization(
11977 VarTemplatePartialSpecializationDecl *Partial);
11978
11979 Decl *ActOnTemplateDeclarator(Scope *S,
11980 MultiTemplateParamsArg TemplateParameterLists,
11981 Declarator &D);
11982
11983 /// Diagnose cases where we have an explicit template specialization
11984 /// before/after an explicit template instantiation, producing diagnostics
11985 /// for those cases where they are required and determining whether the
11986 /// new specialization/instantiation will have any effect.
11987 ///
11988 /// \param NewLoc the location of the new explicit specialization or
11989 /// instantiation.
11990 ///
11991 /// \param NewTSK the kind of the new explicit specialization or
11992 /// instantiation.
11993 ///
11994 /// \param PrevDecl the previous declaration of the entity.
11995 ///
11996 /// \param PrevTSK the kind of the old explicit specialization or
11997 /// instantiatin.
11998 ///
11999 /// \param PrevPointOfInstantiation if valid, indicates where the previous
12000 /// declaration was instantiated (either implicitly or explicitly).
12001 ///
12002 /// \param HasNoEffect will be set to true to indicate that the new
12003 /// specialization or instantiation has no effect and should be ignored.
12004 ///
12005 /// \returns true if there was an error that should prevent the introduction
12006 /// of the new declaration into the AST, false otherwise.
12007 bool CheckSpecializationInstantiationRedecl(
12008 SourceLocation NewLoc,
12009 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
12010 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
12011 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
12012
12013 /// Perform semantic analysis for the given dependent function
12014 /// template specialization.
12015 ///
12016 /// The only possible way to get a dependent function template specialization
12017 /// is with a friend declaration, like so:
12018 ///
12019 /// \code
12020 /// template \<class T> void foo(T);
12021 /// template \<class T> class A {
12022 /// friend void foo<>(T);
12023 /// };
12024 /// \endcode
12025 ///
12026 /// There really isn't any useful analysis we can do here, so we
12027 /// just store the information.
12028 bool CheckDependentFunctionTemplateSpecialization(
12029 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
12030 LookupResult &Previous);
12031
12032 /// Perform semantic analysis for the given function template
12033 /// specialization.
12034 ///
12035 /// This routine performs all of the semantic analysis required for an
12036 /// explicit function template specialization. On successful completion,
12037 /// the function declaration \p FD will become a function template
12038 /// specialization.
12039 ///
12040 /// \param FD the function declaration, which will be updated to become a
12041 /// function template specialization.
12042 ///
12043 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
12044 /// if any. Note that this may be valid info even when 0 arguments are
12045 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
12046 /// as it anyway contains info on the angle brackets locations.
12047 ///
12048 /// \param Previous the set of declarations that may be specialized by
12049 /// this function specialization.
12050 ///
12051 /// \param QualifiedFriend whether this is a lookup for a qualified friend
12052 /// declaration with no explicit template argument list that might be
12053 /// befriending a function template specialization.
12054 bool CheckFunctionTemplateSpecialization(
12055 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
12056 LookupResult &Previous, bool QualifiedFriend = false);
12057
12058 /// Perform semantic analysis for the given non-template member
12059 /// specialization.
12060 ///
12061 /// This routine performs all of the semantic analysis required for an
12062 /// explicit member function specialization. On successful completion,
12063 /// the function declaration \p FD will become a member function
12064 /// specialization.
12065 ///
12066 /// \param Member the member declaration, which will be updated to become a
12067 /// specialization.
12068 ///
12069 /// \param Previous the set of declarations, one of which may be specialized
12070 /// by this function specialization; the set will be modified to contain the
12071 /// redeclared member.
12072 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12073 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12074
12075 // Explicit instantiation of a class template specialization
12076 DeclResult ActOnExplicitInstantiation(
12077 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
12078 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
12079 TemplateTy Template, SourceLocation TemplateNameLoc,
12080 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
12081 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
12082
12083 // Explicit instantiation of a member class of a class template.
12084 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12085 SourceLocation TemplateLoc,
12086 unsigned TagSpec, SourceLocation KWLoc,
12087 CXXScopeSpec &SS, IdentifierInfo *Name,
12088 SourceLocation NameLoc,
12089 const ParsedAttributesView &Attr);
12090
12091 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12092 SourceLocation TemplateLoc,
12093 Declarator &D);
12094
12095 /// If the given template parameter has a default template
12096 /// argument, substitute into that default template argument and
12097 /// return the corresponding template argument.
12098 TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(
12099 TemplateDecl *Template, SourceLocation TemplateKWLoc,
12100 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
12101 ArrayRef<TemplateArgument> SugaredConverted,
12102 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
12103
12104 /// Returns the top most location responsible for the definition of \p N.
12105 /// If \p N is a a template specialization, this is the location
12106 /// of the top of the instantiation stack.
12107 /// Otherwise, the location of \p N is returned.
12108 SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const;
12109
12110 /// Specifies the context in which a particular template
12111 /// argument is being checked.
12112 enum CheckTemplateArgumentKind {
12113 /// The template argument was specified in the code or was
12114 /// instantiated with some deduced template arguments.
12115 CTAK_Specified,
12116
12117 /// The template argument was deduced via template argument
12118 /// deduction.
12119 CTAK_Deduced,
12120
12121 /// The template argument was deduced from an array bound
12122 /// via template argument deduction.
12123 CTAK_DeducedFromArrayBound
12124 };
12125
12126 struct CheckTemplateArgumentInfo {
12127 explicit CheckTemplateArgumentInfo(bool PartialOrdering = false,
12128 bool MatchingTTP = false)
12129 : PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {}
12130 CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete;
12131 CheckTemplateArgumentInfo &
12132 operator=(const CheckTemplateArgumentInfo &) = delete;
12133
12134 /// The checked, converted argument will be added to the
12135 /// end of these vectors.
12136 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
12137
12138 /// The check is being performed in the context of partial ordering.
12139 bool PartialOrdering;
12140
12141 /// If true, assume these template arguments are
12142 /// the injected template arguments for a template template parameter.
12143 /// This will relax the requirement that all its possible uses are valid:
12144 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
12145 /// during instantiation.
12146 bool MatchingTTP;
12147
12148 /// Is set to true when, in the context of TTP matching, a pack parameter
12149 /// matches non-pack arguments.
12150 bool StrictPackMatch = false;
12151 };
12152
12153 /// Check that the given template argument corresponds to the given
12154 /// template parameter.
12155 ///
12156 /// \param Param The template parameter against which the argument will be
12157 /// checked.
12158 ///
12159 /// \param Arg The template argument, which may be updated due to conversions.
12160 ///
12161 /// \param Template The template in which the template argument resides.
12162 ///
12163 /// \param TemplateLoc The location of the template name for the template
12164 /// whose argument list we're matching.
12165 ///
12166 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
12167 /// the template argument list.
12168 ///
12169 /// \param ArgumentPackIndex The index into the argument pack where this
12170 /// argument will be placed. Only valid if the parameter is a parameter pack.
12171 ///
12172 /// \param CTAK Describes how we arrived at this particular template argument:
12173 /// explicitly written, deduced, etc.
12174 ///
12175 /// \returns true on error, false otherwise.
12176 bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
12177 NamedDecl *Template, SourceLocation TemplateLoc,
12178 SourceLocation RAngleLoc,
12179 unsigned ArgumentPackIndex,
12180 CheckTemplateArgumentInfo &CTAI,
12181 CheckTemplateArgumentKind CTAK);
12182
12183 /// Check that the given template arguments can be provided to
12184 /// the given template, converting the arguments along the way.
12185 ///
12186 /// \param Template The template to which the template arguments are being
12187 /// provided.
12188 ///
12189 /// \param TemplateLoc The location of the template name in the source.
12190 ///
12191 /// \param TemplateArgs The list of template arguments. If the template is
12192 /// a template template parameter, this function may extend the set of
12193 /// template arguments to also include substituted, defaulted template
12194 /// arguments.
12195 ///
12196 /// \param PartialTemplateArgs True if the list of template arguments is
12197 /// intentionally partial, e.g., because we're checking just the initial
12198 /// set of template arguments.
12199 ///
12200 /// \param Converted Will receive the converted, canonicalized template
12201 /// arguments.
12202 ///
12203 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12204 /// contain the converted forms of the template arguments as written.
12205 /// Otherwise, \p TemplateArgs will not be modified.
12206 ///
12207 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12208 /// receive true if the cause for the error is the associated constraints of
12209 /// the template not being satisfied by the template arguments.
12210 ///
12211 /// \param DefaultArgs any default arguments from template specialization
12212 /// deduction.
12213 ///
12214 /// \returns true if an error occurred, false otherwise.
12215 bool CheckTemplateArgumentList(TemplateDecl *Template,
12216 SourceLocation TemplateLoc,
12217 TemplateArgumentListInfo &TemplateArgs,
12218 const DefaultArguments &DefaultArgs,
12219 bool PartialTemplateArgs,
12220 CheckTemplateArgumentInfo &CTAI,
12221 bool UpdateArgsWithConversions = true,
12222 bool *ConstraintsNotSatisfied = nullptr);
12223
12224 bool CheckTemplateArgumentList(
12225 TemplateDecl *Template, TemplateParameterList *Params,
12226 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12227 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12228 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12229 bool *ConstraintsNotSatisfied = nullptr);
12230
12231 bool CheckTemplateTypeArgument(
12232 TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
12233 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12234 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12235
12236 /// Check a template argument against its corresponding
12237 /// template type parameter.
12238 ///
12239 /// This routine implements the semantics of C++ [temp.arg.type]. It
12240 /// returns true if an error occurred, and false otherwise.
12241 bool CheckTemplateArgument(TypeSourceInfo *Arg);
12242
12243 /// Check a template argument against its corresponding
12244 /// non-type template parameter.
12245 ///
12246 /// This routine implements the semantics of C++ [temp.arg.nontype].
12247 /// If an error occurred, it returns ExprError(); otherwise, it
12248 /// returns the converted template argument. \p ParamType is the
12249 /// type of the non-type template parameter after it has been instantiated.
12250 ExprResult CheckTemplateArgument(NamedDecl *Param,
12251 QualType InstantiatedParamType, Expr *Arg,
12252 TemplateArgument &SugaredConverted,
12253 TemplateArgument &CanonicalConverted,
12254 bool StrictCheck,
12255 CheckTemplateArgumentKind CTAK);
12256
12257 /// Check a template argument against its corresponding
12258 /// template template parameter.
12259 ///
12260 /// This routine implements the semantics of C++ [temp.arg.template].
12261 /// It returns true if an error occurred, and false otherwise.
12262 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
12263 TemplateParameterList *Params,
12264 TemplateArgumentLoc &Arg,
12265 bool PartialOrdering,
12266 bool *StrictPackMatch);
12267
12268 bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template,
12269 TemplateTemplateParmDecl *Param,
12270 const TemplateArgumentLoc &Arg);
12271
12272 void NoteTemplateLocation(const NamedDecl &Decl,
12273 std::optional<SourceRange> ParamRange = {});
12274 void NoteTemplateParameterLocation(const NamedDecl &Decl);
12275
12276 /// Given a non-type template argument that refers to a
12277 /// declaration and the type of its corresponding non-type template
12278 /// parameter, produce an expression that properly refers to that
12279 /// declaration.
12280 /// FIXME: This is used in some contexts where the resulting expression
12281 /// doesn't need to live too long. It would be useful if this function
12282 /// could return a temporary expression.
12283 ExprResult BuildExpressionFromDeclTemplateArgument(
12284 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc);
12285 ExprResult
12286 BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
12287 SourceLocation Loc);
12288
12289 /// Enumeration describing how template parameter lists are compared
12290 /// for equality.
12291 enum TemplateParameterListEqualKind {
12292 /// We are matching the template parameter lists of two templates
12293 /// that might be redeclarations.
12294 ///
12295 /// \code
12296 /// template<typename T> struct X;
12297 /// template<typename T> struct X;
12298 /// \endcode
12299 TPL_TemplateMatch,
12300
12301 /// We are matching the template parameter lists of two template
12302 /// template parameters as part of matching the template parameter lists
12303 /// of two templates that might be redeclarations.
12304 ///
12305 /// \code
12306 /// template<template<int I> class TT> struct X;
12307 /// template<template<int Value> class Other> struct X;
12308 /// \endcode
12309 TPL_TemplateTemplateParmMatch,
12310
12311 /// We are determining whether the template-parameters are equivalent
12312 /// according to C++ [temp.over.link]/6. This comparison does not consider
12313 /// constraints.
12314 ///
12315 /// \code
12316 /// template<C1 T> void f(T);
12317 /// template<C2 T> void f(T);
12318 /// \endcode
12319 TPL_TemplateParamsEquivalent,
12320 };
12321
12322 // A struct to represent the 'new' declaration, which is either itself just
12323 // the named decl, or the important information we need about it in order to
12324 // do constraint comparisons.
12325 class TemplateCompareNewDeclInfo {
12326 const NamedDecl *ND = nullptr;
12327 const DeclContext *DC = nullptr;
12328 const DeclContext *LexicalDC = nullptr;
12329 SourceLocation Loc;
12330
12331 public:
12332 TemplateCompareNewDeclInfo(const NamedDecl *ND) : ND(ND) {}
12333 TemplateCompareNewDeclInfo(const DeclContext *DeclCtx,
12334 const DeclContext *LexicalDeclCtx,
12335 SourceLocation Loc)
12336
12337 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12338 assert(DC && LexicalDC &&
12339 "Constructor only for cases where we have the information to put "
12340 "in here");
12341 }
12342
12343 // If this was constructed with no information, we cannot do substitution
12344 // for constraint comparison, so make sure we can check that.
12345 bool isInvalid() const { return !ND && !DC; }
12346
12347 const NamedDecl *getDecl() const { return ND; }
12348
12349 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12350
12351 const DeclContext *getLexicalDeclContext() const {
12352 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12353 }
12354
12355 const DeclContext *getDeclContext() const {
12356 return ND ? ND->getDeclContext() : DC;
12357 }
12358
12359 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12360 };
12361
12362 /// Determine whether the given template parameter lists are
12363 /// equivalent.
12364 ///
12365 /// \param New The new template parameter list, typically written in the
12366 /// source code as part of a new template declaration.
12367 ///
12368 /// \param Old The old template parameter list, typically found via
12369 /// name lookup of the template declared with this template parameter
12370 /// list.
12371 ///
12372 /// \param Complain If true, this routine will produce a diagnostic if
12373 /// the template parameter lists are not equivalent.
12374 ///
12375 /// \param Kind describes how we are to match the template parameter lists.
12376 ///
12377 /// \param TemplateArgLoc If this source location is valid, then we
12378 /// are actually checking the template parameter list of a template
12379 /// argument (New) against the template parameter list of its
12380 /// corresponding template template parameter (Old). We produce
12381 /// slightly different diagnostics in this scenario.
12382 ///
12383 /// \returns True if the template parameter lists are equal, false
12384 /// otherwise.
12385 bool TemplateParameterListsAreEqual(
12386 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12387 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12388 TemplateParameterListEqualKind Kind,
12389 SourceLocation TemplateArgLoc = SourceLocation());
12390
12391 bool TemplateParameterListsAreEqual(
12392 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12393 TemplateParameterListEqualKind Kind,
12394 SourceLocation TemplateArgLoc = SourceLocation()) {
12395 return TemplateParameterListsAreEqual(NewInstFrom: nullptr, New, OldInstFrom: nullptr, Old, Complain,
12396 Kind, TemplateArgLoc);
12397 }
12398
12399 /// Check whether a template can be declared within this scope.
12400 ///
12401 /// If the template declaration is valid in this scope, returns
12402 /// false. Otherwise, issues a diagnostic and returns true.
12403 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12404
12405 /// Called when the parser has parsed a C++ typename
12406 /// specifier, e.g., "typename T::type".
12407 ///
12408 /// \param S The scope in which this typename type occurs.
12409 /// \param TypenameLoc the location of the 'typename' keyword
12410 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12411 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12412 /// \param IdLoc the location of the identifier.
12413 /// \param IsImplicitTypename context where T::type refers to a type.
12414 TypeResult ActOnTypenameType(
12415 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12416 const IdentifierInfo &II, SourceLocation IdLoc,
12417 ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No);
12418
12419 /// Called when the parser has parsed a C++ typename
12420 /// specifier that ends in a template-id, e.g.,
12421 /// "typename MetaFun::template apply<T1, T2>".
12422 ///
12423 /// \param S The scope in which this typename type occurs.
12424 /// \param TypenameLoc the location of the 'typename' keyword
12425 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12426 /// \param TemplateLoc the location of the 'template' keyword, if any.
12427 /// \param TemplateName The template name.
12428 /// \param TemplateII The identifier used to name the template.
12429 /// \param TemplateIILoc The location of the template name.
12430 /// \param LAngleLoc The location of the opening angle bracket ('<').
12431 /// \param TemplateArgs The template arguments.
12432 /// \param RAngleLoc The location of the closing angle bracket ('>').
12433 TypeResult
12434 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12435 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12436 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12437 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12438 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12439
12440 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12441 SourceLocation KeywordLoc,
12442 NestedNameSpecifierLoc QualifierLoc,
12443 const IdentifierInfo &II, SourceLocation IILoc,
12444 TypeSourceInfo **TSI, bool DeducedTSTContext);
12445
12446 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12447 SourceLocation KeywordLoc,
12448 NestedNameSpecifierLoc QualifierLoc,
12449 const IdentifierInfo &II, SourceLocation IILoc,
12450 bool DeducedTSTContext = true);
12451
12452 /// Rebuilds a type within the context of the current instantiation.
12453 ///
12454 /// The type \p T is part of the type of an out-of-line member definition of
12455 /// a class template (or class template partial specialization) that was
12456 /// parsed and constructed before we entered the scope of the class template
12457 /// (or partial specialization thereof). This routine will rebuild that type
12458 /// now that we have entered the declarator's scope, which may produce
12459 /// different canonical types, e.g.,
12460 ///
12461 /// \code
12462 /// template<typename T>
12463 /// struct X {
12464 /// typedef T* pointer;
12465 /// pointer data();
12466 /// };
12467 ///
12468 /// template<typename T>
12469 /// typename X<T>::pointer X<T>::data() { ... }
12470 /// \endcode
12471 ///
12472 /// Here, the type "typename X<T>::pointer" will be created as a
12473 /// DependentNameType, since we do not know that we can look into X<T> when we
12474 /// parsed the type. This function will rebuild the type, performing the
12475 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12476 /// canonical type is the same as the canonical type of T*, allowing the
12477 /// return types of the out-of-line definition and the declaration to match.
12478 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
12479 SourceLocation Loc,
12480 DeclarationName Name);
12481 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
12482
12483 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
12484
12485 /// Rebuild the template parameters now that we know we're in a current
12486 /// instantiation.
12487 bool
12488 RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params);
12489
12490 /// Produces a formatted string that describes the binding of
12491 /// template parameters to template arguments.
12492 std::string
12493 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12494 const TemplateArgumentList &Args);
12495
12496 std::string
12497 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12498 const TemplateArgument *Args,
12499 unsigned NumArgs);
12500
12501 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
12502 SourceLocation Less,
12503 SourceLocation Greater);
12504
12505 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12506 /// was just parsed. This is only possible with an explicit scope
12507 /// specifier naming a dependent type.
12508 ExprResult ActOnDependentIdExpression(
12509 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12510 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12511 const TemplateArgumentListInfo *TemplateArgs);
12512
12513 ExprResult
12514 BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
12515 SourceLocation TemplateKWLoc,
12516 const DeclarationNameInfo &NameInfo,
12517 const TemplateArgumentListInfo *TemplateArgs);
12518
12519 // Calculates whether the expression Constraint depends on an enclosing
12520 // template, for the purposes of [temp.friend] p9.
12521 // TemplateDepth is the 'depth' of the friend function, which is used to
12522 // compare whether a declaration reference is referring to a containing
12523 // template, or just the current friend function. A 'lower' TemplateDepth in
12524 // the AST refers to a 'containing' template. As the constraint is
12525 // uninstantiated, this is relative to the 'top' of the TU.
12526 bool
12527 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
12528 unsigned TemplateDepth,
12529 const Expr *Constraint);
12530
12531 /// Find the failed Boolean condition within a given Boolean
12532 /// constant expression, and describe it with a string.
12533 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12534
12535 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
12536
12537 ConceptDecl *ActOnStartConceptDefinition(
12538 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12539 const IdentifierInfo *Name, SourceLocation NameLoc);
12540
12541 ConceptDecl *ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
12542 Expr *ConstraintExpr,
12543 const ParsedAttributesView &Attrs);
12544
12545 void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
12546 bool &AddToScope);
12547 bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc);
12548
12549 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12550 const CXXScopeSpec &SS,
12551 const IdentifierInfo *Name,
12552 SourceLocation TagLoc, SourceLocation NameLoc);
12553
12554 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
12555 CachedTokens &Toks);
12556 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
12557 bool IsInsideALocalClassWithinATemplateFunction();
12558
12559 /// We've found a use of a templated declaration that would trigger an
12560 /// implicit instantiation. Check that any relevant explicit specializations
12561 /// and partial specializations are visible/reachable, and diagnose if not.
12562 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
12563 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
12564
12565 ///@}
12566
12567 //
12568 //
12569 // -------------------------------------------------------------------------
12570 //
12571 //
12572
12573 /// \name C++ Template Argument Deduction
12574 /// Implementations are in SemaTemplateDeduction.cpp
12575 ///@{
12576
12577public:
12578 class SFINAETrap;
12579
12580 struct SFINAEContextBase {
12581 SFINAEContextBase(Sema &S, SFINAETrap *Cur)
12582 : S(S), Prev(std::exchange(obj&: S.CurrentSFINAEContext, new_val&: Cur)) {}
12583
12584 protected:
12585 Sema &S;
12586 ~SFINAEContextBase() { S.CurrentSFINAEContext = Prev; }
12587 SFINAEContextBase(const SFINAEContextBase &) = delete;
12588 SFINAEContextBase &operator=(const SFINAEContextBase &) = delete;
12589
12590 private:
12591 SFINAETrap *Prev;
12592 };
12593
12594 struct NonSFINAEContext : SFINAEContextBase {
12595 NonSFINAEContext(Sema &S) : SFINAEContextBase(S, nullptr) {}
12596 };
12597
12598 /// RAII class used to determine whether SFINAE has
12599 /// trapped any errors that occur during template argument
12600 /// deduction.
12601 class SFINAETrap : SFINAEContextBase {
12602 bool HasErrorOcurred = false;
12603 bool WithAccessChecking = false;
12604 bool PrevLastDiagnosticIgnored =
12605 S.getDiagnostics().isLastDiagnosticIgnored();
12606 sema::TemplateDeductionInfo *DeductionInfo = nullptr;
12607
12608 SFINAETrap(Sema &S, sema::TemplateDeductionInfo *Info,
12609 bool WithAccessChecking)
12610 : SFINAEContextBase(S, this), WithAccessChecking(WithAccessChecking),
12611 DeductionInfo(Info) {}
12612
12613 public:
12614 /// \param WithAccessChecking If true, discard all diagnostics (from the
12615 /// immediate context) instead of adding them to the currently active
12616 /// \ref TemplateDeductionInfo.
12617 explicit SFINAETrap(Sema &S, bool WithAccessChecking = false)
12618 : SFINAETrap(S, /*Info=*/nullptr, WithAccessChecking) {}
12619
12620 SFINAETrap(Sema &S, sema::TemplateDeductionInfo &Info)
12621 : SFINAETrap(S, &Info, /*WithAccessChecking=*/false) {}
12622
12623 ~SFINAETrap() {
12624 S.getDiagnostics().setLastDiagnosticIgnored(PrevLastDiagnosticIgnored);
12625 }
12626
12627 SFINAETrap(const SFINAETrap &) = delete;
12628 SFINAETrap &operator=(const SFINAETrap &) = delete;
12629
12630 sema::TemplateDeductionInfo *getDeductionInfo() const {
12631 return DeductionInfo;
12632 }
12633
12634 /// Determine whether any SFINAE errors have been trapped.
12635 bool hasErrorOccurred() const { return HasErrorOcurred; }
12636 void setErrorOccurred() { HasErrorOcurred = true; }
12637
12638 bool withAccessChecking() const { return WithAccessChecking; }
12639 };
12640
12641 /// RAII class used to indicate that we are performing provisional
12642 /// semantic analysis to determine the validity of a construct, so
12643 /// typo-correction and diagnostics in the immediate context (not within
12644 /// implicitly-instantiated templates) should be suppressed.
12645 class TentativeAnalysisScope {
12646 Sema &SemaRef;
12647 // FIXME: Using a SFINAETrap for this is a hack.
12648 SFINAETrap Trap;
12649 bool PrevDisableTypoCorrection;
12650
12651 public:
12652 explicit TentativeAnalysisScope(Sema &SemaRef)
12653 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12654 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12655 SemaRef.DisableTypoCorrection = true;
12656 }
12657 ~TentativeAnalysisScope() {
12658 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12659 }
12660
12661 TentativeAnalysisScope(const TentativeAnalysisScope &) = delete;
12662 TentativeAnalysisScope &operator=(const TentativeAnalysisScope &) = delete;
12663 };
12664
12665 /// For each declaration that involved template argument deduction, the
12666 /// set of diagnostics that were suppressed during that template argument
12667 /// deduction.
12668 ///
12669 /// FIXME: Serialize this structure to the AST file.
12670 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12671 SuppressedDiagnosticsMap;
12672 SuppressedDiagnosticsMap SuppressedDiagnostics;
12673
12674 /// Compare types for equality with respect to possibly compatible
12675 /// function types (noreturn adjustment, implicit calling conventions). If any
12676 /// of parameter and argument is not a function, just perform type comparison.
12677 ///
12678 /// \param P the template parameter type.
12679 ///
12680 /// \param A the argument type.
12681 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
12682
12683 /// Allocate a TemplateArgumentLoc where all locations have
12684 /// been initialized to the given location.
12685 ///
12686 /// \param Arg The template argument we are producing template argument
12687 /// location information for.
12688 ///
12689 /// \param NTTPType For a declaration template argument, the type of
12690 /// the non-type template parameter that corresponds to this template
12691 /// argument. Can be null if no type sugar is available to add to the
12692 /// type from the template argument.
12693 ///
12694 /// \param Loc The source location to use for the resulting template
12695 /// argument.
12696 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
12697 QualType NTTPType,
12698 SourceLocation Loc);
12699
12700 /// Get a template argument mapping the given template parameter to itself,
12701 /// e.g. for X in \c template<int X>, this would return an expression template
12702 /// argument referencing X.
12703 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
12704 SourceLocation Location);
12705
12706 /// Adjust the type \p ArgFunctionType to match the calling convention,
12707 /// noreturn, and optionally the exception specification of \p FunctionType.
12708 /// Deduction often wants to ignore these properties when matching function
12709 /// types.
12710 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
12711 bool AdjustExceptionSpec = false);
12712
12713 TemplateDeductionResult
12714 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
12715 ArrayRef<TemplateArgument> TemplateArgs,
12716 sema::TemplateDeductionInfo &Info);
12717
12718 TemplateDeductionResult
12719 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
12720 ArrayRef<TemplateArgument> TemplateArgs,
12721 sema::TemplateDeductionInfo &Info);
12722
12723 /// Deduce the template arguments of the given template from \p FromType.
12724 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12725 /// [over.match.class.deduct]p4.
12726 ///
12727 /// It only supports class or type alias templates.
12728 TemplateDeductionResult
12729 DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,
12730 sema::TemplateDeductionInfo &Info);
12731
12732 TemplateDeductionResult DeduceTemplateArguments(
12733 TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps,
12734 ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info,
12735 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12736 bool NumberOfArgumentsMustMatch);
12737
12738 /// Substitute the explicitly-provided template arguments into the
12739 /// given function template according to C++ [temp.arg.explicit].
12740 ///
12741 /// \param FunctionTemplate the function template into which the explicit
12742 /// template arguments will be substituted.
12743 ///
12744 /// \param ExplicitTemplateArgs the explicitly-specified template
12745 /// arguments.
12746 ///
12747 /// \param Deduced the deduced template arguments, which will be populated
12748 /// with the converted and checked explicit template arguments.
12749 ///
12750 /// \param ParamTypes will be populated with the instantiated function
12751 /// parameters.
12752 ///
12753 /// \param FunctionType if non-NULL, the result type of the function template
12754 /// will also be instantiated and the pointed-to value will be updated with
12755 /// the instantiated function type.
12756 ///
12757 /// \param Info if substitution fails for any reason, this object will be
12758 /// populated with more information about the failure.
12759 ///
12760 /// \returns TemplateDeductionResult::Success if substitution was successful,
12761 /// or some failure condition.
12762 TemplateDeductionResult SubstituteExplicitTemplateArguments(
12763 FunctionTemplateDecl *FunctionTemplate,
12764 TemplateArgumentListInfo &ExplicitTemplateArgs,
12765 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12766 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
12767 sema::TemplateDeductionInfo &Info);
12768
12769 /// brief A function argument from which we performed template argument
12770 // deduction for a call.
12771 struct OriginalCallArg {
12772 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
12773 unsigned ArgIdx, QualType OriginalArgType)
12774 : OriginalParamType(OriginalParamType),
12775 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
12776 OriginalArgType(OriginalArgType) {}
12777
12778 QualType OriginalParamType;
12779 bool DecomposedParam;
12780 unsigned ArgIdx;
12781 QualType OriginalArgType;
12782 };
12783
12784 /// Finish template argument deduction for a function template,
12785 /// checking the deduced template arguments for completeness and forming
12786 /// the function template specialization.
12787 ///
12788 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12789 /// which the deduced argument types should be compared.
12790 /// \param CheckNonDependent Callback before substituting into the declaration
12791 /// with the deduced template arguments.
12792 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12793 /// some breakages introduced by CWG2369, where non-user-defined conversions
12794 /// are checked first before the constraints.
12795 TemplateDeductionResult FinishTemplateArgumentDeduction(
12796 FunctionTemplateDecl *FunctionTemplate,
12797 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12798 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12799 sema::TemplateDeductionInfo &Info,
12800 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12801 bool PartialOverloading, bool PartialOrdering,
12802 bool ForOverloadSetAddressResolution,
12803 llvm::function_ref<bool(bool)> CheckNonDependent =
12804 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12805 return false;
12806 });
12807
12808 /// Perform template argument deduction from a function call
12809 /// (C++ [temp.deduct.call]).
12810 ///
12811 /// \param FunctionTemplate the function template for which we are performing
12812 /// template argument deduction.
12813 ///
12814 /// \param ExplicitTemplateArgs the explicit template arguments provided
12815 /// for this call.
12816 ///
12817 /// \param Args the function call arguments
12818 ///
12819 /// \param Specialization if template argument deduction was successful,
12820 /// this will be set to the function template specialization produced by
12821 /// template argument deduction.
12822 ///
12823 /// \param Info the argument will be updated to provide additional information
12824 /// about template argument deduction.
12825 ///
12826 /// \param CheckNonDependent A callback to invoke to check conversions for
12827 /// non-dependent parameters, between deduction and substitution, per DR1391.
12828 /// If this returns true, substitution will be skipped and we return
12829 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12830 /// passed the parameter types (after substituting explicit template
12831 /// arguments).
12832 ///
12833 /// \returns the result of template argument deduction.
12834 TemplateDeductionResult DeduceTemplateArguments(
12835 FunctionTemplateDecl *FunctionTemplate,
12836 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12837 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12838 bool PartialOverloading, bool AggregateDeductionCandidate,
12839 bool PartialOrdering, QualType ObjectType,
12840 Expr::Classification ObjectClassification,
12841 bool ForOverloadSetAddressResolution,
12842 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12843
12844 /// Deduce template arguments when taking the address of a function
12845 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12846 /// a template.
12847 ///
12848 /// \param FunctionTemplate the function template for which we are performing
12849 /// template argument deduction.
12850 ///
12851 /// \param ExplicitTemplateArgs the explicitly-specified template
12852 /// arguments.
12853 ///
12854 /// \param ArgFunctionType the function type that will be used as the
12855 /// "argument" type (A) when performing template argument deduction from the
12856 /// function template's function type. This type may be NULL, if there is no
12857 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12858 ///
12859 /// \param Specialization if template argument deduction was successful,
12860 /// this will be set to the function template specialization produced by
12861 /// template argument deduction.
12862 ///
12863 /// \param Info the argument will be updated to provide additional information
12864 /// about template argument deduction.
12865 ///
12866 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12867 /// the address of a function template per [temp.deduct.funcaddr] and
12868 /// [over.over]. If \c false, we are looking up a function template
12869 /// specialization based on its signature, per [temp.deduct.decl].
12870 ///
12871 /// \returns the result of template argument deduction.
12872 TemplateDeductionResult DeduceTemplateArguments(
12873 FunctionTemplateDecl *FunctionTemplate,
12874 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12875 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12876 bool IsAddressOfFunction = false);
12877
12878 /// Deduce template arguments for a templated conversion
12879 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12880 /// conversion function template specialization.
12881 TemplateDeductionResult DeduceTemplateArguments(
12882 FunctionTemplateDecl *FunctionTemplate, QualType ObjectType,
12883 Expr::Classification ObjectClassification, QualType ToType,
12884 CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info);
12885
12886 /// Deduce template arguments for a function template when there is
12887 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
12888 ///
12889 /// \param FunctionTemplate the function template for which we are performing
12890 /// template argument deduction.
12891 ///
12892 /// \param ExplicitTemplateArgs the explicitly-specified template
12893 /// arguments.
12894 ///
12895 /// \param Specialization if template argument deduction was successful,
12896 /// this will be set to the function template specialization produced by
12897 /// template argument deduction.
12898 ///
12899 /// \param Info the argument will be updated to provide additional information
12900 /// about template argument deduction.
12901 ///
12902 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12903 /// the address of a function template in a context where we do not have a
12904 /// target type, per [over.over]. If \c false, we are looking up a function
12905 /// template specialization based on its signature, which only happens when
12906 /// deducing a function parameter type from an argument that is a template-id
12907 /// naming a function template specialization.
12908 ///
12909 /// \returns the result of template argument deduction.
12910 TemplateDeductionResult
12911 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
12912 TemplateArgumentListInfo *ExplicitTemplateArgs,
12913 FunctionDecl *&Specialization,
12914 sema::TemplateDeductionInfo &Info,
12915 bool IsAddressOfFunction = false);
12916
12917 /// Substitute Replacement for \p auto in \p TypeWithAuto
12918 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
12919 /// Substitute Replacement for auto in TypeWithAuto
12920 TypeSourceInfo *SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12921 QualType Replacement);
12922
12923 // Substitute auto in TypeWithAuto for a Dependent auto type
12924 QualType SubstAutoTypeDependent(QualType TypeWithAuto);
12925
12926 // Substitute auto in TypeWithAuto for a Dependent auto type
12927 TypeSourceInfo *
12928 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
12929
12930 /// Completely replace the \c auto in \p TypeWithAuto by
12931 /// \p Replacement. This does not retain any \c auto type sugar.
12932 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
12933 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12934 QualType Replacement);
12935
12936 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
12937 ///
12938 /// Note that this is done even if the initializer is dependent. (This is
12939 /// necessary to support partial ordering of templates using 'auto'.)
12940 /// A dependent type will be produced when deducing from a dependent type.
12941 ///
12942 /// \param Type the type pattern using the auto type-specifier.
12943 /// \param Init the initializer for the variable whose type is to be deduced.
12944 /// \param Result if type deduction was successful, this will be set to the
12945 /// deduced type.
12946 /// \param Info the argument will be updated to provide additional information
12947 /// about template argument deduction.
12948 /// \param DependentDeduction Set if we should permit deduction in
12949 /// dependent cases. This is necessary for template partial ordering
12950 /// with 'auto' template parameters. The template parameter depth to be
12951 /// used should be specified in the 'Info' parameter.
12952 /// \param IgnoreConstraints Set if we should not fail if the deduced type
12953 /// does not satisfy the type-constraint in the auto
12954 /// type.
12955 TemplateDeductionResult
12956 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result,
12957 sema::TemplateDeductionInfo &Info,
12958 bool DependentDeduction = false,
12959 bool IgnoreConstraints = false,
12960 TemplateSpecCandidateSet *FailedTSC = nullptr);
12961 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
12962 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
12963 bool Diagnose = true);
12964
12965 bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
12966 SourceLocation Loc);
12967
12968 /// Returns the more specialized class template partial specialization
12969 /// according to the rules of partial ordering of class template partial
12970 /// specializations (C++ [temp.class.order]).
12971 ///
12972 /// \param PS1 the first class template partial specialization
12973 ///
12974 /// \param PS2 the second class template partial specialization
12975 ///
12976 /// \returns the more specialized class template partial specialization. If
12977 /// neither partial specialization is more specialized, returns NULL.
12978 ClassTemplatePartialSpecializationDecl *
12979 getMoreSpecializedPartialSpecialization(
12980 ClassTemplatePartialSpecializationDecl *PS1,
12981 ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12982
12983 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
12984 sema::TemplateDeductionInfo &Info);
12985
12986 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
12987 VarTemplatePartialSpecializationDecl *PS1,
12988 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12989
12990 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
12991 sema::TemplateDeductionInfo &Info);
12992
12993 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
12994 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
12995 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
12996 bool PartialOrdering, bool *StrictPackMatch);
12997
12998 /// Mark which template parameters are used in a given expression.
12999 ///
13000 /// \param E the expression from which template parameters will be deduced.
13001 ///
13002 /// \param Used a bit vector whose elements will be set to \c true
13003 /// to indicate when the corresponding template parameter will be
13004 /// deduced.
13005 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
13006 unsigned Depth, llvm::SmallBitVector &Used);
13007
13008 /// Mark which template parameters are named in a given expression.
13009 ///
13010 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
13011 /// are used but not directly named by an expression - i.e. it excludes
13012 /// any template parameter that denotes the type of a referenced NTTP.
13013 ///
13014 /// \param Used a bit vector whose elements will be set to \c true
13015 /// to indicate when the corresponding template parameter will be
13016 /// deduced.
13017 void MarkUsedTemplateParametersForSubsumptionParameterMapping(
13018 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
13019
13020 /// Mark which template parameters can be deduced from a given
13021 /// template argument list.
13022 ///
13023 /// \param TemplateArgs the template argument list from which template
13024 /// parameters will be deduced.
13025 ///
13026 /// \param Used a bit vector whose elements will be set to \c true
13027 /// to indicate when the corresponding template parameter will be
13028 /// deduced.
13029 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
13030 bool OnlyDeduced, unsigned Depth,
13031 llvm::SmallBitVector &Used);
13032
13033 void MarkUsedTemplateParameters(ArrayRef<TemplateArgument> TemplateArgs,
13034 unsigned Depth, llvm::SmallBitVector &Used);
13035
13036 void MarkUsedTemplateParameters(ArrayRef<TemplateArgumentLoc> TemplateArgs,
13037 unsigned Depth, llvm::SmallBitVector &Used);
13038
13039 void
13040 MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate,
13041 llvm::SmallBitVector &Deduced) {
13042 return MarkDeducedTemplateParameters(Ctx&: Context, FunctionTemplate, Deduced);
13043 }
13044
13045 /// Marks all of the template parameters that will be deduced by a
13046 /// call to the given function template.
13047 static void
13048 MarkDeducedTemplateParameters(ASTContext &Ctx,
13049 const FunctionTemplateDecl *FunctionTemplate,
13050 llvm::SmallBitVector &Deduced);
13051
13052 /// Returns the more specialized function template according
13053 /// to the rules of function template partial ordering (C++
13054 /// [temp.func.order]).
13055 ///
13056 /// \param FT1 the first function template
13057 ///
13058 /// \param FT2 the second function template
13059 ///
13060 /// \param TPOC the context in which we are performing partial ordering of
13061 /// function templates.
13062 ///
13063 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
13064 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
13065 /// when calling a member function.
13066 ///
13067 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
13068 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
13069 /// template from a member function
13070 ///
13071 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
13072 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
13073 /// template from a member function
13074 ///
13075 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
13076 /// candidate with a reversed parameter order. In this case, the corresponding
13077 /// P/A pairs between FT1 and FT2 are reversed.
13078 ///
13079 /// \returns the more specialized function template. If neither
13080 /// template is more specialized, returns NULL.
13081 FunctionTemplateDecl *getMoreSpecializedTemplate(
13082 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
13083 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
13084 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
13085 bool PartialOverloading = false);
13086
13087 /// Retrieve the most specialized of the given function template
13088 /// specializations.
13089 ///
13090 /// \param SpecBegin the start iterator of the function template
13091 /// specializations that we will be comparing.
13092 ///
13093 /// \param SpecEnd the end iterator of the function template
13094 /// specializations, paired with \p SpecBegin.
13095 ///
13096 /// \param Loc the location where the ambiguity or no-specializations
13097 /// diagnostic should occur.
13098 ///
13099 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
13100 /// no matching candidates.
13101 ///
13102 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
13103 /// occurs.
13104 ///
13105 /// \param CandidateDiag partial diagnostic used for each function template
13106 /// specialization that is a candidate in the ambiguous ordering. One
13107 /// parameter in this diagnostic should be unbound, which will correspond to
13108 /// the string describing the template arguments for the function template
13109 /// specialization.
13110 ///
13111 /// \returns the most specialized function template specialization, if
13112 /// found. Otherwise, returns SpecEnd.
13113 UnresolvedSetIterator
13114 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
13115 TemplateSpecCandidateSet &FailedCandidates,
13116 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
13117 const PartialDiagnostic &AmbigDiag,
13118 const PartialDiagnostic &CandidateDiag,
13119 bool Complain = true, QualType TargetType = QualType());
13120
13121 /// Returns the more constrained function according to the rules of
13122 /// partial ordering by constraints (C++ [temp.constr.order]).
13123 ///
13124 /// \param FD1 the first function
13125 ///
13126 /// \param FD2 the second function
13127 ///
13128 /// \returns the more constrained function. If neither function is
13129 /// more constrained, returns NULL.
13130 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
13131 FunctionDecl *FD2);
13132
13133 ///@}
13134
13135 //
13136 //
13137 // -------------------------------------------------------------------------
13138 //
13139 //
13140
13141 /// \name C++ Template Deduction Guide
13142 /// Implementations are in SemaTemplateDeductionGuide.cpp
13143 ///@{
13144
13145 /// Declare implicit deduction guides for a class template if we've
13146 /// not already done so.
13147 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
13148 SourceLocation Loc);
13149
13150 CXXDeductionGuideDecl *DeclareAggregateDeductionGuideFromInitList(
13151 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
13152 SourceLocation Loc);
13153
13154 ///@}
13155
13156 //
13157 //
13158 // -------------------------------------------------------------------------
13159 //
13160 //
13161
13162 /// \name C++ Template Instantiation
13163 /// Implementations are in SemaTemplateInstantiate.cpp
13164 ///@{
13165
13166public:
13167 /// A helper class for building up ExtParameterInfos.
13168 class ExtParameterInfoBuilder {
13169 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
13170 bool HasInteresting = false;
13171
13172 public:
13173 /// Set the ExtParameterInfo for the parameter at the given index,
13174 ///
13175 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
13176 assert(Infos.size() <= index);
13177 Infos.resize(N: index);
13178 Infos.push_back(Elt: info);
13179
13180 if (!HasInteresting)
13181 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
13182 }
13183
13184 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
13185 /// ExtParameterInfo array we've built up.
13186 const FunctionProtoType::ExtParameterInfo *
13187 getPointerOrNull(unsigned numParams) {
13188 if (!HasInteresting)
13189 return nullptr;
13190 Infos.resize(N: numParams);
13191 return Infos.data();
13192 }
13193 };
13194
13195 /// The current instantiation scope used to store local
13196 /// variables.
13197 LocalInstantiationScope *CurrentInstantiationScope;
13198
13199 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
13200 UnparsedDefaultArgInstantiationsMap;
13201
13202 /// A mapping from parameters with unparsed default arguments to the
13203 /// set of instantiations of each parameter.
13204 ///
13205 /// This mapping is a temporary data structure used when parsing
13206 /// nested class templates or nested classes of class templates,
13207 /// where we might end up instantiating an inner class before the
13208 /// default arguments of its methods have been parsed.
13209 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
13210
13211 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13212
13213 struct RecursiveInstGuard {
13214 enum class Kind {
13215 Template,
13216 DefaultArgument,
13217 ExceptionSpec,
13218 };
13219
13220 RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
13221 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13222 auto [_, Created] = S.InstantiatingSpecializations.insert(V: Key);
13223 if (!Created)
13224 Key = {};
13225 }
13226
13227 ~RecursiveInstGuard() {
13228 if (Key.getOpaqueValue()) {
13229 [[maybe_unused]] bool Erased =
13230 S.InstantiatingSpecializations.erase(V: Key);
13231 assert(Erased);
13232 }
13233 }
13234
13235 RecursiveInstGuard(const RecursiveInstGuard &) = delete;
13236 RecursiveInstGuard &operator=(const RecursiveInstGuard &) = delete;
13237
13238 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13239
13240 private:
13241 Sema &S;
13242 Sema::InstantiatingSpecializationsKey Key;
13243 };
13244
13245 /// A context in which code is being synthesized (where a source location
13246 /// alone is not sufficient to identify the context). This covers template
13247 /// instantiation and various forms of implicitly-generated functions.
13248 struct CodeSynthesisContext {
13249 /// The kind of template instantiation we are performing
13250 enum SynthesisKind {
13251 /// We are instantiating a template declaration. The entity is
13252 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13253 TemplateInstantiation,
13254
13255 /// We are instantiating a default argument for a template
13256 /// parameter. The Entity is the template parameter whose argument is
13257 /// being instantiated, the Template is the template, and the
13258 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13259 /// specified.
13260 DefaultTemplateArgumentInstantiation,
13261
13262 /// We are instantiating a default argument for a function.
13263 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13264 /// provides the template arguments as specified.
13265 DefaultFunctionArgumentInstantiation,
13266
13267 /// We are substituting explicit template arguments provided for
13268 /// a function template. The entity is a FunctionTemplateDecl.
13269 ExplicitTemplateArgumentSubstitution,
13270
13271 /// We are substituting template argument determined as part of
13272 /// template argument deduction for either a class template
13273 /// partial specialization or a function template. The
13274 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13275 /// a TemplateDecl.
13276 DeducedTemplateArgumentSubstitution,
13277
13278 /// We are substituting into a lambda expression.
13279 LambdaExpressionSubstitution,
13280
13281 /// We are substituting prior template arguments into a new
13282 /// template parameter. The template parameter itself is either a
13283 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13284 PriorTemplateArgumentSubstitution,
13285
13286 /// We are checking the validity of a default template argument that
13287 /// has been used when naming a template-id.
13288 DefaultTemplateArgumentChecking,
13289
13290 /// We are computing the exception specification for a defaulted special
13291 /// member function.
13292 ExceptionSpecEvaluation,
13293
13294 /// We are instantiating the exception specification for a function
13295 /// template which was deferred until it was needed.
13296 ExceptionSpecInstantiation,
13297
13298 /// We are instantiating a requirement of a requires expression.
13299 RequirementInstantiation,
13300
13301 /// We are checking the satisfaction of a nested requirement of a requires
13302 /// expression.
13303 NestedRequirementConstraintsCheck,
13304
13305 /// We are declaring an implicit special member function.
13306 DeclaringSpecialMember,
13307
13308 /// We are declaring an implicit 'operator==' for a defaulted
13309 /// 'operator<=>'.
13310 DeclaringImplicitEqualityComparison,
13311
13312 /// We are defining a synthesized function (such as a defaulted special
13313 /// member).
13314 DefiningSynthesizedFunction,
13315
13316 // We are checking the constraints associated with a constrained entity or
13317 // the constraint expression of a concept. This includes the checks that
13318 // atomic constraints have the type 'bool' and that they can be constant
13319 // evaluated.
13320 ConstraintsCheck,
13321
13322 // We are substituting template arguments into a constraint expression.
13323 ConstraintSubstitution,
13324
13325 // Instantiating a Requires Expression parameter clause.
13326 RequirementParameterInstantiation,
13327
13328 // We are substituting into the parameter mapping of an atomic constraint
13329 // during normalization.
13330 ParameterMappingSubstitution,
13331
13332 /// We are rewriting a comparison operator in terms of an operator<=>.
13333 RewritingOperatorAsSpaceship,
13334
13335 /// We are initializing a structured binding.
13336 InitializingStructuredBinding,
13337
13338 /// We are marking a class as __dllexport.
13339 MarkingClassDllexported,
13340
13341 /// We are building an implied call from __builtin_dump_struct. The
13342 /// arguments are in CallArgs.
13343 BuildingBuiltinDumpStructCall,
13344
13345 /// Added for Template instantiation observation.
13346 /// Memoization means we are _not_ instantiating a template because
13347 /// it is already instantiated (but we entered a context where we
13348 /// would have had to if it was not already instantiated).
13349 Memoization,
13350
13351 /// We are building deduction guides for a class.
13352 BuildingDeductionGuides,
13353
13354 /// We are instantiating a type alias template declaration.
13355 TypeAliasTemplateInstantiation,
13356
13357 /// We are performing partial ordering for template template parameters.
13358 PartialOrderingTTP,
13359
13360 /// We are performing name lookup for a function template or variable
13361 /// template named 'sycl_kernel_launch'.
13362 SYCLKernelLaunchLookup,
13363
13364 /// We are performing overload resolution for a call to a function
13365 /// template or variable template named 'sycl_kernel_launch'.
13366 SYCLKernelLaunchOverloadResolution,
13367
13368 /// We are instantiating an expansion statement.
13369 ExpansionStmtInstantiation,
13370 } Kind;
13371
13372 /// Whether we're substituting into constraints.
13373 bool InConstraintSubstitution;
13374
13375 /// Whether we're substituting into the parameter mapping of a constraint.
13376 bool InParameterMappingSubstitution;
13377
13378 /// The point of instantiation or synthesis within the source code.
13379 SourceLocation PointOfInstantiation;
13380
13381 /// The entity that is being synthesized.
13382 Decl *Entity;
13383
13384 /// The template (or partial specialization) in which we are
13385 /// performing the instantiation, for substitutions of prior template
13386 /// arguments.
13387 NamedDecl *Template;
13388
13389 union {
13390 /// The list of template arguments we are substituting, if they
13391 /// are not part of the entity.
13392 const TemplateArgument *TemplateArgs;
13393
13394 /// The list of argument expressions in a synthesized call.
13395 const Expr *const *CallArgs;
13396 };
13397
13398 // FIXME: Wrap this union around more members, or perhaps store the
13399 // kind-specific members in the RAII object owning the context.
13400 union {
13401 /// The number of template arguments in TemplateArgs.
13402 unsigned NumTemplateArgs;
13403
13404 /// The number of expressions in CallArgs.
13405 unsigned NumCallArgs;
13406
13407 /// The special member being declared or defined.
13408 CXXSpecialMemberKind SpecialMember;
13409 };
13410
13411 ArrayRef<TemplateArgument> template_arguments() const {
13412 assert(Kind != DeclaringSpecialMember);
13413 return {TemplateArgs, NumTemplateArgs};
13414 }
13415
13416 /// The source range that covers the construct that cause
13417 /// the instantiation, e.g., the template-id that causes a class
13418 /// template instantiation.
13419 SourceRange InstantiationRange;
13420
13421 CodeSynthesisContext()
13422 : Kind(TemplateInstantiation), InConstraintSubstitution(false),
13423 InParameterMappingSubstitution(false), Entity(nullptr),
13424 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0) {}
13425
13426 /// Determines whether this template is an actual instantiation
13427 /// that should be counted toward the maximum instantiation depth.
13428 bool isInstantiationRecord() const;
13429 };
13430
13431 /// A stack object to be created when performing template
13432 /// instantiation.
13433 ///
13434 /// Construction of an object of type \c InstantiatingTemplate
13435 /// pushes the current instantiation onto the stack of active
13436 /// instantiations. If the size of this stack exceeds the maximum
13437 /// number of recursive template instantiations, construction
13438 /// produces an error and evaluates true.
13439 ///
13440 /// Destruction of this object will pop the named instantiation off
13441 /// the stack.
13442 struct InstantiatingTemplate {
13443 /// Note that we are instantiating a class template,
13444 /// function template, variable template, alias template,
13445 /// or a member thereof.
13446 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13447 Decl *Entity,
13448 SourceRange InstantiationRange = SourceRange());
13449
13450 struct ExceptionSpecification {};
13451 /// Note that we are instantiating an exception specification
13452 /// of a function template.
13453 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13454 FunctionDecl *Entity, ExceptionSpecification,
13455 SourceRange InstantiationRange = SourceRange());
13456
13457 /// Note that we are instantiating a type alias template declaration.
13458 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13459 TypeAliasTemplateDecl *Entity,
13460 ArrayRef<TemplateArgument> TemplateArgs,
13461 SourceRange InstantiationRange = SourceRange());
13462
13463 /// Note that we are instantiating a default argument in a
13464 /// template-id.
13465 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13466 TemplateParameter Param, TemplateDecl *Template,
13467 ArrayRef<TemplateArgument> TemplateArgs,
13468 SourceRange InstantiationRange = SourceRange());
13469
13470 /// Note that we are substituting either explicitly-specified or
13471 /// deduced template arguments during function template argument deduction.
13472 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13473 FunctionTemplateDecl *FunctionTemplate,
13474 ArrayRef<TemplateArgument> TemplateArgs,
13475 CodeSynthesisContext::SynthesisKind Kind,
13476 SourceRange InstantiationRange = SourceRange());
13477
13478 /// Note that we are instantiating as part of template
13479 /// argument deduction for a class template declaration.
13480 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13481 TemplateDecl *Template,
13482 ArrayRef<TemplateArgument> TemplateArgs,
13483 SourceRange InstantiationRange = SourceRange());
13484
13485 /// Note that we are instantiating as part of template
13486 /// argument deduction for a class template partial
13487 /// specialization.
13488 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13489 ClassTemplatePartialSpecializationDecl *PartialSpec,
13490 ArrayRef<TemplateArgument> TemplateArgs,
13491 SourceRange InstantiationRange = SourceRange());
13492
13493 /// Note that we are instantiating as part of template
13494 /// argument deduction for a variable template partial
13495 /// specialization.
13496 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13497 VarTemplatePartialSpecializationDecl *PartialSpec,
13498 ArrayRef<TemplateArgument> TemplateArgs,
13499 SourceRange InstantiationRange = SourceRange());
13500
13501 /// Note that we are instantiating a default argument for a function
13502 /// parameter.
13503 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13504 ParmVarDecl *Param,
13505 ArrayRef<TemplateArgument> TemplateArgs,
13506 SourceRange InstantiationRange = SourceRange());
13507
13508 /// Note that we are substituting prior template arguments into a
13509 /// non-type parameter.
13510 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13511 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
13512 ArrayRef<TemplateArgument> TemplateArgs,
13513 SourceRange InstantiationRange);
13514
13515 /// Note that we are substituting prior template arguments into a
13516 /// template template parameter.
13517 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13518 NamedDecl *Template, TemplateTemplateParmDecl *Param,
13519 ArrayRef<TemplateArgument> TemplateArgs,
13520 SourceRange InstantiationRange);
13521
13522 /// Note that we are checking the default template argument
13523 /// against the template parameter for a given template-id.
13524 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13525 TemplateDecl *Template, NamedDecl *Param,
13526 ArrayRef<TemplateArgument> TemplateArgs,
13527 SourceRange InstantiationRange);
13528
13529 struct ConstraintsCheck {};
13530 /// \brief Note that we are checking the constraints associated with some
13531 /// constrained entity (a concept declaration or a template with associated
13532 /// constraints).
13533 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13534 ConstraintsCheck, NamedDecl *Template,
13535 ArrayRef<TemplateArgument> TemplateArgs,
13536 SourceRange InstantiationRange);
13537
13538 struct ConstraintSubstitution {};
13539 /// \brief Note that we are checking a constraint expression associated
13540 /// with a template declaration or as part of the satisfaction check of a
13541 /// concept.
13542 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13543 ConstraintSubstitution, NamedDecl *Template,
13544 SourceRange InstantiationRange);
13545
13546 struct ParameterMappingSubstitution {};
13547 /// \brief Note that we are subtituting into the parameter mapping of an
13548 /// atomic constraint during constraint normalization.
13549 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13550 ParameterMappingSubstitution, NamedDecl *Template,
13551 SourceRange InstantiationRange);
13552
13553 /// \brief Note that we are substituting template arguments into a part of
13554 /// a requirement of a requires expression.
13555 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13556 concepts::Requirement *Req,
13557 SourceRange InstantiationRange = SourceRange());
13558
13559 /// \brief Note that we are substituting the body of an expansion statement.
13560 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13561 CXXExpansionStmtPattern *ExpansionStmt,
13562 ArrayRef<TemplateArgument> TArgs,
13563 SourceRange InstantiationRange);
13564
13565 /// \brief Note that we are checking the satisfaction of the constraint
13566 /// expression inside of a nested requirement.
13567 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13568 concepts::NestedRequirement *Req, ConstraintsCheck,
13569 SourceRange InstantiationRange = SourceRange());
13570
13571 /// \brief Note that we are checking a requires clause.
13572 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13573 const RequiresExpr *E,
13574 SourceRange InstantiationRange);
13575
13576 struct BuildingDeductionGuidesTag {};
13577 /// \brief Note that we are building deduction guides.
13578 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13579 TemplateDecl *Entity, BuildingDeductionGuidesTag,
13580 SourceRange InstantiationRange = SourceRange());
13581
13582 struct PartialOrderingTTP {};
13583 /// \brief Note that we are partial ordering template template parameters.
13584 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13585 PartialOrderingTTP, TemplateDecl *PArg,
13586 SourceRange InstantiationRange = SourceRange());
13587
13588 /// Note that we have finished instantiating this template.
13589 void Clear();
13590
13591 ~InstantiatingTemplate() { Clear(); }
13592
13593 /// Determines whether we have exceeded the maximum
13594 /// recursive template instantiations.
13595 bool isInvalid() const { return Invalid; }
13596
13597 private:
13598 Sema &SemaRef;
13599 bool Invalid;
13600
13601 InstantiatingTemplate(Sema &SemaRef,
13602 CodeSynthesisContext::SynthesisKind Kind,
13603 SourceLocation PointOfInstantiation,
13604 SourceRange InstantiationRange, Decl *Entity,
13605 NamedDecl *Template = nullptr,
13606 ArrayRef<TemplateArgument> TemplateArgs = {});
13607
13608 InstantiatingTemplate(const InstantiatingTemplate &) = delete;
13609
13610 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13611 };
13612
13613 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13614 const MultiLevelTemplateArgumentList &TemplateArgs,
13615 TemplateArgumentLoc &Output,
13616 SourceLocation Loc = {},
13617 const DeclarationName &Entity = {});
13618 bool
13619 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13620 const MultiLevelTemplateArgumentList &TemplateArgs,
13621 TemplateArgumentListInfo &Outputs);
13622
13623 /// Substitute concept template arguments in the constraint expression
13624 /// of a concept-id. This is used to implement [temp.constr.normal].
13625 ExprResult
13626 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13627 const Expr *ConstraintExpr,
13628 const MultiLevelTemplateArgumentList &MLTAL);
13629
13630 bool SubstTemplateArgumentsInParameterMapping(
13631 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13632 const MultiLevelTemplateArgumentList &TemplateArgs,
13633 TemplateArgumentListInfo &Out);
13634
13635 /// Retrieve the template argument list(s) that should be used to
13636 /// instantiate the definition of the given declaration.
13637 ///
13638 /// \param ND the declaration for which we are computing template
13639 /// instantiation arguments.
13640 ///
13641 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13642 /// the decl context where it will be created. In this case, the `Innermost`
13643 /// should likely be provided. If ND is non-null, this is ignored.
13644 ///
13645 /// \param Innermost if non-NULL, specifies a template argument list for the
13646 /// template declaration passed as ND.
13647 ///
13648 /// \param RelativeToPrimary true if we should get the template
13649 /// arguments relative to the primary template, even when we're
13650 /// dealing with a specialization. This is only relevant for function
13651 /// template specializations.
13652 ///
13653 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13654 /// instantiating the definition of the given declaration, \p ND. This is
13655 /// used to determine the proper set of template instantiation arguments for
13656 /// friend function template specializations.
13657 ///
13658 /// \param ForConstraintInstantiation when collecting arguments,
13659 /// ForConstraintInstantiation indicates we should continue looking when
13660 /// encountering a lambda generic call operator, and continue looking for
13661 /// arguments on an enclosing class template.
13662 ///
13663 /// \param SkipForSpecialization when specified, any template specializations
13664 /// in a traversal would be ignored.
13665 ///
13666 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13667 /// when encountering a specialized member function template, rather than
13668 /// returning immediately.
13669 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13670 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13671 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13672 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13673 bool ForConstraintInstantiation = false,
13674 bool SkipForSpecialization = false,
13675 bool ForDefaultArgumentSubstitution = false);
13676
13677 /// RAII object to handle the state changes required to synthesize
13678 /// a function body.
13679 class SynthesizedFunctionScope {
13680 Sema &S;
13681 Sema::ContextRAII SavedContext;
13682 bool PushedCodeSynthesisContext = false;
13683
13684 public:
13685 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
13686 : S(S), SavedContext(S, DC) {
13687 auto *FD = dyn_cast<FunctionDecl>(Val: DC);
13688 S.PushFunctionScope();
13689 S.PushExpressionEvaluationContextForFunction(
13690 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, FD);
13691 if (FD)
13692 FD->setWillHaveBody(true);
13693 else
13694 assert(isa<ObjCMethodDecl>(DC));
13695 }
13696
13697 void addContextNote(SourceLocation UseLoc) {
13698 assert(!PushedCodeSynthesisContext);
13699
13700 Sema::CodeSynthesisContext Ctx;
13701 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
13702 Ctx.PointOfInstantiation = UseLoc;
13703 Ctx.Entity = cast<Decl>(Val: S.CurContext);
13704 S.pushCodeSynthesisContext(Ctx);
13705
13706 PushedCodeSynthesisContext = true;
13707 }
13708
13709 ~SynthesizedFunctionScope() {
13710 if (PushedCodeSynthesisContext)
13711 S.popCodeSynthesisContext();
13712 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
13713 FD->setWillHaveBody(false);
13714 S.CheckImmediateEscalatingFunctionDefinition(FD, FSI: S.getCurFunction());
13715 }
13716 S.PopExpressionEvaluationContext();
13717 S.PopFunctionScopeInfo();
13718 }
13719
13720 SynthesizedFunctionScope(const SynthesizedFunctionScope &) = delete;
13721 SynthesizedFunctionScope &
13722 operator=(const SynthesizedFunctionScope &) = delete;
13723 };
13724
13725 /// RAII object to ensure that a code synthesis context is popped on scope
13726 /// exit.
13727 class ScopedCodeSynthesisContext {
13728 Sema &S;
13729
13730 public:
13731 ScopedCodeSynthesisContext(Sema &S, const CodeSynthesisContext &Ctx)
13732 : S(S) {
13733 S.pushCodeSynthesisContext(Ctx);
13734 }
13735
13736 ~ScopedCodeSynthesisContext() { S.popCodeSynthesisContext(); }
13737 ScopedCodeSynthesisContext(const ScopedCodeSynthesisContext &) = delete;
13738 ScopedCodeSynthesisContext &
13739 operator=(const ScopedCodeSynthesisContext &) = delete;
13740 };
13741
13742 /// List of active code synthesis contexts.
13743 ///
13744 /// This vector is treated as a stack. As synthesis of one entity requires
13745 /// synthesis of another, additional contexts are pushed onto the stack.
13746 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
13747
13748 /// Specializations whose definitions are currently being instantiated.
13749 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13750
13751 /// Non-dependent types used in templates that have already been instantiated
13752 /// by some template instantiation.
13753 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13754
13755 /// Extra modules inspected when performing a lookup during a template
13756 /// instantiation. Computed lazily.
13757 SmallVector<Module *, 16> CodeSynthesisContextLookupModules;
13758
13759 /// Cache of additional modules that should be used for name lookup
13760 /// within the current template instantiation. Computed lazily; use
13761 /// getLookupModules() to get a complete set.
13762 llvm::DenseSet<Module *> LookupModulesCache;
13763
13764 /// Map from the most recent declaration of a namespace to the most
13765 /// recent visible declaration of that namespace.
13766 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13767
13768 SFINAETrap *CurrentSFINAEContext = nullptr;
13769
13770 /// The number of \p CodeSynthesisContexts that are not template
13771 /// instantiations and, therefore, should not be counted as part of the
13772 /// instantiation depth.
13773 ///
13774 /// When the instantiation depth reaches the user-configurable limit
13775 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13776 // FIXME: Should we have a similar limit for other forms of synthesis?
13777 unsigned NonInstantiationEntries;
13778
13779 /// The depth of the context stack at the point when the most recent
13780 /// error or warning was produced.
13781 ///
13782 /// This value is used to suppress printing of redundant context stacks
13783 /// when there are multiple errors or warnings in the same instantiation.
13784 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13785 unsigned LastEmittedCodeSynthesisContextDepth = 0;
13786
13787 /// The current index into pack expansion arguments that will be
13788 /// used for substitution of parameter packs.
13789 ///
13790 /// The pack expansion index will be none to indicate that parameter packs
13791 /// should be instantiated as themselves. Otherwise, the index specifies
13792 /// which argument within the parameter pack will be used for substitution.
13793 UnsignedOrNone ArgPackSubstIndex;
13794
13795 /// RAII object used to change the argument pack substitution index
13796 /// within a \c Sema object.
13797 ///
13798 /// See \c ArgPackSubstIndex for more information.
13799 class ArgPackSubstIndexRAII {
13800 Sema &Self;
13801 UnsignedOrNone OldSubstIndex;
13802
13803 public:
13804 ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
13805 : Self(Self),
13806 OldSubstIndex(std::exchange(obj&: Self.ArgPackSubstIndex, new_val&: NewSubstIndex)) {}
13807
13808 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13809 ArgPackSubstIndexRAII(const ArgPackSubstIndexRAII &) = delete;
13810 ArgPackSubstIndexRAII &operator=(const ArgPackSubstIndexRAII &) = delete;
13811 };
13812
13813 bool pushCodeSynthesisContext(CodeSynthesisContext Ctx);
13814 void popCodeSynthesisContext();
13815
13816 void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc) {
13817 if (!CodeSynthesisContexts.empty() &&
13818 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
13819 PrintInstantiationStack(DiagFunc);
13820 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
13821 }
13822 if (PragmaAttributeCurrentTargetDecl)
13823 PrintPragmaAttributeInstantiationPoint(DiagFunc);
13824 }
13825 void PrintContextStack() { PrintContextStack(DiagFunc: getDefaultDiagFunc()); }
13826 /// Prints the current instantiation stack through a series of
13827 /// notes.
13828 void PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc);
13829 void PrintInstantiationStack() {
13830 PrintInstantiationStack(DiagFunc: getDefaultDiagFunc());
13831 }
13832
13833 /// Returns a pointer to the current SFINAE context, if any.
13834 [[nodiscard]] SFINAETrap *getSFINAEContext() const {
13835 return CurrentSFINAEContext;
13836 }
13837 [[nodiscard]] bool isSFINAEContext() const {
13838 return CurrentSFINAEContext != nullptr;
13839 }
13840
13841 /// Perform substitution on the type T with a given set of template
13842 /// arguments.
13843 ///
13844 /// This routine substitutes the given template arguments into the
13845 /// type T and produces the instantiated type.
13846 ///
13847 /// \param T the type into which the template arguments will be
13848 /// substituted. If this type is not dependent, it will be returned
13849 /// immediately.
13850 ///
13851 /// \param Args the template arguments that will be
13852 /// substituted for the top-level template parameters within T.
13853 ///
13854 /// \param Loc the location in the source code where this substitution
13855 /// is being performed. It will typically be the location of the
13856 /// declarator (if we're instantiating the type of some declaration)
13857 /// or the location of the type in the source code (if, e.g., we're
13858 /// instantiating the type of a cast expression).
13859 ///
13860 /// \param Entity the name of the entity associated with a declaration
13861 /// being instantiated (if any). May be empty to indicate that there
13862 /// is no such entity (if, e.g., this is a type that occurs as part of
13863 /// a cast expression) or that the entity has no name (e.g., an
13864 /// unnamed function parameter).
13865 ///
13866 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13867 /// acceptable as the top level type of the result.
13868 ///
13869 /// \param IsIncompleteSubstitution If provided, the pointee will be set
13870 /// whenever substitution would perform a replacement with a null or
13871 /// non-existent template argument.
13872 ///
13873 /// \returns If the instantiation succeeds, the instantiated
13874 /// type. Otherwise, produces diagnostics and returns a NULL type.
13875 TypeSourceInfo *SubstType(TypeSourceInfo *T,
13876 const MultiLevelTemplateArgumentList &TemplateArgs,
13877 SourceLocation Loc, DeclarationName Entity,
13878 bool AllowDeducedTST = false);
13879
13880 QualType SubstType(QualType T,
13881 const MultiLevelTemplateArgumentList &TemplateArgs,
13882 SourceLocation Loc, DeclarationName Entity,
13883 bool *IsIncompleteSubstitution = nullptr);
13884
13885 TypeSourceInfo *SubstType(TypeLoc TL,
13886 const MultiLevelTemplateArgumentList &TemplateArgs,
13887 SourceLocation Loc, DeclarationName Entity);
13888
13889 /// A form of SubstType intended specifically for instantiating the
13890 /// type of a FunctionDecl. Its purpose is solely to force the
13891 /// instantiation of default-argument expressions and to avoid
13892 /// instantiating an exception-specification.
13893 TypeSourceInfo *SubstFunctionDeclType(
13894 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
13895 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
13896 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
13897 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
13898 const MultiLevelTemplateArgumentList &Args);
13899 bool SubstExceptionSpec(SourceLocation Loc,
13900 FunctionProtoType::ExceptionSpecInfo &ESI,
13901 SmallVectorImpl<QualType> &ExceptionStorage,
13902 const MultiLevelTemplateArgumentList &Args);
13903 ParmVarDecl *
13904 SubstParmVarDecl(ParmVarDecl *D,
13905 const MultiLevelTemplateArgumentList &TemplateArgs,
13906 int indexAdjustment, UnsignedOrNone NumExpansions,
13907 bool ExpectParameterPack, bool EvaluateConstraints = true);
13908
13909 /// Substitute the given template arguments into the given set of
13910 /// parameters, producing the set of parameter types that would be generated
13911 /// from such a substitution.
13912 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
13913 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
13914 const MultiLevelTemplateArgumentList &TemplateArgs,
13915 SmallVectorImpl<QualType> &ParamTypes,
13916 SmallVectorImpl<ParmVarDecl *> *OutParams,
13917 ExtParameterInfoBuilder &ParamInfos);
13918
13919 /// Substitute the given template arguments into the default argument.
13920 bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
13921 const MultiLevelTemplateArgumentList &TemplateArgs,
13922 bool ForCallExpr = false);
13923 ExprResult SubstExpr(Expr *E,
13924 const MultiLevelTemplateArgumentList &TemplateArgs);
13925 /// Substitute an expression as if it is a address-of-operand, which makes it
13926 /// act like a CXXIdExpression rather than an attempt to call.
13927 ExprResult SubstCXXIdExpr(Expr *E,
13928 const MultiLevelTemplateArgumentList &TemplateArgs);
13929
13930 // Must be used instead of SubstExpr at 'constraint checking' time.
13931 ExprResult
13932 SubstConstraintExpr(Expr *E,
13933 const MultiLevelTemplateArgumentList &TemplateArgs);
13934 // Unlike the above, this does not evaluate constraints.
13935 ExprResult SubstConstraintExprWithoutSatisfaction(
13936 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
13937
13938 /// Substitute the given template arguments into a list of
13939 /// expressions, expanding pack expansions if required.
13940 ///
13941 /// \param Exprs The list of expressions to substitute into.
13942 ///
13943 /// \param IsCall Whether this is some form of call, in which case
13944 /// default arguments will be dropped.
13945 ///
13946 /// \param TemplateArgs The set of template arguments to substitute.
13947 ///
13948 /// \param Outputs Will receive all of the substituted arguments.
13949 ///
13950 /// \returns true if an error occurred, false otherwise.
13951 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
13952 const MultiLevelTemplateArgumentList &TemplateArgs,
13953 SmallVectorImpl<Expr *> &Outputs);
13954
13955 StmtResult SubstStmt(Stmt *S,
13956 const MultiLevelTemplateArgumentList &TemplateArgs);
13957
13958 ExprResult
13959 SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs,
13960 bool CXXDirectInit);
13961
13962 /// Perform substitution on the base class specifiers of the
13963 /// given class template specialization.
13964 ///
13965 /// Produces a diagnostic and returns true on error, returns false and
13966 /// attaches the instantiated base classes to the class template
13967 /// specialization if successful.
13968 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13969 const MultiLevelTemplateArgumentList &TemplateArgs);
13970
13971 /// Instantiate the definition of a class from a given pattern.
13972 ///
13973 /// \param PointOfInstantiation The point of instantiation within the
13974 /// source code.
13975 ///
13976 /// \param Instantiation is the declaration whose definition is being
13977 /// instantiated. This will be either a class template specialization
13978 /// or a member class of a class template specialization.
13979 ///
13980 /// \param Pattern is the pattern from which the instantiation
13981 /// occurs. This will be either the declaration of a class template or
13982 /// the declaration of a member class of a class template.
13983 ///
13984 /// \param TemplateArgs The template arguments to be substituted into
13985 /// the pattern.
13986 ///
13987 /// \param TSK the kind of implicit or explicit instantiation to perform.
13988 ///
13989 /// \param Complain whether to complain if the class cannot be instantiated
13990 /// due to the lack of a definition.
13991 ///
13992 /// \returns true if an error occurred, false otherwise.
13993 bool InstantiateClass(SourceLocation PointOfInstantiation,
13994 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13995 const MultiLevelTemplateArgumentList &TemplateArgs,
13996 TemplateSpecializationKind TSK, bool Complain = true);
13997
13998private:
13999 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
14000 CXXRecordDecl *Instantiation,
14001 CXXRecordDecl *Pattern,
14002 const MultiLevelTemplateArgumentList &TemplateArgs,
14003 TemplateSpecializationKind TSK, bool Complain);
14004
14005public:
14006 /// Instantiate the definition of an enum from a given pattern.
14007 ///
14008 /// \param PointOfInstantiation The point of instantiation within the
14009 /// source code.
14010 /// \param Instantiation is the declaration whose definition is being
14011 /// instantiated. This will be a member enumeration of a class
14012 /// temploid specialization, or a local enumeration within a
14013 /// function temploid specialization.
14014 /// \param Pattern The templated declaration from which the instantiation
14015 /// occurs.
14016 /// \param TemplateArgs The template arguments to be substituted into
14017 /// the pattern.
14018 /// \param TSK The kind of implicit or explicit instantiation to perform.
14019 ///
14020 /// \return \c true if an error occurred, \c false otherwise.
14021 bool InstantiateEnum(SourceLocation PointOfInstantiation,
14022 EnumDecl *Instantiation, EnumDecl *Pattern,
14023 const MultiLevelTemplateArgumentList &TemplateArgs,
14024 TemplateSpecializationKind TSK);
14025
14026 /// Instantiate the definition of a field from the given pattern.
14027 ///
14028 /// \param PointOfInstantiation The point of instantiation within the
14029 /// source code.
14030 /// \param Instantiation is the declaration whose definition is being
14031 /// instantiated. This will be a class of a class temploid
14032 /// specialization, or a local enumeration within a function temploid
14033 /// specialization.
14034 /// \param Pattern The templated declaration from which the instantiation
14035 /// occurs.
14036 /// \param TemplateArgs The template arguments to be substituted into
14037 /// the pattern.
14038 ///
14039 /// \return \c true if an error occurred, \c false otherwise.
14040 bool InstantiateInClassInitializer(
14041 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
14042 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
14043
14044 bool usesPartialOrExplicitSpecialization(
14045 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
14046
14047 bool InstantiateClassTemplateSpecialization(
14048 SourceLocation PointOfInstantiation,
14049 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14050 TemplateSpecializationKind TSK, bool Complain,
14051 bool PrimaryStrictPackMatch);
14052
14053 /// Instantiates the definitions of all of the member
14054 /// of the given class, which is an instantiation of a class template
14055 /// or a member class of a template.
14056 void
14057 InstantiateClassMembers(SourceLocation PointOfInstantiation,
14058 CXXRecordDecl *Instantiation,
14059 const MultiLevelTemplateArgumentList &TemplateArgs,
14060 TemplateSpecializationKind TSK);
14061
14062 /// Instantiate the definitions of all of the members of the
14063 /// given class template specialization, which was named as part of an
14064 /// explicit instantiation.
14065 void InstantiateClassTemplateSpecializationMembers(
14066 SourceLocation PointOfInstantiation,
14067 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14068 TemplateSpecializationKind TSK);
14069
14070 NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(
14071 NestedNameSpecifierLoc NNS,
14072 const MultiLevelTemplateArgumentList &TemplateArgs);
14073
14074 /// Do template substitution on declaration name info.
14075 DeclarationNameInfo
14076 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
14077 const MultiLevelTemplateArgumentList &TemplateArgs);
14078 TemplateName
14079 SubstTemplateName(SourceLocation TemplateKWLoc,
14080 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
14081 SourceLocation NameLoc,
14082 const MultiLevelTemplateArgumentList &TemplateArgs);
14083
14084 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
14085 const MultiLevelTemplateArgumentList &TemplateArgs,
14086 bool EvaluateConstraint);
14087
14088 /// Determine whether we are currently performing template instantiation.
14089 bool inTemplateInstantiation() const {
14090 return CodeSynthesisContexts.size() > NonInstantiationEntries;
14091 }
14092
14093 /// Determine whether we are currently performing constraint substitution.
14094 bool inConstraintSubstitution() const {
14095 return !CodeSynthesisContexts.empty() &&
14096 CodeSynthesisContexts.back().InConstraintSubstitution;
14097 }
14098
14099 bool inParameterMappingSubstitution() const {
14100 return !CodeSynthesisContexts.empty() &&
14101 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
14102 !inConstraintSubstitution();
14103 }
14104
14105 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
14106
14107 /// \brief create a Requirement::SubstitutionDiagnostic with only a
14108 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
14109 concepts::Requirement::SubstitutionDiagnostic *
14110 createSubstDiagAt(SourceLocation Location, EntityPrinter Printer);
14111
14112 ///@}
14113
14114 //
14115 //
14116 // -------------------------------------------------------------------------
14117 //
14118 //
14119
14120 /// \name C++ Template Declaration Instantiation
14121 /// Implementations are in SemaTemplateInstantiateDecl.cpp
14122 ///@{
14123
14124public:
14125 /// An entity for which implicit template instantiation is required.
14126 ///
14127 /// The source location associated with the declaration is the first place in
14128 /// the source code where the declaration was "used". It is not necessarily
14129 /// the point of instantiation (which will be either before or after the
14130 /// namespace-scope declaration that triggered this implicit instantiation),
14131 /// However, it is the location that diagnostics should generally refer to,
14132 /// because users will need to know what code triggered the instantiation.
14133 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
14134
14135 /// The queue of implicit template instantiations that are required
14136 /// but have not yet been performed.
14137 std::deque<PendingImplicitInstantiation> PendingInstantiations;
14138
14139 /// Queue of implicit template instantiations that cannot be performed
14140 /// eagerly.
14141 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
14142
14143 SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses;
14144 SmallVector<std::deque<PendingImplicitInstantiation>, 8>
14145 SavedPendingInstantiations;
14146
14147 /// The queue of implicit template instantiations that are required
14148 /// and must be performed within the current local scope.
14149 ///
14150 /// This queue is only used for member functions of local classes in
14151 /// templates, which must be instantiated in the same scope as their
14152 /// enclosing function, so that they can reference function-local
14153 /// types, static variables, enumerators, etc.
14154 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
14155
14156 class LocalEagerInstantiationScope {
14157 public:
14158 LocalEagerInstantiationScope(Sema &S, bool AtEndOfTU)
14159 : S(S), AtEndOfTU(AtEndOfTU) {
14160 SavedPendingLocalImplicitInstantiations.swap(
14161 x&: S.PendingLocalImplicitInstantiations);
14162 }
14163
14164 void perform() {
14165 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: true,
14166 /*AtEndOfTU=*/AtEndOfTU);
14167 }
14168
14169 ~LocalEagerInstantiationScope() {
14170 assert(S.PendingLocalImplicitInstantiations.empty() &&
14171 "there shouldn't be any pending local implicit instantiations");
14172 SavedPendingLocalImplicitInstantiations.swap(
14173 x&: S.PendingLocalImplicitInstantiations);
14174 }
14175
14176 LocalEagerInstantiationScope(const LocalEagerInstantiationScope &) = delete;
14177 LocalEagerInstantiationScope &
14178 operator=(const LocalEagerInstantiationScope &) = delete;
14179
14180 private:
14181 Sema &S;
14182 bool AtEndOfTU;
14183 std::deque<PendingImplicitInstantiation>
14184 SavedPendingLocalImplicitInstantiations;
14185 };
14186
14187 /// Records and restores the CurFPFeatures state on entry/exit of compound
14188 /// statements.
14189 class FPFeaturesStateRAII {
14190 public:
14191 FPFeaturesStateRAII(Sema &S);
14192 ~FPFeaturesStateRAII();
14193 FPFeaturesStateRAII(const FPFeaturesStateRAII &) = delete;
14194 FPFeaturesStateRAII &operator=(const FPFeaturesStateRAII &) = delete;
14195 FPOptionsOverride getOverrides() { return OldOverrides; }
14196
14197 private:
14198 Sema &S;
14199 FPOptions OldFPFeaturesState;
14200 FPOptionsOverride OldOverrides;
14201 LangOptions::FPEvalMethodKind OldEvalMethod;
14202 SourceLocation OldFPPragmaLocation;
14203 };
14204
14205 class GlobalEagerInstantiationScope {
14206 public:
14207 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14208 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14209 if (!Enabled)
14210 return;
14211
14212 S.SavedPendingInstantiations.emplace_back();
14213 S.SavedPendingInstantiations.back().swap(x&: S.PendingInstantiations);
14214
14215 S.SavedVTableUses.emplace_back();
14216 S.SavedVTableUses.back().swap(RHS&: S.VTableUses);
14217 }
14218
14219 void perform() {
14220 if (Enabled) {
14221 S.DefineUsedVTables();
14222 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: false,
14223 /*AtEndOfTU=*/AtEndOfTU);
14224 }
14225 }
14226
14227 ~GlobalEagerInstantiationScope() {
14228 if (!Enabled)
14229 return;
14230
14231 // Restore the set of pending vtables.
14232 assert(S.VTableUses.empty() &&
14233 "VTableUses should be empty before it is discarded.");
14234 S.VTableUses.swap(RHS&: S.SavedVTableUses.back());
14235 S.SavedVTableUses.pop_back();
14236
14237 // Restore the set of pending implicit instantiations.
14238 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14239 AtEndOfTU) {
14240 assert(S.PendingInstantiations.empty() &&
14241 "PendingInstantiations should be empty before it is discarded.");
14242 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14243 S.SavedPendingInstantiations.pop_back();
14244 } else {
14245 // Template instantiations in the PCH may be delayed until the TU.
14246 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14247 S.PendingInstantiations.insert(
14248 position: S.PendingInstantiations.end(),
14249 first: S.SavedPendingInstantiations.back().begin(),
14250 last: S.SavedPendingInstantiations.back().end());
14251 S.SavedPendingInstantiations.pop_back();
14252 }
14253 }
14254
14255 GlobalEagerInstantiationScope(const GlobalEagerInstantiationScope &) =
14256 delete;
14257 GlobalEagerInstantiationScope &
14258 operator=(const GlobalEagerInstantiationScope &) = delete;
14259
14260 private:
14261 Sema &S;
14262 bool Enabled;
14263 bool AtEndOfTU;
14264 };
14265
14266 ExplicitSpecifier instantiateExplicitSpecifier(
14267 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14268
14269 struct LateInstantiatedAttribute {
14270 const Attr *TmplAttr;
14271 LocalInstantiationScope *Scope;
14272 Decl *NewDecl;
14273
14274 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
14275 Decl *D)
14276 : TmplAttr(A), Scope(S), NewDecl(D) {}
14277 };
14278 typedef SmallVector<LateInstantiatedAttribute, 1> LateInstantiatedAttrVec;
14279
14280 /// Recheck instantiated thread-safety attributes that could not be validated
14281 /// on the dependent pattern declaration.
14282 bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A);
14283
14284 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14285 const Decl *Pattern, Decl *Inst,
14286 LateInstantiatedAttrVec *LateAttrs = nullptr,
14287 LocalInstantiationScope *OuterMostScope = nullptr);
14288
14289 /// Update instantiation attributes after template was late parsed.
14290 ///
14291 /// Some attributes are evaluated based on the body of template. If it is
14292 /// late parsed, such attributes cannot be evaluated when declaration is
14293 /// instantiated. This function is used to update instantiation attributes
14294 /// when template definition is ready.
14295 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14296
14297 void
14298 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
14299 const Decl *Pattern, Decl *Inst,
14300 LateInstantiatedAttrVec *LateAttrs = nullptr,
14301 LocalInstantiationScope *OuterMostScope = nullptr);
14302
14303 bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor,
14304 bool IsCopy = false);
14305
14306 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
14307 ParmVarDecl *Param);
14308 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14309 FunctionDecl *Function);
14310
14311 /// Instantiate (or find existing instantiation of) a function template with a
14312 /// given set of template arguments.
14313 ///
14314 /// Usually this should not be used, and template argument deduction should be
14315 /// used in its place.
14316 FunctionDecl *InstantiateFunctionDeclaration(
14317 FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
14318 SourceLocation Loc,
14319 CodeSynthesisContext::SynthesisKind CSC =
14320 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution);
14321
14322 /// Instantiate the definition of the given function from its
14323 /// template.
14324 ///
14325 /// \param PointOfInstantiation the point at which the instantiation was
14326 /// required. Note that this is not precisely a "point of instantiation"
14327 /// for the function, but it's close.
14328 ///
14329 /// \param Function the already-instantiated declaration of a
14330 /// function template specialization or member function of a class template
14331 /// specialization.
14332 ///
14333 /// \param Recursive if true, recursively instantiates any functions that
14334 /// are required by this instantiation.
14335 ///
14336 /// \param DefinitionRequired if true, then we are performing an explicit
14337 /// instantiation where the body of the function is required. Complain if
14338 /// there is no such body.
14339 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14340 FunctionDecl *Function,
14341 bool Recursive = false,
14342 bool DefinitionRequired = false,
14343 bool AtEndOfTU = false);
14344 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
14345 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
14346 const TemplateArgumentList *PartialSpecArgs,
14347 SmallVectorImpl<TemplateArgument> &Converted,
14348 SourceLocation PointOfInstantiation,
14349 LateInstantiatedAttrVec *LateAttrs = nullptr,
14350 LocalInstantiationScope *StartingScope = nullptr);
14351
14352 /// Instantiates a variable template specialization by completing it
14353 /// with appropriate type information and initializer.
14354 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
14355 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14356 const MultiLevelTemplateArgumentList &TemplateArgs);
14357
14358 /// BuildVariableInstantiation - Used after a new variable has been created.
14359 /// Sets basic variable data and decides whether to postpone the
14360 /// variable instantiation.
14361 void
14362 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
14363 const MultiLevelTemplateArgumentList &TemplateArgs,
14364 LateInstantiatedAttrVec *LateAttrs,
14365 DeclContext *Owner,
14366 LocalInstantiationScope *StartingScope,
14367 bool InstantiatingVarTemplate = false,
14368 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14369
14370 /// Instantiate the initializer of a variable.
14371 void InstantiateVariableInitializer(
14372 VarDecl *Var, VarDecl *OldVar,
14373 const MultiLevelTemplateArgumentList &TemplateArgs);
14374
14375 /// Instantiate the definition of the given variable from its
14376 /// template.
14377 ///
14378 /// \param PointOfInstantiation the point at which the instantiation was
14379 /// required. Note that this is not precisely a "point of instantiation"
14380 /// for the variable, but it's close.
14381 ///
14382 /// \param Var the already-instantiated declaration of a templated variable.
14383 ///
14384 /// \param Recursive if true, recursively instantiates any functions that
14385 /// are required by this instantiation.
14386 ///
14387 /// \param DefinitionRequired if true, then we are performing an explicit
14388 /// instantiation where a definition of the variable is required. Complain
14389 /// if there is no such definition.
14390 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14391 VarDecl *Var, bool Recursive = false,
14392 bool DefinitionRequired = false,
14393 bool AtEndOfTU = false);
14394
14395 void InstantiateMemInitializers(
14396 CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl,
14397 const MultiLevelTemplateArgumentList &TemplateArgs);
14398
14399 /// Find the instantiation of the given declaration within the
14400 /// current instantiation.
14401 ///
14402 /// This routine is intended to be used when \p D is a declaration
14403 /// referenced from within a template, that needs to mapped into the
14404 /// corresponding declaration within an instantiation. For example,
14405 /// given:
14406 ///
14407 /// \code
14408 /// template<typename T>
14409 /// struct X {
14410 /// enum Kind {
14411 /// KnownValue = sizeof(T)
14412 /// };
14413 ///
14414 /// bool getKind() const { return KnownValue; }
14415 /// };
14416 ///
14417 /// template struct X<int>;
14418 /// \endcode
14419 ///
14420 /// In the instantiation of X<int>::getKind(), we need to map the \p
14421 /// EnumConstantDecl for \p KnownValue (which refers to
14422 /// X<T>::<Kind>::KnownValue) to its instantiation
14423 /// (X<int>::<Kind>::KnownValue).
14424 /// \p FindInstantiatedDecl performs this mapping from within the
14425 /// instantiation of X<int>.
14426 NamedDecl *
14427 FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
14428 const MultiLevelTemplateArgumentList &TemplateArgs,
14429 bool FindingInstantiatedContext = false);
14430
14431 /// Finds the instantiation of the given declaration context
14432 /// within the current instantiation.
14433 ///
14434 /// \returns NULL if there was an error
14435 DeclContext *
14436 FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
14437 const MultiLevelTemplateArgumentList &TemplateArgs);
14438
14439 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14440 const MultiLevelTemplateArgumentList &TemplateArgs);
14441
14442 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14443 /// an implicit 'operator=='.
14444 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
14445 FunctionDecl *Spaceship);
14446
14447 /// Performs template instantiation for all implicit template
14448 /// instantiations we have seen until this point.
14449 void PerformPendingInstantiations(bool LocalOnly = false,
14450 bool AtEndOfTU = true);
14451
14452 TemplateParameterList *
14453 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
14454 const MultiLevelTemplateArgumentList &TemplateArgs,
14455 bool EvaluateConstraints = true);
14456
14457 void PerformDependentDiagnostics(
14458 const DeclContext *Pattern,
14459 const MultiLevelTemplateArgumentList &TemplateArgs);
14460
14461private:
14462 /// Introduce the instantiated local variables into the local
14463 /// instantiation scope.
14464 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14465 const FunctionDecl *PatternDecl,
14466 LocalInstantiationScope &Scope);
14467 /// Introduce the instantiated function parameters into the local
14468 /// instantiation scope, and set the parameter names to those used
14469 /// in the template.
14470 bool addInstantiatedParametersToScope(
14471 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14472 LocalInstantiationScope &Scope,
14473 const MultiLevelTemplateArgumentList &TemplateArgs);
14474
14475 /// Introduce the instantiated captures of the lambda into the local
14476 /// instantiation scope.
14477 bool addInstantiatedCapturesToScope(
14478 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14479 LocalInstantiationScope &Scope,
14480 const MultiLevelTemplateArgumentList &TemplateArgs);
14481
14482 int ParsingClassDepth = 0;
14483
14484 class SavePendingParsedClassStateRAII {
14485 public:
14486 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14487
14488 ~SavePendingParsedClassStateRAII() {
14489 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14490 "there shouldn't be any pending delayed exception spec checks");
14491 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14492 "there shouldn't be any pending delayed exception spec checks");
14493 swapSavedState();
14494 }
14495
14496 SavePendingParsedClassStateRAII(const SavePendingParsedClassStateRAII &) =
14497 delete;
14498 SavePendingParsedClassStateRAII &
14499 operator=(const SavePendingParsedClassStateRAII &) = delete;
14500
14501 private:
14502 Sema &S;
14503 decltype(DelayedOverridingExceptionSpecChecks)
14504 SavedOverridingExceptionSpecChecks;
14505 decltype(DelayedEquivalentExceptionSpecChecks)
14506 SavedEquivalentExceptionSpecChecks;
14507
14508 void swapSavedState() {
14509 SavedOverridingExceptionSpecChecks.swap(
14510 RHS&: S.DelayedOverridingExceptionSpecChecks);
14511 SavedEquivalentExceptionSpecChecks.swap(
14512 RHS&: S.DelayedEquivalentExceptionSpecChecks);
14513 }
14514 };
14515
14516 ///@}
14517
14518 //
14519 //
14520 // -------------------------------------------------------------------------
14521 //
14522 //
14523
14524 /// \name C++ Variadic Templates
14525 /// Implementations are in SemaTemplateVariadic.cpp
14526 ///@{
14527
14528public:
14529 /// Determine whether an unexpanded parameter pack might be permitted in this
14530 /// location. Useful for error recovery.
14531 bool isUnexpandedParameterPackPermitted();
14532
14533 /// The context in which an unexpanded parameter pack is
14534 /// being diagnosed.
14535 ///
14536 /// Note that the values of this enumeration line up with the first
14537 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14538 enum UnexpandedParameterPackContext {
14539 /// An arbitrary expression.
14540 UPPC_Expression = 0,
14541
14542 /// The base type of a class type.
14543 UPPC_BaseType,
14544
14545 /// The type of an arbitrary declaration.
14546 UPPC_DeclarationType,
14547
14548 /// The type of a data member.
14549 UPPC_DataMemberType,
14550
14551 /// The size of a bit-field.
14552 UPPC_BitFieldWidth,
14553
14554 /// The expression in a static assertion.
14555 UPPC_StaticAssertExpression,
14556
14557 /// The fixed underlying type of an enumeration.
14558 UPPC_FixedUnderlyingType,
14559
14560 /// The enumerator value.
14561 UPPC_EnumeratorValue,
14562
14563 /// A using declaration.
14564 UPPC_UsingDeclaration,
14565
14566 /// A friend declaration.
14567 UPPC_FriendDeclaration,
14568
14569 /// A declaration qualifier.
14570 UPPC_DeclarationQualifier,
14571
14572 /// An initializer.
14573 UPPC_Initializer,
14574
14575 /// A default argument.
14576 UPPC_DefaultArgument,
14577
14578 /// The type of a non-type template parameter.
14579 UPPC_NonTypeTemplateParameterType,
14580
14581 /// The type of an exception.
14582 UPPC_ExceptionType,
14583
14584 /// Explicit specialization.
14585 UPPC_ExplicitSpecialization,
14586
14587 /// Partial specialization.
14588 UPPC_PartialSpecialization,
14589
14590 /// Microsoft __if_exists.
14591 UPPC_IfExists,
14592
14593 /// Microsoft __if_not_exists.
14594 UPPC_IfNotExists,
14595
14596 /// Lambda expression.
14597 UPPC_Lambda,
14598
14599 /// Block expression.
14600 UPPC_Block,
14601
14602 /// A type constraint.
14603 UPPC_TypeConstraint,
14604
14605 // A requirement in a requires-expression.
14606 UPPC_Requirement,
14607
14608 // A requires-clause.
14609 UPPC_RequiresClause,
14610 };
14611
14612 /// Diagnose unexpanded parameter packs.
14613 ///
14614 /// \param Loc The location at which we should emit the diagnostic.
14615 ///
14616 /// \param UPPC The context in which we are diagnosing unexpanded
14617 /// parameter packs.
14618 ///
14619 /// \param Unexpanded the set of unexpanded parameter packs.
14620 ///
14621 /// \returns true if an error occurred, false otherwise.
14622 bool DiagnoseUnexpandedParameterPacks(
14623 SourceLocation Loc, UnexpandedParameterPackContext UPPC,
14624 ArrayRef<UnexpandedParameterPack> Unexpanded);
14625
14626 /// If the given type contains an unexpanded parameter pack,
14627 /// diagnose the error.
14628 ///
14629 /// \param Loc The source location where a diagnostc should be emitted.
14630 ///
14631 /// \param T The type that is being checked for unexpanded parameter
14632 /// packs.
14633 ///
14634 /// \returns true if an error occurred, false otherwise.
14635 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
14636 UnexpandedParameterPackContext UPPC);
14637
14638 /// If the given expression contains an unexpanded parameter
14639 /// pack, diagnose the error.
14640 ///
14641 /// \param E The expression that is being checked for unexpanded
14642 /// parameter packs.
14643 ///
14644 /// \returns true if an error occurred, false otherwise.
14645 bool DiagnoseUnexpandedParameterPack(
14646 Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression);
14647
14648 /// If the given requirees-expression contains an unexpanded reference to one
14649 /// of its own parameter packs, diagnose the error.
14650 ///
14651 /// \param RE The requiress-expression that is being checked for unexpanded
14652 /// parameter packs.
14653 ///
14654 /// \returns true if an error occurred, false otherwise.
14655 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
14656
14657 /// If the given nested-name-specifier contains an unexpanded
14658 /// parameter pack, diagnose the error.
14659 ///
14660 /// \param SS The nested-name-specifier that is being checked for
14661 /// unexpanded parameter packs.
14662 ///
14663 /// \returns true if an error occurred, false otherwise.
14664 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
14665 UnexpandedParameterPackContext UPPC);
14666
14667 /// If the given name contains an unexpanded parameter pack,
14668 /// diagnose the error.
14669 ///
14670 /// \param NameInfo The name (with source location information) that
14671 /// is being checked for unexpanded parameter packs.
14672 ///
14673 /// \returns true if an error occurred, false otherwise.
14674 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
14675 UnexpandedParameterPackContext UPPC);
14676
14677 /// If the given template name contains an unexpanded parameter pack,
14678 /// diagnose the error.
14679 ///
14680 /// \param Loc The location of the template name.
14681 ///
14682 /// \param Template The template name that is being checked for unexpanded
14683 /// parameter packs.
14684 ///
14685 /// \returns true if an error occurred, false otherwise.
14686 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
14687 TemplateName Template,
14688 UnexpandedParameterPackContext UPPC);
14689
14690 /// If the given template argument contains an unexpanded parameter
14691 /// pack, diagnose the error.
14692 ///
14693 /// \param Arg The template argument that is being checked for unexpanded
14694 /// parameter packs.
14695 ///
14696 /// \returns true if an error occurred, false otherwise.
14697 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
14698 UnexpandedParameterPackContext UPPC);
14699
14700 /// Collect the set of unexpanded parameter packs within the given
14701 /// template argument.
14702 ///
14703 /// \param Arg The template argument that will be traversed to find
14704 /// unexpanded parameter packs.
14705 void collectUnexpandedParameterPacks(
14706 TemplateArgument Arg,
14707 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14708
14709 /// Collect the set of unexpanded parameter packs within the given
14710 /// template argument.
14711 ///
14712 /// \param Arg The template argument that will be traversed to find
14713 /// unexpanded parameter packs.
14714 void collectUnexpandedParameterPacks(
14715 TemplateArgumentLoc Arg,
14716 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14717
14718 /// Collect the set of unexpanded parameter packs within the given
14719 /// type.
14720 ///
14721 /// \param T The type that will be traversed to find
14722 /// unexpanded parameter packs.
14723 void collectUnexpandedParameterPacks(
14724 QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14725
14726 /// Collect the set of unexpanded parameter packs within the given
14727 /// type.
14728 ///
14729 /// \param TL The type that will be traversed to find
14730 /// unexpanded parameter packs.
14731 void collectUnexpandedParameterPacks(
14732 TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14733
14734 /// Collect the set of unexpanded parameter packs within the given
14735 /// nested-name-specifier.
14736 ///
14737 /// \param NNS The nested-name-specifier that will be traversed to find
14738 /// unexpanded parameter packs.
14739 void collectUnexpandedParameterPacks(
14740 NestedNameSpecifierLoc NNS,
14741 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14742
14743 /// Collect the set of unexpanded parameter packs within the given
14744 /// name.
14745 ///
14746 /// \param NameInfo The name that will be traversed to find
14747 /// unexpanded parameter packs.
14748 void collectUnexpandedParameterPacks(
14749 const DeclarationNameInfo &NameInfo,
14750 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14751
14752 /// Collect the set of unexpanded parameter packs within the given
14753 /// expression.
14754 static void collectUnexpandedParameterPacks(
14755 Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14756
14757 /// Invoked when parsing a template argument.
14758 ///
14759 /// \param Arg the template argument, which may already be invalid.
14760 ///
14761 /// If it is followed by ellipsis, this function is called before
14762 /// `ActOnPackExpansion`.
14763 ParsedTemplateArgument
14764 ActOnTemplateTemplateArgument(const ParsedTemplateArgument &Arg);
14765
14766 /// Invoked when parsing a template argument followed by an
14767 /// ellipsis, which creates a pack expansion.
14768 ///
14769 /// \param Arg The template argument preceding the ellipsis, which
14770 /// may already be invalid.
14771 ///
14772 /// \param EllipsisLoc The location of the ellipsis.
14773 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
14774 SourceLocation EllipsisLoc);
14775
14776 /// Invoked when parsing a type followed by an ellipsis, which
14777 /// creates a pack expansion.
14778 ///
14779 /// \param Type The type preceding the ellipsis, which will become
14780 /// the pattern of the pack expansion.
14781 ///
14782 /// \param EllipsisLoc The location of the ellipsis.
14783 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
14784
14785 /// Construct a pack expansion type from the pattern of the pack
14786 /// expansion.
14787 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
14788 SourceLocation EllipsisLoc,
14789 UnsignedOrNone NumExpansions);
14790
14791 /// Construct a pack expansion type from the pattern of the pack
14792 /// expansion.
14793 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14794 SourceLocation EllipsisLoc,
14795 UnsignedOrNone NumExpansions);
14796
14797 /// Invoked when parsing an expression followed by an ellipsis, which
14798 /// creates a pack expansion.
14799 ///
14800 /// \param Pattern The expression preceding the ellipsis, which will become
14801 /// the pattern of the pack expansion.
14802 ///
14803 /// \param EllipsisLoc The location of the ellipsis.
14804 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14805
14806 /// Invoked when parsing an expression followed by an ellipsis, which
14807 /// creates a pack expansion.
14808 ///
14809 /// \param Pattern The expression preceding the ellipsis, which will become
14810 /// the pattern of the pack expansion.
14811 ///
14812 /// \param EllipsisLoc The location of the ellipsis.
14813 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14814 UnsignedOrNone NumExpansions);
14815
14816 /// Determine whether we could expand a pack expansion with the
14817 /// given set of parameter packs into separate arguments by repeatedly
14818 /// transforming the pattern.
14819 ///
14820 /// \param EllipsisLoc The location of the ellipsis that identifies the
14821 /// pack expansion.
14822 ///
14823 /// \param PatternRange The source range that covers the entire pattern of
14824 /// the pack expansion.
14825 ///
14826 /// \param Unexpanded The set of unexpanded parameter packs within the
14827 /// pattern.
14828 ///
14829 /// \param ShouldExpand Will be set to \c true if the transformer should
14830 /// expand the corresponding pack expansions into separate arguments. When
14831 /// set, \c NumExpansions must also be set.
14832 ///
14833 /// \param RetainExpansion Whether the caller should add an unexpanded
14834 /// pack expansion after all of the expanded arguments. This is used
14835 /// when extending explicitly-specified template argument packs per
14836 /// C++0x [temp.arg.explicit]p9.
14837 ///
14838 /// \param NumExpansions The number of separate arguments that will be in
14839 /// the expanded form of the corresponding pack expansion. This is both an
14840 /// input and an output parameter, which can be set by the caller if the
14841 /// number of expansions is known a priori (e.g., due to a prior substitution)
14842 /// and will be set by the callee when the number of expansions is known.
14843 /// The callee must set this value when \c ShouldExpand is \c true; it may
14844 /// set this value in other cases.
14845 ///
14846 /// \returns true if an error occurred (e.g., because the parameter packs
14847 /// are to be instantiated with arguments of different lengths), false
14848 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
14849 /// must be set.
14850 bool CheckParameterPacksForExpansion(
14851 SourceLocation EllipsisLoc, SourceRange PatternRange,
14852 ArrayRef<UnexpandedParameterPack> Unexpanded,
14853 const MultiLevelTemplateArgumentList &TemplateArgs,
14854 bool FailOnPackProducingTemplates, bool &ShouldExpand,
14855 bool &RetainExpansion, UnsignedOrNone &NumExpansions,
14856 bool Diagnose = true);
14857
14858 /// Determine the number of arguments in the given pack expansion
14859 /// type.
14860 ///
14861 /// This routine assumes that the number of arguments in the expansion is
14862 /// consistent across all of the unexpanded parameter packs in its pattern.
14863 ///
14864 /// Returns an empty Optional if the type can't be expanded.
14865 UnsignedOrNone getNumArgumentsInExpansion(
14866 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
14867
14868 UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(
14869 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
14870 const MultiLevelTemplateArgumentList &TemplateArgs);
14871
14872 /// Determine whether the given declarator contains any unexpanded
14873 /// parameter packs.
14874 ///
14875 /// This routine is used by the parser to disambiguate function declarators
14876 /// with an ellipsis prior to the ')', e.g.,
14877 ///
14878 /// \code
14879 /// void f(T...);
14880 /// \endcode
14881 ///
14882 /// To determine whether we have an (unnamed) function parameter pack or
14883 /// a variadic function.
14884 ///
14885 /// \returns true if the declarator contains any unexpanded parameter packs,
14886 /// false otherwise.
14887 bool containsUnexpandedParameterPacks(Declarator &D);
14888
14889 /// Returns the pattern of the pack expansion for a template argument.
14890 ///
14891 /// \param OrigLoc The template argument to expand.
14892 ///
14893 /// \param Ellipsis Will be set to the location of the ellipsis.
14894 ///
14895 /// \param NumExpansions Will be set to the number of expansions that will
14896 /// be generated from this pack expansion, if known a priori.
14897 TemplateArgumentLoc
14898 getTemplateArgumentPackExpansionPattern(TemplateArgumentLoc OrigLoc,
14899 SourceLocation &Ellipsis,
14900 UnsignedOrNone &NumExpansions) const;
14901
14902 /// Given a template argument that contains an unexpanded parameter pack, but
14903 /// which has already been substituted, attempt to determine the number of
14904 /// elements that will be produced once this argument is fully-expanded.
14905 ///
14906 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
14907 /// avoid actually expanding the pack where possible.
14908 UnsignedOrNone getFullyPackExpandedSize(TemplateArgument Arg);
14909
14910 /// Called when an expression computing the size of a parameter pack
14911 /// is parsed.
14912 ///
14913 /// \code
14914 /// template<typename ...Types> struct count {
14915 /// static const unsigned value = sizeof...(Types);
14916 /// };
14917 /// \endcode
14918 ///
14919 //
14920 /// \param OpLoc The location of the "sizeof" keyword.
14921 /// \param Name The name of the parameter pack whose size will be determined.
14922 /// \param NameLoc The source location of the name of the parameter pack.
14923 /// \param RParenLoc The location of the closing parentheses.
14924 ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc,
14925 IdentifierInfo &Name,
14926 SourceLocation NameLoc,
14927 SourceLocation RParenLoc);
14928
14929 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
14930 SourceLocation EllipsisLoc,
14931 SourceLocation LSquareLoc, Expr *IndexExpr,
14932 SourceLocation RSquareLoc);
14933
14934 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
14935 SourceLocation EllipsisLoc, Expr *IndexExpr,
14936 SourceLocation RSquareLoc,
14937 ArrayRef<Expr *> ExpandedExprs = {},
14938 bool FullySubstituted = false);
14939
14940 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
14941 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
14942 tok::TokenKind Operator,
14943 SourceLocation EllipsisLoc, Expr *RHS,
14944 SourceLocation RParenLoc);
14945 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
14946 SourceLocation LParenLoc, Expr *LHS,
14947 BinaryOperatorKind Operator,
14948 SourceLocation EllipsisLoc, Expr *RHS,
14949 SourceLocation RParenLoc,
14950 UnsignedOrNone NumExpansions);
14951 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
14952 BinaryOperatorKind Operator);
14953
14954 ///@}
14955
14956 //
14957 //
14958 // -------------------------------------------------------------------------
14959 //
14960 //
14961
14962 /// \name Constraints and Concepts
14963 /// Implementations are in SemaConcept.cpp
14964 ///@{
14965
14966public:
14967 ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI);
14968
14969 ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc,
14970 TypeSourceInfo *TSI);
14971
14972public:
14973 void PushSatisfactionStackEntry(const NamedDecl *D,
14974 const llvm::FoldingSetNodeID &ID) {
14975 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
14976 SatisfactionStack.emplace_back(Args&: Can, Args: ID);
14977 }
14978
14979 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
14980
14981 bool SatisfactionStackContains(const NamedDecl *D,
14982 const llvm::FoldingSetNodeID &ID) const {
14983 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
14984 return llvm::is_contained(Range: SatisfactionStack,
14985 Element: SatisfactionStackEntryTy{Can, ID});
14986 }
14987
14988 using SatisfactionStackEntryTy =
14989 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
14990
14991 // Resets the current SatisfactionStack for cases where we are instantiating
14992 // constraints as a 'side effect' of normal instantiation in a way that is not
14993 // indicative of recursive definition.
14994 class SatisfactionStackResetRAII {
14995 llvm::SmallVector<SatisfactionStackEntryTy, 10> BackupSatisfactionStack;
14996 Sema &SemaRef;
14997
14998 public:
14999 SatisfactionStackResetRAII(Sema &S) : SemaRef(S) {
15000 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
15001 }
15002
15003 ~SatisfactionStackResetRAII() {
15004 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
15005 }
15006
15007 SatisfactionStackResetRAII(const SatisfactionStackResetRAII &) = delete;
15008 SatisfactionStackResetRAII &
15009 operator=(const SatisfactionStackResetRAII &) = delete;
15010 };
15011
15012 void SwapSatisfactionStack(
15013 llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) {
15014 SatisfactionStack.swap(RHS&: NewSS);
15015 }
15016
15017 using ConstrainedDeclOrNestedRequirement =
15018 llvm::PointerUnion<const NamedDecl *,
15019 const concepts::NestedRequirement *>;
15020
15021 /// Check whether the given expression is a valid constraint expression.
15022 /// A diagnostic is emitted if it is not, false is returned, and
15023 /// PossibleNonPrimary will be set to true if the failure might be due to a
15024 /// non-primary expression being used as an atomic constraint.
15025 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
15026 bool *PossibleNonPrimary = nullptr,
15027 bool IsTrailingRequiresClause = false);
15028
15029 /// \brief Check whether the given list of constraint expressions are
15030 /// satisfied (as if in a 'conjunction') given template arguments.
15031 /// \param Template the template-like entity that triggered the constraints
15032 /// check (either a concept or a constrained entity).
15033 /// \param ConstraintExprs a list of constraint expressions, treated as if
15034 /// they were 'AND'ed together.
15035 /// \param TemplateArgLists the list of template arguments to substitute into
15036 /// the constraint expression.
15037 /// \param TemplateIDRange The source range of the template id that
15038 /// caused the constraints check.
15039 /// \param Satisfaction if true is returned, will contain details of the
15040 /// satisfaction, with enough information to diagnose an unsatisfied
15041 /// expression.
15042 /// \returns true if an error occurred and satisfaction could not be checked,
15043 /// false otherwise.
15044 bool CheckConstraintSatisfaction(
15045 ConstrainedDeclOrNestedRequirement Entity,
15046 ArrayRef<AssociatedConstraint> AssociatedConstraints,
15047 const MultiLevelTemplateArgumentList &TemplateArgLists,
15048 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
15049 const ConceptReference *TopLevelConceptId = nullptr,
15050 Expr **ConvertedExpr = nullptr);
15051
15052 /// Check whether the given function decl's trailing requires clause is
15053 /// satisfied, if any. Returns false and updates Satisfaction with the
15054 /// satisfaction verdict if successful, emits a diagnostic and returns true if
15055 /// an error occurred and satisfaction could not be determined.
15056 ///
15057 /// \returns true if an error occurred, false otherwise.
15058 bool CheckFunctionConstraints(const FunctionDecl *FD,
15059 ConstraintSatisfaction &Satisfaction,
15060 SourceLocation UsageLoc = SourceLocation(),
15061 bool ForOverloadResolution = false);
15062
15063 // Calculates whether two constraint expressions are equal irrespective of a
15064 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
15065 // 'New', which are the "source" of the constraint, since this is necessary
15066 // for figuring out the relative 'depth' of the constraint. The depth of the
15067 // 'primary template' and the 'instantiated from' templates aren't necessarily
15068 // the same, such as a case when one is a 'friend' defined in a class.
15069 bool AreConstraintExpressionsEqual(const NamedDecl *Old,
15070 const Expr *OldConstr,
15071 const TemplateCompareNewDeclInfo &New,
15072 const Expr *NewConstr);
15073
15074 // Calculates whether the friend function depends on an enclosing template for
15075 // the purposes of [temp.friend] p9.
15076 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
15077
15078 /// \brief Ensure that the given template arguments satisfy the constraints
15079 /// associated with the given template, emitting a diagnostic if they do not.
15080 ///
15081 /// \param Template The template to which the template arguments are being
15082 /// provided.
15083 ///
15084 /// \param TemplateArgs The converted, canonicalized template arguments.
15085 ///
15086 /// \param TemplateIDRange The source range of the template id that
15087 /// caused the constraints check.
15088 ///
15089 /// \returns true if the constrains are not satisfied or could not be checked
15090 /// for satisfaction, false if the constraints are satisfied.
15091 bool EnsureTemplateArgumentListConstraints(
15092 TemplateDecl *Template,
15093 const MultiLevelTemplateArgumentList &TemplateArgs,
15094 SourceRange TemplateIDRange);
15095
15096 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
15097 FunctionDecl *Decl,
15098 ArrayRef<TemplateArgument> TemplateArgs,
15099 ConstraintSatisfaction &Satisfaction);
15100
15101 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15102 /// unsatisfied.
15103 /// \param First whether this is the first time an unsatisfied constraint is
15104 /// diagnosed for this error.
15105 void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
15106 SourceLocation Loc = {},
15107 bool First = true);
15108
15109 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15110 /// unsatisfied.
15111 void
15112 DiagnoseUnsatisfiedConstraint(const ConceptSpecializationExpr *ConstraintExpr,
15113 bool First = true);
15114
15115 const NormalizedConstraint *getNormalizedAssociatedConstraints(
15116 ConstrainedDeclOrNestedRequirement Entity,
15117 ArrayRef<AssociatedConstraint> AssociatedConstraints);
15118
15119 /// \brief Check whether the given declaration's associated constraints are
15120 /// at least as constrained than another declaration's according to the
15121 /// partial ordering of constraints.
15122 ///
15123 /// \param Result If no error occurred, receives the result of true if D1 is
15124 /// at least constrained than D2, and false otherwise.
15125 ///
15126 /// \returns true if an error occurred, false otherwise.
15127 bool IsAtLeastAsConstrained(const NamedDecl *D1,
15128 MutableArrayRef<AssociatedConstraint> AC1,
15129 const NamedDecl *D2,
15130 MutableArrayRef<AssociatedConstraint> AC2,
15131 bool &Result);
15132
15133 /// If D1 was not at least as constrained as D2, but would've been if a pair
15134 /// of atomic constraints involved had been declared in a concept and not
15135 /// repeated in two separate places in code.
15136 /// \returns true if such a diagnostic was emitted, false otherwise.
15137 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
15138 const NamedDecl *D1, ArrayRef<AssociatedConstraint> AC1,
15139 const NamedDecl *D2, ArrayRef<AssociatedConstraint> AC2);
15140
15141 /// Cache the satisfaction of an atomic constraint.
15142 /// The key is based on the unsubstituted expression and the parameter
15143 /// mapping. This lets us not substituting the mapping more than once,
15144 /// which is (very!) expensive.
15145 /// FIXME: this should be private.
15146 llvm::DenseMap<llvm::FoldingSetNodeID,
15147 UnsubstitutedConstraintSatisfactionCacheResult>
15148 UnsubstitutedConstraintSatisfactionCache;
15149
15150 /// Cache the instantiation results of template parameter mappings within
15151 /// concepts. Substituting into normalized concepts can be extremely expensive
15152 /// due to the redundancy of template parameters. This cache is intended for
15153 /// use by TemplateInstantiator to avoid redundant semantic checking.
15154 llvm::DenseMap<llvm::FoldingSetNodeID, TemplateArgumentLoc>
15155 *CurrentCachedTemplateArgs = nullptr;
15156
15157private:
15158 /// Caches pairs of template-like decls whose associated constraints were
15159 /// checked for subsumption and whether or not the first's constraints did in
15160 /// fact subsume the second's.
15161 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
15162 SubsumptionCache;
15163 /// Caches the normalized associated constraints of declarations (concepts or
15164 /// constrained declarations). If an error occurred while normalizing the
15165 /// associated constraints of the template or concept, nullptr will be cached
15166 /// here.
15167 llvm::DenseMap<ConstrainedDeclOrNestedRequirement, NormalizedConstraint *>
15168 NormalizationCache;
15169
15170 /// Cache whether the associated constraint of a declaration
15171 /// is satisfied.
15172 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
15173 SatisfactionCache;
15174
15175 // The current stack of constraint satisfactions, so we can exit-early.
15176 llvm::SmallVector<SatisfactionStackEntryTy, 10> SatisfactionStack;
15177
15178 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
15179 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
15180 /// use LambdaScopeForCallOperatorInstantiationRAII.
15181 bool
15182 SetupConstraintScope(FunctionDecl *FD,
15183 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15184 const MultiLevelTemplateArgumentList &MLTAL,
15185 LocalInstantiationScope &Scope);
15186
15187 /// Used during constraint checking, sets up the constraint template argument
15188 /// lists, and calls SetupConstraintScope to set up the
15189 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
15190 std::optional<MultiLevelTemplateArgumentList>
15191 SetupConstraintCheckingTemplateArgumentsAndScope(
15192 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15193 LocalInstantiationScope &Scope);
15194
15195 ///@}
15196
15197 //
15198 //
15199 // -------------------------------------------------------------------------
15200 //
15201 //
15202
15203 /// \name Types
15204 /// Implementations are in SemaType.cpp
15205 ///@{
15206
15207public:
15208 /// A mapping that describes the nullability we've seen in each header file.
15209 FileNullabilityMap NullabilityMap;
15210
15211 static int getPrintable(int I) { return I; }
15212 static unsigned getPrintable(unsigned I) { return I; }
15213 static bool getPrintable(bool B) { return B; }
15214 static const char *getPrintable(const char *S) { return S; }
15215 static StringRef getPrintable(StringRef S) { return S; }
15216 static const std::string &getPrintable(const std::string &S) { return S; }
15217 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
15218 return II;
15219 }
15220 static DeclarationName getPrintable(DeclarationName N) { return N; }
15221 static QualType getPrintable(QualType T) { return T; }
15222 static SourceRange getPrintable(SourceRange R) { return R; }
15223 static SourceRange getPrintable(SourceLocation L) { return L; }
15224 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15225 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange(); }
15226
15227 enum class CompleteTypeKind {
15228 /// Apply the normal rules for complete types. In particular,
15229 /// treat all sizeless types as incomplete.
15230 Normal,
15231
15232 /// Relax the normal rules for complete types so that they include
15233 /// sizeless built-in types.
15234 AcceptSizeless,
15235
15236 // FIXME: Eventually we should flip the default to Normal and opt in
15237 // to AcceptSizeless rather than opt out of it.
15238 Default = AcceptSizeless
15239 };
15240
15241 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
15242 const DeclSpec *DS = nullptr);
15243 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
15244 const DeclSpec *DS = nullptr);
15245
15246 /// Build a pointer type.
15247 ///
15248 /// \param T The type to which we'll be building a pointer.
15249 ///
15250 /// \param Loc The location of the entity whose type involves this
15251 /// pointer type or, if there is no such entity, the location of the
15252 /// type that will have pointer type.
15253 ///
15254 /// \param Entity The name of the entity that involves the pointer
15255 /// type, if known.
15256 ///
15257 /// \returns A suitable pointer type, if there are no
15258 /// errors. Otherwise, returns a NULL type.
15259 QualType BuildPointerType(QualType T, SourceLocation Loc,
15260 DeclarationName Entity);
15261
15262 /// Build a reference type.
15263 ///
15264 /// \param T The type to which we'll be building a reference.
15265 ///
15266 /// \param Loc The location of the entity whose type involves this
15267 /// reference type or, if there is no such entity, the location of the
15268 /// type that will have reference type.
15269 ///
15270 /// \param Entity The name of the entity that involves the reference
15271 /// type, if known.
15272 ///
15273 /// \returns A suitable reference type, if there are no
15274 /// errors. Otherwise, returns a NULL type.
15275 QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc,
15276 DeclarationName Entity);
15277
15278 /// Build an array type.
15279 ///
15280 /// \param T The type of each element in the array.
15281 ///
15282 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15283 ///
15284 /// \param ArraySize Expression describing the size of the array.
15285 ///
15286 /// \param Brackets The range from the opening '[' to the closing ']'.
15287 ///
15288 /// \param Entity The name of the entity that involves the array
15289 /// type, if known.
15290 ///
15291 /// \returns A suitable array type, if there are no errors. Otherwise,
15292 /// returns a NULL type.
15293 QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize,
15294 unsigned Quals, SourceRange Brackets,
15295 DeclarationName Entity);
15296 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
15297
15298 /// Build an ext-vector type.
15299 ///
15300 /// Run the required checks for the extended vector type.
15301 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
15302 SourceLocation AttrLoc);
15303 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15304 SourceLocation AttrLoc);
15305
15306 QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy,
15307 Expr *CountExpr,
15308 bool CountInBytes,
15309 bool OrNull);
15310
15311 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15312 /// expression is uninstantiated. If instantiated it will apply the
15313 /// appropriate address space to the type. This function allows dependent
15314 /// template variables to be used in conjunction with the address_space
15315 /// attribute
15316 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15317 SourceLocation AttrLoc);
15318
15319 /// Same as above, but constructs the AddressSpace index if not provided.
15320 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
15321 SourceLocation AttrLoc);
15322
15323 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
15324
15325 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
15326
15327 /// Build a function type.
15328 ///
15329 /// This routine checks the function type according to C++ rules and
15330 /// under the assumption that the result type and parameter types have
15331 /// just been instantiated from a template. It therefore duplicates
15332 /// some of the behavior of GetTypeForDeclarator, but in a much
15333 /// simpler form that is only suitable for this narrow use case.
15334 ///
15335 /// \param T The return type of the function.
15336 ///
15337 /// \param ParamTypes The parameter types of the function. This array
15338 /// will be modified to account for adjustments to the types of the
15339 /// function parameters.
15340 ///
15341 /// \param Loc The location of the entity whose type involves this
15342 /// function type or, if there is no such entity, the location of the
15343 /// type that will have function type.
15344 ///
15345 /// \param Entity The name of the entity that involves the function
15346 /// type, if known.
15347 ///
15348 /// \param EPI Extra information about the function type. Usually this will
15349 /// be taken from an existing function with the same prototype.
15350 ///
15351 /// \returns A suitable function type, if there are no errors. The
15352 /// unqualified type will always be a FunctionProtoType.
15353 /// Otherwise, returns a NULL type.
15354 QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes,
15355 SourceLocation Loc, DeclarationName Entity,
15356 const FunctionProtoType::ExtProtoInfo &EPI);
15357
15358 /// Build a member pointer type \c T Class::*.
15359 ///
15360 /// \param T the type to which the member pointer refers.
15361 /// \param Class the class type into which the member pointer points.
15362 /// \param Loc the location where this type begins
15363 /// \param Entity the name of the entity that will have this member pointer
15364 /// type
15365 ///
15366 /// \returns a member pointer type, if successful, or a NULL type if there was
15367 /// an error.
15368 QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS,
15369 CXXRecordDecl *Cls, SourceLocation Loc,
15370 DeclarationName Entity);
15371
15372 /// Build a block pointer type.
15373 ///
15374 /// \param T The type to which we'll be building a block pointer.
15375 ///
15376 /// \param Loc The source location, used for diagnostics.
15377 ///
15378 /// \param Entity The name of the entity that involves the block pointer
15379 /// type, if known.
15380 ///
15381 /// \returns A suitable block pointer type, if there are no
15382 /// errors. Otherwise, returns a NULL type.
15383 QualType BuildBlockPointerType(QualType T, SourceLocation Loc,
15384 DeclarationName Entity);
15385
15386 /// Build a paren type including \p T.
15387 QualType BuildParenType(QualType T);
15388 QualType BuildAtomicType(QualType T, SourceLocation Loc);
15389
15390 /// Build a Read-only Pipe type.
15391 ///
15392 /// \param T The type to which we'll be building a Pipe.
15393 ///
15394 /// \param Loc We do not use it for now.
15395 ///
15396 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15397 /// a NULL type.
15398 QualType BuildReadPipeType(QualType T, SourceLocation Loc);
15399
15400 /// Build a Write-only Pipe type.
15401 ///
15402 /// \param T The type to which we'll be building a Pipe.
15403 ///
15404 /// \param Loc We do not use it for now.
15405 ///
15406 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15407 /// a NULL type.
15408 QualType BuildWritePipeType(QualType T, SourceLocation Loc);
15409
15410 /// Build a bit-precise integer type.
15411 ///
15412 /// \param IsUnsigned Boolean representing the signedness of the type.
15413 ///
15414 /// \param BitWidth Size of this int type in bits, or an expression
15415 /// representing that.
15416 ///
15417 /// \param Loc Location of the keyword.
15418 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15419
15420 /// GetTypeForDeclarator - Convert the type for the specified
15421 /// declarator to Type instances.
15422 ///
15423 /// The result of this call will never be null, but the associated
15424 /// type may be a null type if there's an unrecoverable error.
15425 TypeSourceInfo *GetTypeForDeclarator(Declarator &D);
15426 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
15427
15428 /// Package the given type and TSI into a ParsedType.
15429 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
15430 static QualType GetTypeFromParser(ParsedType Ty,
15431 TypeSourceInfo **TInfo = nullptr);
15432
15433 TypeResult ActOnTypeName(Declarator &D);
15434
15435 // Check whether the size of array element of type \p EltTy is a multiple of
15436 // its alignment and return false if it isn't.
15437 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
15438
15439 void
15440 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15441 SourceLocation FallbackLoc,
15442 SourceLocation ConstQualLoc = SourceLocation(),
15443 SourceLocation VolatileQualLoc = SourceLocation(),
15444 SourceLocation RestrictQualLoc = SourceLocation(),
15445 SourceLocation AtomicQualLoc = SourceLocation(),
15446 SourceLocation UnalignedQualLoc = SourceLocation());
15447
15448 /// Retrieve the keyword associated
15449 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
15450
15451 /// Adjust the calling convention of a method to be the ABI default if it
15452 /// wasn't specified explicitly. This handles method types formed from
15453 /// function type typedefs and typename template arguments.
15454 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15455 bool IsCtorOrDtor, SourceLocation Loc);
15456
15457 // Check if there is an explicit attribute, but only look through parens.
15458 // The intent is to look for an attribute on the current declarator, but not
15459 // one that came from a typedef.
15460 bool hasExplicitCallingConv(QualType T);
15461
15462 /// Check whether a nullability type specifier can be added to the given
15463 /// type through some means not written in source (e.g. API notes).
15464 ///
15465 /// \param Type The type to which the nullability specifier will be
15466 /// added. On success, this type will be updated appropriately.
15467 ///
15468 /// \param Nullability The nullability specifier to add.
15469 ///
15470 /// \param DiagLoc The location to use for diagnostics.
15471 ///
15472 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15473 /// array type (e.g., because it will decay to a pointer).
15474 ///
15475 /// \param OverrideExisting Whether to override an existing, locally-specified
15476 /// nullability specifier rather than complaining about the conflict.
15477 ///
15478 /// \returns true if nullability cannot be applied, false otherwise.
15479 bool CheckImplicitNullabilityTypeSpecifier(QualType &Type,
15480 NullabilityKind Nullability,
15481 SourceLocation DiagLoc,
15482 bool AllowArrayTypes,
15483 bool OverrideExisting);
15484
15485 /// Check whether the given variable declaration has a size that fits within
15486 /// the address space it is declared in. This issues a diagnostic if not.
15487 ///
15488 /// \param VD The variable declaration to check the size of.
15489 ///
15490 /// \param AS The address space to check the size of \p VD against.
15491 ///
15492 /// \returns true if the variable's size fits within the address space, false
15493 /// otherwise.
15494 bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS);
15495
15496 /// Get the type of expression E, triggering instantiation to complete the
15497 /// type if necessary -- that is, if the expression refers to a templated
15498 /// static data member of incomplete array type.
15499 ///
15500 /// May still return an incomplete type if instantiation was not possible or
15501 /// if the type is incomplete for a different reason. Use
15502 /// RequireCompleteExprType instead if a diagnostic is expected for an
15503 /// incomplete expression type.
15504 QualType getCompletedType(Expr *E);
15505
15506 void completeExprArrayBound(Expr *E);
15507
15508 /// Ensure that the type of the given expression is complete.
15509 ///
15510 /// This routine checks whether the expression \p E has a complete type. If
15511 /// the expression refers to an instantiable construct, that instantiation is
15512 /// performed as needed to complete its type. Furthermore
15513 /// Sema::RequireCompleteType is called for the expression's type (or in the
15514 /// case of a reference type, the referred-to type).
15515 ///
15516 /// \param E The expression whose type is required to be complete.
15517 /// \param Kind Selects which completeness rules should be applied.
15518 /// \param Diagnoser The object that will emit a diagnostic if the type is
15519 /// incomplete.
15520 ///
15521 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15522 /// otherwise.
15523 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
15524 TypeDiagnoser &Diagnoser);
15525 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15526
15527 template <typename... Ts>
15528 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15529 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15530 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
15531 }
15532
15533 // Returns the underlying type of a decltype with the given expression.
15534 QualType getDecltypeForExpr(Expr *E);
15535
15536 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
15537 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15538 /// context, such as when building a type for decltype(auto).
15539 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15540
15541 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15542 SourceLocation Loc,
15543 SourceLocation EllipsisLoc);
15544 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15545 SourceLocation Loc, SourceLocation EllipsisLoc,
15546 bool FullySubstituted = false,
15547 ArrayRef<QualType> Expansions = {});
15548
15549 using UTTKind = UnaryTransformType::UTTKind;
15550 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
15551 SourceLocation Loc);
15552 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
15553 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
15554 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
15555 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
15556 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
15557 SourceLocation Loc);
15558 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
15559 SourceLocation Loc);
15560 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
15561 SourceLocation Loc);
15562
15563 QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc) {
15564 return BuiltinRemoveReference(BaseType, UKind: UTTKind::RemoveCVRef, Loc);
15565 }
15566
15567 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
15568 SourceLocation Loc);
15569 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
15570 SourceLocation Loc);
15571
15572 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15573
15574 /// Ensure that the type T is a literal type.
15575 ///
15576 /// This routine checks whether the type @p T is a literal type. If @p T is an
15577 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15578 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15579 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15580 /// it the type @p T), along with notes explaining why the type is not a
15581 /// literal type, and returns true.
15582 ///
15583 /// @param Loc The location in the source that the non-literal type
15584 /// diagnostic should refer to.
15585 ///
15586 /// @param T The type that this routine is examining for literalness.
15587 ///
15588 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15589 ///
15590 /// @returns @c true if @p T is not a literal type and a diagnostic was
15591 /// emitted, @c false otherwise.
15592 bool RequireLiteralType(SourceLocation Loc, QualType T,
15593 TypeDiagnoser &Diagnoser);
15594 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15595
15596 template <typename... Ts>
15597 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15598 const Ts &...Args) {
15599 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15600 return RequireLiteralType(Loc, T, Diagnoser);
15601 }
15602
15603 bool isCompleteType(SourceLocation Loc, QualType T,
15604 CompleteTypeKind Kind = CompleteTypeKind::Default) {
15605 return !RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser: nullptr);
15606 }
15607
15608 /// Ensure that the type T is a complete type.
15609 ///
15610 /// This routine checks whether the type @p T is complete in any
15611 /// context where a complete type is required. If @p T is a complete
15612 /// type, returns false. If @p T is a class template specialization,
15613 /// this routine then attempts to perform class template
15614 /// instantiation. If instantiation fails, or if @p T is incomplete
15615 /// and cannot be completed, issues the diagnostic @p diag (giving it
15616 /// the type @p T) and returns true.
15617 ///
15618 /// @param Loc The location in the source that the incomplete type
15619 /// diagnostic should refer to.
15620 ///
15621 /// @param T The type that this routine is examining for completeness.
15622 ///
15623 /// @param Kind Selects which completeness rules should be applied.
15624 ///
15625 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15626 /// @c false otherwise.
15627 bool RequireCompleteType(SourceLocation Loc, QualType T,
15628 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15629 bool RequireCompleteType(SourceLocation Loc, QualType T,
15630 CompleteTypeKind Kind, unsigned DiagID);
15631
15632 bool RequireCompleteType(SourceLocation Loc, QualType T,
15633 TypeDiagnoser &Diagnoser) {
15634 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, Diagnoser);
15635 }
15636 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15637 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, DiagID);
15638 }
15639
15640 template <typename... Ts>
15641 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15642 const Ts &...Args) {
15643 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15644 return RequireCompleteType(Loc, T, Diagnoser);
15645 }
15646
15647 /// Determine whether a declaration is visible to name lookup.
15648 bool isVisible(const NamedDecl *D) {
15649 return D->isUnconditionallyVisible() ||
15650 isAcceptableSlow(D, Kind: AcceptableKind::Visible);
15651 }
15652
15653 /// Determine whether a declaration is reachable.
15654 bool isReachable(const NamedDecl *D) {
15655 // All visible declarations are reachable.
15656 return D->isUnconditionallyVisible() ||
15657 isAcceptableSlow(D, Kind: AcceptableKind::Reachable);
15658 }
15659
15660 /// Determine whether a declaration is acceptable (visible/reachable).
15661 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
15662 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15663 }
15664
15665 /// Determine if \p D and \p Suggested have a structurally compatible
15666 /// layout as described in C11 6.2.7/1.
15667 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15668
15669 /// Determine if \p D has a visible definition. If not, suggest a declaration
15670 /// that should be made visible to expose the definition.
15671 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15672 bool OnlyNeedComplete = false);
15673 bool hasVisibleDefinition(const NamedDecl *D) {
15674 NamedDecl *Hidden;
15675 return hasVisibleDefinition(D: const_cast<NamedDecl *>(D), Suggested: &Hidden);
15676 }
15677 /// Determine if \p D has a definition which allows we redefine it in current
15678 /// TU. \p Suggested is the definition that should be made visible to expose
15679 /// the definition.
15680 bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
15681 bool &Visible);
15682 bool isRedefinitionAllowedFor(const NamedDecl *D, bool &Visible) {
15683 NamedDecl *Hidden;
15684 return isRedefinitionAllowedFor(D: const_cast<NamedDecl *>(D), Suggested: &Hidden,
15685 Visible);
15686 }
15687
15688 /// Determine if \p D has a reachable definition. If not, suggest a
15689 /// declaration that should be made reachable to expose the definition.
15690 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15691 bool OnlyNeedComplete = false);
15692 bool hasReachableDefinition(NamedDecl *D) {
15693 NamedDecl *Hidden;
15694 return hasReachableDefinition(D, Suggested: &Hidden);
15695 }
15696
15697 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15698 AcceptableKind Kind,
15699 bool OnlyNeedComplete = false);
15700 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
15701 NamedDecl *Hidden;
15702 return hasAcceptableDefinition(D, Suggested: &Hidden, Kind);
15703 }
15704
15705 /// Try to parse the conditional expression attached to an effect attribute
15706 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15707 /// optional on error.
15708 std::optional<FunctionEffectMode>
15709 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15710
15711 void ActOnCleanupAttr(Decl *D, const Attr *A);
15712 void ActOnInitPriorityAttr(Decl *D, const Attr *A);
15713
15714private:
15715 /// The implementation of RequireCompleteType
15716 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15717 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15718
15719 /// Nullability type specifiers.
15720 IdentifierInfo *Ident__Nonnull = nullptr;
15721 IdentifierInfo *Ident__Nullable = nullptr;
15722 IdentifierInfo *Ident__Nullable_result = nullptr;
15723 IdentifierInfo *Ident__Null_unspecified = nullptr;
15724
15725 ///@}
15726
15727 //
15728 //
15729 // -------------------------------------------------------------------------
15730 //
15731 //
15732
15733 /// \name FixIt Helpers
15734 /// Implementations are in SemaFixItUtils.cpp
15735 ///@{
15736
15737public:
15738 /// Get a string to suggest for zero-initialization of a type.
15739 std::string getFixItZeroInitializerForType(QualType T,
15740 SourceLocation Loc) const;
15741 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15742
15743 ///@}
15744
15745 //
15746 //
15747 // -------------------------------------------------------------------------
15748 //
15749 //
15750
15751 /// \name Function Effects
15752 /// Implementations are in SemaFunctionEffects.cpp
15753 ///@{
15754public:
15755 struct FunctionEffectDiff {
15756 enum class Kind { Added, Removed, ConditionMismatch };
15757
15758 FunctionEffect::Kind EffectKind;
15759 Kind DiffKind;
15760 std::optional<FunctionEffectWithCondition>
15761 Old; // Invalid when 'Kind' is 'Added'.
15762 std::optional<FunctionEffectWithCondition>
15763 New; // Invalid when 'Kind' is 'Removed'.
15764
15765 StringRef effectName() const {
15766 if (Old)
15767 return Old.value().Effect.name();
15768 return New.value().Effect.name();
15769 }
15770
15771 /// Describes the result of effects differing between a base class's virtual
15772 /// method and an overriding method in a subclass.
15773 enum class OverrideResult {
15774 NoAction,
15775 Warn,
15776 Merge // Merge missing effect from base to derived.
15777 };
15778
15779 /// Return true if adding or removing the effect as part of a type
15780 /// conversion should generate a diagnostic.
15781 bool shouldDiagnoseConversion(QualType SrcType,
15782 const FunctionEffectsRef &SrcFX,
15783 QualType DstType,
15784 const FunctionEffectsRef &DstFX) const;
15785
15786 /// Return true if adding or removing the effect in a redeclaration should
15787 /// generate a diagnostic.
15788 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15789 const FunctionEffectsRef &OldFX,
15790 const FunctionDecl &NewFunction,
15791 const FunctionEffectsRef &NewFX) const;
15792
15793 /// Return true if adding or removing the effect in a C++ virtual method
15794 /// override should generate a diagnostic.
15795 OverrideResult shouldDiagnoseMethodOverride(
15796 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15797 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15798 };
15799
15800 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15801 /// Caller should short-circuit by checking for equality first.
15802 FunctionEffectDiffVector(const FunctionEffectsRef &Old,
15803 const FunctionEffectsRef &New);
15804 };
15805
15806 /// All functions/lambdas/blocks which have bodies and which have a non-empty
15807 /// FunctionEffectsRef to be verified.
15808 SmallVector<const Decl *> DeclsWithEffectsToVerify;
15809
15810 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
15811 /// are all null.
15812 FunctionEffectKindSet AllEffectsToVerify;
15813
15814public:
15815 /// Warn and return true if adding a function effect to a set would create a
15816 /// conflict.
15817 bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX,
15818 const FunctionEffectWithCondition &EC,
15819 SourceLocation NewAttrLoc);
15820
15821 // Report a failure to merge function effects between declarations due to a
15822 // conflict.
15823 void
15824 diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs,
15825 SourceLocation NewLoc,
15826 SourceLocation OldLoc);
15827
15828 /// Inline checks from the start of maybeAddDeclWithEffects, to
15829 /// minimize performance impact on code not using effects.
15830 template <class FuncOrBlockDecl>
15831 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
15832 if (Context.hasAnyFunctionEffects())
15833 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
15834 maybeAddDeclWithEffects(D, FX);
15835 }
15836
15837 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
15838 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15839
15840 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
15841 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15842
15843 void performFunctionEffectAnalysis(TranslationUnitDecl *TU);
15844
15845 ///@}
15846
15847 //
15848 //
15849 // -------------------------------------------------------------------------
15850 //
15851 //
15852
15853 /// \name Expansion Statements
15854 /// Implementations are in SemaExpand.cpp
15855 ///@{
15856public:
15857 CXXExpansionStmtDecl *ActOnCXXExpansionStmtDecl(unsigned TemplateDepth,
15858 SourceLocation TemplateKWLoc);
15859
15860 CXXExpansionStmtDecl *
15861 BuildCXXExpansionStmtDecl(DeclContext *Ctx, SourceLocation TemplateKWLoc,
15862 NonTypeTemplateParmDecl *NTTP);
15863
15864 ExprResult ActOnCXXExpansionInitList(MultiExprArg SubExprs,
15865 SourceLocation LBraceLoc,
15866 SourceLocation RBraceLoc);
15867
15868 StmtResult ActOnCXXExpansionStmtPattern(
15869 CXXExpansionStmtDecl *ESD, Stmt *Init, Stmt *ExpansionVarStmt,
15870 Expr *ExpansionInitializer, SourceLocation LParenLoc,
15871 SourceLocation ColonLoc, SourceLocation RParenLoc,
15872 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps);
15873
15874 StmtResult FinishCXXExpansionStmt(Stmt *Expansion, Stmt *Body);
15875
15876 StmtResult BuildCXXEnumeratingExpansionStmtPattern(Decl *ESD, Stmt *Init,
15877 Stmt *ExpansionVar,
15878 SourceLocation LParenLoc,
15879 SourceLocation ColonLoc,
15880 SourceLocation RParenLoc);
15881
15882 StmtResult BuildNonEnumeratingCXXExpansionStmtPattern(
15883 CXXExpansionStmtDecl *ESD, Stmt *Init, DeclStmt *ExpansionVarStmt,
15884 Expr *ExpansionInitializer, SourceLocation LParenLoc,
15885 SourceLocation ColonLoc, SourceLocation RParenLoc,
15886 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
15887
15888 ExprResult BuildCXXExpansionSelectExpr(InitListExpr *Range, Expr *Idx);
15889
15890 std::optional<uint64_t>
15891 ComputeExpansionSize(CXXExpansionStmtPattern *Expansion);
15892 ///@}
15893};
15894
15895DeductionFailureInfo
15896MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK,
15897 sema::TemplateDeductionInfo &Info);
15898
15899/// Contains a late templated function.
15900/// Will be parsed at the end of the translation unit, used by Sema & Parser.
15901struct LateParsedTemplate {
15902 CachedTokens Toks;
15903 /// The template function declaration to be late parsed.
15904 Decl *D;
15905 /// Floating-point options in the point of definition.
15906 FPOptions FPO;
15907};
15908
15909template <>
15910void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
15911 PragmaMsStackAction Action,
15912 llvm::StringRef StackSlotLabel,
15913 AlignPackInfo Value);
15914
15915} // end namespace clang
15916
15917#endif
15918