clang 20.0.0git
Sema.h
Go to the documentation of this file.
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
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/Attr.h"
21#include "clang/AST/CharUnits.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
32#include "clang/AST/StmtCXX.h"
33#include "clang/AST/Type.h"
34#include "clang/AST/TypeLoc.h"
38#include "clang/Basic/Cuda.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/Lambda.h"
45#include "clang/Basic/Module.h"
57#include "clang/Sema/Attr.h"
59#include "clang/Sema/DeclSpec.h"
65#include "clang/Sema/Scope.h"
66#include "clang/Sema/SemaBase.h"
68#include "clang/Sema/Weak.h"
69#include "llvm/ADT/APInt.h"
70#include "llvm/ADT/ArrayRef.h"
71#include "llvm/ADT/BitmaskEnum.h"
72#include "llvm/ADT/DenseMap.h"
73#include "llvm/ADT/DenseSet.h"
74#include "llvm/ADT/FloatingPointMode.h"
75#include "llvm/ADT/FoldingSet.h"
76#include "llvm/ADT/MapVector.h"
77#include "llvm/ADT/PointerIntPair.h"
78#include "llvm/ADT/PointerUnion.h"
79#include "llvm/ADT/STLExtras.h"
80#include "llvm/ADT/STLForwardCompat.h"
81#include "llvm/ADT/STLFunctionalExtras.h"
82#include "llvm/ADT/SetVector.h"
83#include "llvm/ADT/SmallBitVector.h"
84#include "llvm/ADT/SmallPtrSet.h"
85#include "llvm/ADT/SmallSet.h"
86#include "llvm/ADT/SmallVector.h"
87#include "llvm/ADT/StringExtras.h"
88#include "llvm/ADT/StringMap.h"
89#include "llvm/ADT/TinyPtrVector.h"
90#include "llvm/Support/Allocator.h"
91#include "llvm/Support/Compiler.h"
92#include "llvm/Support/Error.h"
93#include "llvm/Support/ErrorHandling.h"
94#include <cassert>
95#include <climits>
96#include <cstddef>
97#include <cstdint>
98#include <deque>
99#include <functional>
100#include <iterator>
101#include <memory>
102#include <optional>
103#include <string>
104#include <tuple>
105#include <type_traits>
106#include <utility>
107#include <vector>
108
109namespace llvm {
110struct InlineAsmIdentifierInfo;
111} // namespace llvm
112
113namespace clang {
114class ADLResult;
115class APValue;
116struct ASTConstraintSatisfaction;
117class ASTConsumer;
118class ASTContext;
119class ASTDeclReader;
120class ASTMutationListener;
121class ASTReader;
122class ASTWriter;
123class CXXBasePath;
124class CXXBasePaths;
125class CXXFieldCollector;
126class CodeCompleteConsumer;
127enum class ComparisonCategoryType : unsigned char;
128class ConstraintSatisfaction;
129class DarwinSDKInfo;
130class DeclGroupRef;
131class DeducedTemplateArgument;
132struct DeductionFailureInfo;
133class DependentDiagnostic;
134class Designation;
135class IdentifierInfo;
136class ImplicitConversionSequence;
137typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
138class InitializationKind;
139class InitializationSequence;
140class InitializedEntity;
141enum class LangAS : unsigned int;
142class LocalInstantiationScope;
143class LookupResult;
144class MangleNumberingContext;
145typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
146class ModuleLoader;
147class MultiLevelTemplateArgumentList;
148struct NormalizedConstraint;
149class ObjCInterfaceDecl;
150class ObjCMethodDecl;
151struct OverloadCandidate;
152enum class OverloadCandidateParamOrder : char;
154class OverloadCandidateSet;
155class Preprocessor;
156class SemaAMDGPU;
157class SemaARM;
158class SemaAVR;
159class SemaBPF;
160class SemaCodeCompletion;
161class SemaCUDA;
162class SemaHLSL;
163class SemaHexagon;
164class SemaLoongArch;
165class SemaM68k;
166class SemaMIPS;
167class SemaMSP430;
168class SemaNVPTX;
169class SemaObjC;
170class SemaOpenACC;
171class SemaOpenCL;
172class SemaOpenMP;
173class SemaPPC;
174class SemaPseudoObject;
175class SemaRISCV;
176class SemaSYCL;
177class SemaSwift;
178class SemaSystemZ;
179class SemaWasm;
180class SemaX86;
181class StandardConversionSequence;
182class TemplateArgument;
183class TemplateArgumentLoc;
184class TemplateInstantiationCallback;
185class TemplatePartialOrderingContext;
186class TemplateSpecCandidateSet;
187class Token;
188class TypeConstraint;
189class TypoCorrectionConsumer;
190class UnresolvedSetImpl;
191class UnresolvedSetIterator;
192class VisibleDeclConsumer;
193
194namespace sema {
195class BlockScopeInfo;
196class Capture;
197class CapturedRegionScopeInfo;
198class CapturingScopeInfo;
199class CompoundScopeInfo;
200class DelayedDiagnostic;
201class DelayedDiagnosticPool;
202class FunctionScopeInfo;
203class LambdaScopeInfo;
204class SemaPPCallbacks;
205class TemplateDeductionInfo;
206} // namespace sema
207
208// AssignmentAction - This is used by all the assignment diagnostic functions
209// to represent what is actually causing the operation
211 Assigning,
212 Passing,
213 Returning,
216 Sending,
217 Casting,
219};
221 const AssignmentAction &AA) {
222 DB << llvm::to_underlying(AA);
223 return DB;
224}
225
226namespace threadSafety {
227class BeforeSet;
228void threadSafetyCleanup(BeforeSet *Cache);
229} // namespace threadSafety
230
231// FIXME: No way to easily map from TemplateTypeParmTypes to
232// TemplateTypeParmDecls, so we have this horrible PointerUnion.
233typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *>,
234 SourceLocation>
236
237/// Describes whether we've seen any nullability information for the given
238/// file.
240 /// The first pointer declarator (of any pointer kind) in the file that does
241 /// not have a corresponding nullability annotation.
243
244 /// The end location for the first pointer declarator in the file. Used for
245 /// placing fix-its.
247
248 /// Which kind of pointer declarator we saw.
249 uint8_t PointerKind;
250
251 /// Whether we saw any type nullability annotations in the given file.
252 bool SawTypeNullability = false;
253};
254
255/// A mapping from file IDs to a record of whether we've seen nullability
256/// information in that file.
258 /// A mapping from file IDs to the nullability information for each file ID.
259 llvm::DenseMap<FileID, FileNullability> Map;
260
261 /// A single-element cache based on the file ID.
262 struct {
265 } Cache;
266
267public:
269 // Check the single-element cache.
270 if (file == Cache.File)
271 return Cache.Nullability;
272
273 // It's not in the single-element cache; flush the cache if we have one.
274 if (!Cache.File.isInvalid()) {
275 Map[Cache.File] = Cache.Nullability;
276 }
277
278 // Pull this entry into the cache.
279 Cache.File = file;
280 Cache.Nullability = Map[file];
281 return Cache.Nullability;
282 }
283};
284
285/// Tracks expected type during expression parsing, for use in code completion.
286/// The type is tied to a particular token, all functions that update or consume
287/// the type take a start location of the token they are looking at as a
288/// parameter. This avoids updating the type on hot paths in the parser.
290public:
291 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
292
293 void enterCondition(Sema &S, SourceLocation Tok);
294 void enterReturn(Sema &S, SourceLocation Tok);
296 /// Handles e.g. BaseType{ .D = Tok...
298 const Designation &D);
299 /// Computing a type for the function argument may require running
300 /// overloading, so we postpone its computation until it is actually needed.
301 ///
302 /// Clients should be very careful when using this function, as it stores a
303 /// function_ref, clients should make sure all calls to get() with the same
304 /// location happen while function_ref is alive.
305 ///
306 /// The callback should also emit signature help as a side-effect, but only
307 /// if the completion point has been reached.
309 llvm::function_ref<QualType()> ComputeType);
310
312 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
313 SourceLocation OpLoc);
314 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
316 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
317 /// Handles all type casts, including C-style cast, C++ casts, etc.
319
320 /// Get the expected type associated with this location, if any.
321 ///
322 /// If the location is a function argument, determining the expected type
323 /// involves considering all function overloads and the arguments so far.
324 /// In this case, signature help for these function overloads will be reported
325 /// as a side-effect (only if the completion point has been reached).
327 if (!Enabled || Tok != ExpectedLoc)
328 return QualType();
329 if (!Type.isNull())
330 return Type;
331 if (ComputeType)
332 return ComputeType();
333 return QualType();
334 }
335
336private:
337 bool Enabled;
338 /// Start position of a token for which we store expected type.
339 SourceLocation ExpectedLoc;
340 /// Expected type for a token starting at ExpectedLoc.
342 /// A function to compute expected type at ExpectedLoc. It is only considered
343 /// if Type is null.
344 llvm::function_ref<QualType()> ComputeType;
345};
346
348 SkipBodyInfo() = default;
349 bool ShouldSkip = false;
351 NamedDecl *Previous = nullptr;
352 NamedDecl *New = nullptr;
353};
354
355/// Describes the result of template argument deduction.
356///
357/// The TemplateDeductionResult enumeration describes the result of
358/// template argument deduction, as returned from
359/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
360/// structure provides additional information about the results of
361/// template argument deduction, e.g., the deduced template argument
362/// list (if successful) or the specific template parameters or
363/// deduced arguments that were involved in the failure.
365 /// Template argument deduction was successful.
366 Success = 0,
367 /// The declaration was invalid; do nothing.
368 Invalid,
369 /// Template argument deduction exceeded the maximum template
370 /// instantiation depth (which has already been diagnosed).
372 /// Template argument deduction did not deduce a value
373 /// for every template parameter.
375 /// Template argument deduction did not deduce a value for every
376 /// expansion of an expanded template parameter pack.
378 /// Template argument deduction produced inconsistent
379 /// deduced values for the given template parameter.
381 /// Template argument deduction failed due to inconsistent
382 /// cv-qualifiers on a template parameter type that would
383 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
384 /// but were given a non-const "X".
386 /// Substitution of the deduced template argument values
387 /// resulted in an error.
389 /// After substituting deduced template arguments, a dependent
390 /// parameter type did not match the corresponding argument.
392 /// After substituting deduced template arguments, an element of
393 /// a dependent parameter type did not match the corresponding element
394 /// of the corresponding argument (when deducing from an initializer list).
396 /// A non-depnedent component of the parameter did not match the
397 /// corresponding component of the argument.
399 /// When performing template argument deduction for a function
400 /// template, there were too many call arguments.
402 /// When performing template argument deduction for a function
403 /// template, there were too few call arguments.
405 /// The explicitly-specified template arguments were not valid
406 /// template arguments for the given template.
408 /// Checking non-dependent argument conversions failed.
410 /// The deduced arguments did not satisfy the constraints associated
411 /// with the template.
413 /// Deduction failed; that's all we know.
415 /// CUDA Target attributes do not match.
417 /// Some error which was already diagnosed.
419};
420
421/// Kinds of C++ special members.
429 Invalid
430};
431
432/// The kind of conversion being performed.
434 /// An implicit conversion.
435 Implicit,
436 /// A C-style cast.
438 /// A functional-style cast.
440 /// A cast other than a C-style cast.
441 OtherCast,
442 /// A conversion for an operand of a builtin overloaded operator.
444};
445
446enum class TagUseKind {
447 Reference, // Reference to a tag: 'struct foo *X;'
448 Declaration, // Fwd decl of a tag: 'struct foo;'
449 Definition, // Definition of a tag: 'struct foo { int X; } Y;'
450 Friend // Friend declaration: 'friend struct foo;'
451};
452
453/// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
454enum class FunctionEffectMode : uint8_t {
455 None, // effect is not present.
456 False, // effect(false).
457 True, // effect(true).
458 Dependent // effect(expr) where expr is dependent.
459};
460
461/// Sema - This implements semantic analysis and AST building for C.
462/// \nosubgrouping
463class Sema final : public SemaBase {
464 // Table of Contents
465 // -----------------
466 // 1. Semantic Analysis (Sema.cpp)
467 // 2. API Notes (SemaAPINotes.cpp)
468 // 3. C++ Access Control (SemaAccess.cpp)
469 // 4. Attributes (SemaAttr.cpp)
470 // 5. Availability Attribute Handling (SemaAvailability.cpp)
471 // 6. Bounds Safety (SemaBoundsSafety.cpp)
472 // 7. Casts (SemaCast.cpp)
473 // 8. Extra Semantic Checking (SemaChecking.cpp)
474 // 9. C++ Coroutines (SemaCoroutine.cpp)
475 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
476 // 11. Declarations (SemaDecl.cpp)
477 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
478 // 13. C++ Declarations (SemaDeclCXX.cpp)
479 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
480 // 15. Expressions (SemaExpr.cpp)
481 // 16. C++ Expressions (SemaExprCXX.cpp)
482 // 17. Member Access Expressions (SemaExprMember.cpp)
483 // 18. Initializers (SemaInit.cpp)
484 // 19. C++ Lambda Expressions (SemaLambda.cpp)
485 // 20. Name Lookup (SemaLookup.cpp)
486 // 21. Modules (SemaModule.cpp)
487 // 22. C++ Overloading (SemaOverload.cpp)
488 // 23. Statements (SemaStmt.cpp)
489 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
490 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
491 // 26. C++ Templates (SemaTemplate.cpp)
492 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
493 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
494 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
495 // 30. C++ Template Declaration Instantiation
496 // (SemaTemplateInstantiateDecl.cpp)
497 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
498 // 32. Constraints and Concepts (SemaConcept.cpp)
499 // 33. Types (SemaType.cpp)
500 // 34. FixIt Helpers (SemaFixItUtils.cpp)
501 // 35. Function Effects (SemaFunctionEffects.cpp)
502
503 /// \name Semantic Analysis
504 /// Implementations are in Sema.cpp
505 ///@{
506
507public:
508 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
510 CodeCompleteConsumer *CompletionConsumer = nullptr);
511 ~Sema();
512
513 /// Perform initialization that occurs after the parser has been
514 /// initialized but before it parses anything.
515 void Initialize();
516
517 /// This virtual key function only exists to limit the emission of debug info
518 /// describing the Sema class. GCC and Clang only emit debug info for a class
519 /// with a vtable when the vtable is emitted. Sema is final and not
520 /// polymorphic, but the debug info size savings are so significant that it is
521 /// worth adding a vtable just to take advantage of this optimization.
522 virtual void anchor();
523
524 const LangOptions &getLangOpts() const { return LangOpts; }
527
530 Preprocessor &getPreprocessor() const { return PP; }
531 ASTContext &getASTContext() const { return Context; }
535
537 StringRef Platform);
539
540 /// Registers an external source. If an external source already exists,
541 /// creates a multiplex external source and appends to it.
542 ///
543 ///\param[in] E - A non-null external sema source.
544 ///
546
547 /// Print out statistics about the semantic analysis.
548 void PrintStats() const;
549
550 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
551 /// guaranteed). Produces a warning if we're low on stack space and allocates
552 /// more in that case. Use this in code that may recurse deeply (for example,
553 /// in template instantiation) to avoid stack overflow.
555 llvm::function_ref<void()> Fn);
556
557 /// Returns default addr space for method qualifiers.
559
560 /// Load weak undeclared identifiers from the external source.
562
563 /// Determine if VD, which must be a variable or function, is an external
564 /// symbol that nonetheless can't be referenced from outside this translation
565 /// unit because its type has no linkage and it's not extern "C".
566 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
567
568 /// Obtain a sorted list of functions that are undefined but ODR-used.
570 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
571
572 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
574 /// Retrieves list of suspicious delete-expressions that will be checked at
575 /// the end of translation unit.
576 const llvm::MapVector<FieldDecl *, DeleteLocs> &
578
579 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
580 /// This is closely coupled to the SemaDiagnosticBuilder class and
581 /// should not be used elsewhere.
582 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
583
584 void addImplicitTypedef(StringRef Name, QualType T);
585
586 /// Whether uncompilable error has occurred. This includes error happens
587 /// in deferred diagnostics.
588 bool hasUncompilableErrorOccurred() const;
589
590 /// Looks through the macro-expansion chain for the given
591 /// location, looking for a macro expansion with the given name.
592 /// If one is found, returns true and sets the location to that
593 /// expansion loc.
594 bool findMacroSpelling(SourceLocation &loc, StringRef name);
595
596 /// Calls \c Lexer::getLocForEndOfToken()
598
599 /// Retrieve the module loader associated with the preprocessor.
601
602 /// Invent a new identifier for parameters of abbreviated templates.
605 unsigned Index);
606
608
609 // Emit all deferred diagnostics.
610 void emitDeferredDiags();
611
613 /// The global module fragment, between 'module;' and a module-declaration.
615 /// A normal translation unit fragment. For a non-module unit, this is the
616 /// entire translation unit. Otherwise, it runs from the module-declaration
617 /// to the private-module-fragment (if any) or the end of the TU (if not).
619 /// The private module fragment, between 'module :private;' and the end of
620 /// the translation unit.
621 Private
622 };
623
624 /// This is called before the very first declaration in the translation unit
625 /// is parsed. Note that the ASTContext may have already injected some
626 /// declarations.
628 /// ActOnEndOfTranslationUnit - This is called at the very end of the
629 /// translation unit when EOF is reached and all but the top-level scope is
630 /// popped.
633
634 /// Determines the active Scope associated with the given declaration
635 /// context.
636 ///
637 /// This routine maps a declaration context to the active Scope object that
638 /// represents that declaration context in the parser. It is typically used
639 /// from "scope-less" code (e.g., template instantiation, lazy creation of
640 /// declarations) that injects a name for name-lookup purposes and, therefore,
641 /// must update the Scope.
642 ///
643 /// \returns The scope corresponding to the given declaraion context, or NULL
644 /// if no such scope is open.
646
647 void PushFunctionScope();
648 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
650
651 /// This is used to inform Sema what the current TemplateParameterDepth
652 /// is during Parsing. Currently it is used to pass on the depth
653 /// when parsing generic lambda 'auto' parameters.
654 void RecordParsingTemplateParameterDepth(unsigned Depth);
655
656 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
658 unsigned OpenMPCaptureLevel = 0);
659
660 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
661 /// time after they've been popped.
663 Sema *Self;
664
665 public:
666 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
668 };
669
671 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
672
673 /// Pop a function (or block or lambda or captured region) scope from the
674 /// stack.
675 ///
676 /// \param WP The warning policy to use for CFG-based warnings, or null if
677 /// such warnings should not be produced.
678 /// \param D The declaration corresponding to this function scope, if
679 /// producing CFG-based warnings.
680 /// \param BlockType The type of the block expression, if D is a BlockDecl.
683 const Decl *D = nullptr,
684 QualType BlockType = QualType());
685
687
692
693 void PushCompoundScope(bool IsStmtExpr);
694 void PopCompoundScope();
695
696 /// Determine whether any errors occurred within this function/method/
697 /// block.
699
700 /// Retrieve the current block, if any.
702
703 /// Get the innermost lambda or block enclosing the current location, if any.
704 /// This looks through intervening non-lambda, non-block scopes such as local
705 /// functions.
707
708 /// Retrieve the current lambda scope info, if any.
709 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
710 /// lambda scope info ignoring all inner capturing scopes that are not
711 /// lambda scopes.
713 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
714
715 /// Retrieve the current generic lambda info, if any.
717
718 /// Retrieve the current captured region, if any.
720
721 void ActOnComment(SourceRange Comment);
722
723 /// Retrieve the parser's current scope.
724 ///
725 /// This routine must only be used when it is certain that semantic analysis
726 /// and the parser are in precisely the same context, which is not the case
727 /// when, e.g., we are performing any kind of template instantiation.
728 /// Therefore, the only safe places to use this scope are in the parser
729 /// itself and in routines directly invoked from the parser and *never* from
730 /// template substitution or instantiation.
731 Scope *getCurScope() const { return CurScope; }
732
734
737 }
738
739 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
740 const FunctionDecl *FD = nullptr);
742 const PartialDiagnostic &PD,
743 const FunctionDecl *FD = nullptr) {
744 return targetDiag(Loc, PD.getDiagID(), FD) << PD;
745 }
746
747 /// Check if the type is allowed to be used for the current target.
749 ValueDecl *D = nullptr);
750
751 // /// The kind of conversion being performed.
752 // enum CheckedConversionKind {
753 // /// An implicit conversion.
754 // CCK_ImplicitConversion,
755 // /// A C-style cast.
756 // CCK_CStyleCast,
757 // /// A functional-style cast.
758 // CCK_FunctionalCast,
759 // /// A cast other than a C-style cast.
760 // CCK_OtherCast,
761 // /// A conversion for an operand of a builtin overloaded operator.
762 // CCK_ForBuiltinOverloadedOp
763 // };
764
765 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
766 /// cast. If there is already an implicit cast, merge into the existing one.
767 /// If isLvalue, the result of the cast is an lvalue.
770 const CXXCastPath *BasePath = nullptr,
772
773 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
774 /// to the conversion from scalar type ScalarTy to the Boolean type.
776
777 /// If \p AllowLambda is true, treat lambda as function.
778 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
779
780 /// Returns a pointer to the innermost enclosing function, or nullptr if the
781 /// current context is not inside a function. If \p AllowLambda is true,
782 /// this can return the call operator of an enclosing lambda, otherwise
783 /// lambdas are skipped when looking for an enclosing function.
784 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
785
786 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
787 /// the method decl for the method being parsed. If we're currently
788 /// in a 'block', this returns the containing context.
790
791 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
792 /// or C function we're in, otherwise return null. If we're currently
793 /// in a 'block', this returns the containing context.
795
796 /// Warn if we're implicitly casting from a _Nullable pointer type to a
797 /// _Nonnull one.
800
801 /// Warn when implicitly casting 0 to nullptr.
803
804 /// Warn when implicitly changing function effects.
807
808 /// makeUnavailableInSystemHeader - There is an error in the current
809 /// context. If we're still in a system header, and we can plausibly
810 /// make the relevant declaration unavailable instead of erroring, do
811 /// so and return true.
813 UnavailableAttr::ImplicitReason reason);
814
815 /// Retrieve a suitable printing policy for diagnostics.
818 }
819
820 /// Retrieve a suitable printing policy for diagnostics.
822 const Preprocessor &PP);
823
824 /// Scope actions.
826
827 /// Determine whether \param D is function like (function or function
828 /// template) for parsing.
830
831 /// The maximum alignment, same as in llvm::Value. We duplicate them here
832 /// because that allows us not to duplicate the constants in clang code,
833 /// which we must to since we can't directly use the llvm constants.
834 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
835 ///
836 /// This is the greatest alignment value supported by load, store, and alloca
837 /// instructions, and global values.
838 static const unsigned MaxAlignmentExponent = 32;
839 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
840
841 /// Flag indicating whether or not to collect detailed statistics.
843
844 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
845
846 /// Stack containing information about each of the nested
847 /// function, block, and method scopes that are currently active.
849
850 /// The index of the first FunctionScope that corresponds to the current
851 /// context.
853
854 /// Track the number of currently active capturing scopes.
856
857 llvm::BumpPtrAllocator BumpAlloc;
858
859 /// The kind of translation unit we are processing.
860 ///
861 /// When we're processing a complete translation unit, Sema will perform
862 /// end-of-translation-unit semantic tasks (such as creating
863 /// initializers for tentative definitions in C) once parsing has
864 /// completed. Modules and precompiled headers perform different kinds of
865 /// checks.
867
868 /// Translation Unit Scope - useful to Objective-C actions that need
869 /// to lookup file scope declarations in the "ordinary" C decl namespace.
870 /// For example, user-defined classes, built-in "id" type, etc.
872
874 return CurScope->incrementMSManglingNumber();
875 }
876
877 /// Try to recover by turning the given expression into a
878 /// call. Returns true if recovery was attempted or an error was
879 /// emitted; this may also leave the ExprResult invalid.
881 bool ForceComplain = false,
882 bool (*IsPlausibleResult)(QualType) = nullptr);
883
884 /// Figure out if an expression could be turned into a call.
885 ///
886 /// Use this when trying to recover from an error where the programmer may
887 /// have written just the name of a function instead of actually calling it.
888 ///
889 /// \param E - The expression to examine.
890 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
891 /// with no arguments, this parameter is set to the type returned by such a
892 /// call; otherwise, it is set to an empty QualType.
893 /// \param OverloadSet - If the expression is an overloaded function
894 /// name, this parameter is populated with the decls of the various
895 /// overloads.
896 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
897 UnresolvedSetImpl &NonTemplateOverloads);
898
902
905
913
914 /// A RAII object to enter scope of a compound statement.
916 public:
917 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
918 S.ActOnStartOfCompoundStmt(IsStmtExpr);
919 }
920
922
923 private:
924 Sema &S;
925 };
926
927 /// An RAII helper that pops function a function scope on exit.
930 bool Active;
933 if (Active)
935 }
936 void disable() { Active = false; }
937 };
938
940 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
941 }
942
943 /// Worker object for performing CFG-based warnings.
946
947 /// Callback to the parser to parse templated functions when needed.
948 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
949 typedef void LateTemplateParserCleanupCB(void *P);
953
955 LateTemplateParserCleanupCB *LTPCleanup, void *P) {
956 LateTemplateParser = LTP;
957 LateTemplateParserCleanup = LTPCleanup;
958 OpaqueParser = P;
959 }
960
961 /// Callback to the parser to parse a type expressed as a string.
962 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
964
965 /// VAListTagName - The declaration name corresponding to __va_list_tag.
966 /// This is used as part of a hack to omit that class from ADL results.
968
969 /// Is the last error level diagnostic immediate. This is used to determined
970 /// whether the next info diagnostic should be immediate.
972
973 class DelayedDiagnostics;
974
976 sema::DelayedDiagnosticPool *SavedPool = nullptr;
978 };
981
982 /// A class which encapsulates the logic for delaying diagnostics
983 /// during parsing and other processing.
985 /// The current pool of diagnostics into which delayed
986 /// diagnostics should go.
987 sema::DelayedDiagnosticPool *CurPool = nullptr;
988
989 public:
991
992 /// Adds a delayed diagnostic.
993 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
994
995 /// Determines whether diagnostics should be delayed.
996 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
997
998 /// Returns the current delayed-diagnostics pool.
999 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1000
1001 /// Enter a new scope. Access and deprecation diagnostics will be
1002 /// collected in this pool.
1005 state.SavedPool = CurPool;
1006 CurPool = &pool;
1007 return state;
1008 }
1009
1010 /// Leave a delayed-diagnostic state that was previously pushed.
1011 /// Do not emit any of the diagnostics. This is performed as part
1012 /// of the bookkeeping of popping a pool "properly".
1014 CurPool = state.SavedPool;
1015 }
1016
1017 /// Enter a new scope where access and deprecation diagnostics are
1018 /// not delayed.
1021 state.SavedPool = CurPool;
1022 CurPool = nullptr;
1023 return state;
1024 }
1025
1026 /// Undo a previous pushUndelayed().
1028 assert(CurPool == nullptr);
1029 CurPool = state.SavedPool;
1030 }
1031 } DelayedDiagnostics;
1032
1034 return DelayedDiagnostics.push(pool);
1035 }
1036
1037 /// Diagnostics that are emitted only if we discover that the given function
1038 /// must be codegen'ed. Because handling these correctly adds overhead to
1039 /// compilation, this is currently only enabled for CUDA compilations.
1040 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1041
1042 /// CurContext - This is the current declaration context of parsing.
1044
1046 assert(AMDGPUPtr);
1047 return *AMDGPUPtr;
1048 }
1049
1051 assert(ARMPtr);
1052 return *ARMPtr;
1053 }
1054
1056 assert(AVRPtr);
1057 return *AVRPtr;
1058 }
1059
1061 assert(BPFPtr);
1062 return *BPFPtr;
1063 }
1064
1066 assert(CodeCompletionPtr);
1067 return *CodeCompletionPtr;
1068 }
1069
1071 assert(CUDAPtr);
1072 return *CUDAPtr;
1073 }
1074
1076 assert(HLSLPtr);
1077 return *HLSLPtr;
1078 }
1079
1081 assert(HexagonPtr);
1082 return *HexagonPtr;
1083 }
1084
1086 assert(LoongArchPtr);
1087 return *LoongArchPtr;
1088 }
1089
1091 assert(M68kPtr);
1092 return *M68kPtr;
1093 }
1094
1096 assert(MIPSPtr);
1097 return *MIPSPtr;
1098 }
1099
1101 assert(MSP430Ptr);
1102 return *MSP430Ptr;
1103 }
1104
1106 assert(NVPTXPtr);
1107 return *NVPTXPtr;
1108 }
1109
1111 assert(ObjCPtr);
1112 return *ObjCPtr;
1113 }
1114
1116 assert(OpenACCPtr);
1117 return *OpenACCPtr;
1118 }
1119
1121 assert(OpenCLPtr);
1122 return *OpenCLPtr;
1123 }
1124
1126 assert(OpenMPPtr && "SemaOpenMP is dead");
1127 return *OpenMPPtr;
1128 }
1129
1131 assert(PPCPtr);
1132 return *PPCPtr;
1133 }
1134
1136 assert(PseudoObjectPtr);
1137 return *PseudoObjectPtr;
1138 }
1139
1141 assert(RISCVPtr);
1142 return *RISCVPtr;
1143 }
1144
1146 assert(SYCLPtr);
1147 return *SYCLPtr;
1148 }
1149
1151 assert(SwiftPtr);
1152 return *SwiftPtr;
1153 }
1154
1156 assert(SystemZPtr);
1157 return *SystemZPtr;
1158 }
1159
1161 assert(WasmPtr);
1162 return *WasmPtr;
1163 }
1164
1166 assert(X86Ptr);
1167 return *X86Ptr;
1168 }
1169
1170 /// Source of additional semantic information.
1172
1173protected:
1174 friend class Parser;
1176 friend class ASTReader;
1177 friend class ASTDeclReader;
1178 friend class ASTWriter;
1179
1180private:
1181 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1182 bool WarnedDarwinSDKInfoMissing = false;
1183
1184 StackExhaustionHandler StackHandler;
1185
1186 Sema(const Sema &) = delete;
1187 void operator=(const Sema &) = delete;
1188
1189 /// The handler for the FileChanged preprocessor events.
1190 ///
1191 /// Used for diagnostics that implement custom semantic analysis for #include
1192 /// directives, like -Wpragma-pack.
1193 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1194
1195 /// The parser's current scope.
1196 ///
1197 /// The parser maintains this state here.
1198 Scope *CurScope;
1199
1200 mutable IdentifierInfo *Ident_super;
1201
1202 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1203 std::unique_ptr<SemaARM> ARMPtr;
1204 std::unique_ptr<SemaAVR> AVRPtr;
1205 std::unique_ptr<SemaBPF> BPFPtr;
1206 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1207 std::unique_ptr<SemaCUDA> CUDAPtr;
1208 std::unique_ptr<SemaHLSL> HLSLPtr;
1209 std::unique_ptr<SemaHexagon> HexagonPtr;
1210 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1211 std::unique_ptr<SemaM68k> M68kPtr;
1212 std::unique_ptr<SemaMIPS> MIPSPtr;
1213 std::unique_ptr<SemaMSP430> MSP430Ptr;
1214 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1215 std::unique_ptr<SemaObjC> ObjCPtr;
1216 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1217 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1218 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1219 std::unique_ptr<SemaPPC> PPCPtr;
1220 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1221 std::unique_ptr<SemaRISCV> RISCVPtr;
1222 std::unique_ptr<SemaSYCL> SYCLPtr;
1223 std::unique_ptr<SemaSwift> SwiftPtr;
1224 std::unique_ptr<SemaSystemZ> SystemZPtr;
1225 std::unique_ptr<SemaWasm> WasmPtr;
1226 std::unique_ptr<SemaX86> X86Ptr;
1227
1228 ///@}
1229
1230 //
1231 //
1232 // -------------------------------------------------------------------------
1233 //
1234 //
1235
1236 /// \name API Notes
1237 /// Implementations are in SemaAPINotes.cpp
1238 ///@{
1239
1240public:
1241 /// Map any API notes provided for this declaration to attributes on the
1242 /// declaration.
1243 ///
1244 /// Triggered by declaration-attribute processing.
1245 void ProcessAPINotes(Decl *D);
1246
1247 ///@}
1248
1249 //
1250 //
1251 // -------------------------------------------------------------------------
1252 //
1253 //
1254
1255 /// \name C++ Access Control
1256 /// Implementations are in SemaAccess.cpp
1257 ///@{
1258
1259public:
1266
1267 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1268 /// Returns true on error (when the previous member decl access specifier
1269 /// is different from the new member decl access specifier).
1270 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1271 NamedDecl *PrevMemberDecl,
1272 AccessSpecifier LexicalAS);
1273
1274 /// Perform access-control checking on a previously-unresolved member
1275 /// access which has now been resolved to a member.
1277 DeclAccessPair FoundDecl);
1279 DeclAccessPair FoundDecl);
1280
1281 /// Checks access to an overloaded operator new or delete.
1283 SourceRange PlacementRange,
1284 CXXRecordDecl *NamingClass,
1285 DeclAccessPair FoundDecl,
1286 bool Diagnose = true);
1287
1288 /// Checks access to a constructor.
1290 DeclAccessPair FoundDecl,
1291 const InitializedEntity &Entity,
1292 bool IsCopyBindingRefToTemp = false);
1293
1294 /// Checks access to a constructor.
1296 DeclAccessPair FoundDecl,
1297 const InitializedEntity &Entity,
1298 const PartialDiagnostic &PDiag);
1300 CXXDestructorDecl *Dtor,
1301 const PartialDiagnostic &PDiag,
1302 QualType objectType = QualType());
1303
1304 /// Checks access to the target of a friend declaration.
1306
1307 /// Checks access to a member.
1309 CXXRecordDecl *NamingClass,
1311
1312 /// Checks implicit access to a member in a structured binding.
1315 CXXRecordDecl *DecomposedClass,
1316 DeclAccessPair Field);
1318 const SourceRange &,
1319 DeclAccessPair FoundDecl);
1320
1321 /// Checks access to an overloaded member operator, including
1322 /// conversion operators.
1324 Expr *ArgExpr,
1325 DeclAccessPair FoundDecl);
1327 ArrayRef<Expr *> ArgExprs,
1328 DeclAccessPair FoundDecl);
1330 DeclAccessPair FoundDecl);
1331
1332 /// Checks access for a hierarchy conversion.
1333 ///
1334 /// \param ForceCheck true if this check should be performed even if access
1335 /// control is disabled; some things rely on this for semantics
1336 /// \param ForceUnprivileged true if this check should proceed as if the
1337 /// context had no special privileges
1339 QualType Derived, const CXXBasePath &Path,
1340 unsigned DiagID, bool ForceCheck = false,
1341 bool ForceUnprivileged = false);
1342
1343 /// Checks access to all the declarations in the given result set.
1344 void CheckLookupAccess(const LookupResult &R);
1345
1346 /// Checks access to Target from the given class. The check will take access
1347 /// specifiers into account, but no member access expressions and such.
1348 ///
1349 /// \param Target the declaration to check if it can be accessed
1350 /// \param NamingClass the class in which the lookup was started.
1351 /// \param BaseType type of the left side of member access expression.
1352 /// \p BaseType and \p NamingClass are used for C++ access control.
1353 /// Depending on the lookup case, they should be set to the following:
1354 /// - lhs.target (member access without a qualifier):
1355 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1356 /// - lhs.X::target (member access with a qualifier):
1357 /// BaseType is the type of 'lhs', NamingClass is 'X'
1358 /// - X::target (qualified lookup without member access):
1359 /// BaseType is null, NamingClass is 'X'.
1360 /// - target (unqualified lookup).
1361 /// BaseType is null, NamingClass is the parent class of 'target'.
1362 /// \return true if the Target is accessible from the Class, false otherwise.
1363 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1364 QualType BaseType);
1365
1366 /// Is the given member accessible for the purposes of deciding whether to
1367 /// define a special member function as deleted?
1369 DeclAccessPair Found, QualType ObjectType,
1371 const PartialDiagnostic &Diag);
1374 QualType ObjectType) {
1375 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1376 SourceLocation(), PDiag());
1377 }
1378
1380 const DependentDiagnostic &DD,
1381 const MultiLevelTemplateArgumentList &TemplateArgs);
1383
1384 ///@}
1385
1386 //
1387 //
1388 // -------------------------------------------------------------------------
1389 //
1390 //
1391
1392 /// \name Attributes
1393 /// Implementations are in SemaAttr.cpp
1394 ///@{
1395
1396public:
1397 /// Controls member pointer representation format under the MS ABI.
1400
1401 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1402
1403 /// Source location for newly created implicit MSInheritanceAttrs
1405
1406 /// pragma clang section kind
1413 PCSK_Relro = 5
1415
1417
1419 std::string SectionName;
1420 bool Valid = false;
1422 };
1423
1429
1431 PSK_Reset = 0x0, // #pragma ()
1432 PSK_Set = 0x1, // #pragma (value)
1433 PSK_Push = 0x2, // #pragma (push[, id])
1434 PSK_Pop = 0x4, // #pragma (pop[, id])
1435 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1436 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1437 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1438 };
1439
1442 StringRef SlotLabel;
1444 };
1445
1446 // #pragma pack and align.
1448 public:
1449 // `Native` represents default align mode, which may vary based on the
1450 // platform.
1451 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1452
1453 // #pragma pack info constructor
1454 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1455 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1456 assert(Num == PackNumber && "The pack number has been truncated.");
1457 }
1458
1459 // #pragma align info constructor
1461 : PackAttr(false), AlignMode(M),
1462 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1463
1464 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1465
1467
1468 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1469 // integer encoding for it. This should only be passed to
1470 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1471 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1472 std::uint32_t Encoding{};
1473 if (Info.IsXLStack())
1474 Encoding |= IsXLMask;
1475
1476 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1477
1478 if (Info.IsPackAttr())
1479 Encoding |= PackAttrMask;
1480
1481 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1482
1483 return Encoding;
1484 }
1485
1486 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1487 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1489 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1490 int PackNumber = (Encoding & PackNumMask) >> 4;
1491
1492 if (Encoding & PackAttrMask)
1493 return AlignPackInfo(M, PackNumber, IsXL);
1494
1495 return AlignPackInfo(M, IsXL);
1496 }
1497
1498 bool IsPackAttr() const { return PackAttr; }
1499
1500 bool IsAlignAttr() const { return !PackAttr; }
1501
1502 Mode getAlignMode() const { return AlignMode; }
1503
1504 unsigned getPackNumber() const { return PackNumber; }
1505
1506 bool IsPackSet() const {
1507 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1508 // attriute on a decl.
1509 return PackNumber != UninitPackVal && PackNumber != 0;
1510 }
1511
1512 bool IsXLStack() const { return XLStack; }
1513
1514 bool operator==(const AlignPackInfo &Info) const {
1515 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
1516 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
1517 Info.XLStack);
1518 }
1519
1520 bool operator!=(const AlignPackInfo &Info) const {
1521 return !(*this == Info);
1522 }
1523
1524 private:
1525 /// \brief True if this is a pragma pack attribute,
1526 /// not a pragma align attribute.
1527 bool PackAttr;
1528
1529 /// \brief The alignment mode that is in effect.
1530 Mode AlignMode;
1531
1532 /// \brief The pack number of the stack.
1533 unsigned char PackNumber;
1534
1535 /// \brief True if it is a XL #pragma align/pack stack.
1536 bool XLStack;
1537
1538 /// \brief Uninitialized pack value.
1539 static constexpr unsigned char UninitPackVal = -1;
1540
1541 // Masks to encode and decode an AlignPackInfo.
1542 static constexpr uint32_t IsXLMask{0x0000'0001};
1543 static constexpr uint32_t AlignModeMask{0x0000'0006};
1544 static constexpr uint32_t PackAttrMask{0x00000'0008};
1545 static constexpr uint32_t PackNumMask{0x0000'01F0};
1546 };
1547
1548 template <typename ValueType> struct PragmaStack {
1549 struct Slot {
1550 llvm::StringRef StackSlotLabel;
1551 ValueType Value;
1554 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
1559 };
1560
1561 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1562 llvm::StringRef StackSlotLabel, ValueType Value) {
1563 if (Action == PSK_Reset) {
1565 CurrentPragmaLocation = PragmaLocation;
1566 return;
1567 }
1568 if (Action & PSK_Push)
1569 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1570 PragmaLocation);
1571 else if (Action & PSK_Pop) {
1572 if (!StackSlotLabel.empty()) {
1573 // If we've got a label, try to find it and jump there.
1574 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
1575 return x.StackSlotLabel == StackSlotLabel;
1576 });
1577 // If we found the label so pop from there.
1578 if (I != Stack.rend()) {
1579 CurrentValue = I->Value;
1580 CurrentPragmaLocation = I->PragmaLocation;
1581 Stack.erase(std::prev(I.base()), Stack.end());
1582 }
1583 } else if (!Stack.empty()) {
1584 // We do not have a label, just pop the last entry.
1585 CurrentValue = Stack.back().Value;
1586 CurrentPragmaLocation = Stack.back().PragmaLocation;
1587 Stack.pop_back();
1588 }
1589 }
1590 if (Action & PSK_Set) {
1592 CurrentPragmaLocation = PragmaLocation;
1593 }
1594 }
1595
1596 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
1597 // method body to restore the stacks on exit, so it works like this:
1598 //
1599 // struct S {
1600 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
1601 // void Method {}
1602 // #pragma <name>(pop, InternalPragmaSlot)
1603 // };
1604 //
1605 // It works even with #pragma vtordisp, although MSVC doesn't support
1606 // #pragma vtordisp(push [, id], n)
1607 // syntax.
1608 //
1609 // Push / pop a named sentinel slot.
1610 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
1611 assert((Action == PSK_Push || Action == PSK_Pop) &&
1612 "Can only push / pop #pragma stack sentinels!");
1614 }
1615
1616 // Constructors.
1617 explicit PragmaStack(const ValueType &Default)
1619
1620 bool hasValue() const { return CurrentValue != DefaultValue; }
1621
1623 ValueType DefaultValue; // Value used for PSK_Reset action.
1624 ValueType CurrentValue;
1626 };
1627 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
1628 // we shouldn't do so if they're in a module).
1629
1630 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
1631 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
1632 ///
1633 /// 0: Suppress all vtordisps
1634 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
1635 /// structors
1636 /// 2: Always insert vtordisps to support RTTI on partially constructed
1637 /// objects
1640 // The current #pragma align/pack values and locations at each #include.
1645 };
1647 // Segment #pragmas.
1652
1653 // #pragma strict_gs_check.
1655
1656 // This stack tracks the current state of Sema.CurFPFeatures.
1659 FPOptionsOverride result;
1660 if (!FpPragmaStack.hasValue()) {
1661 result = FPOptionsOverride();
1662 } else {
1663 result = FpPragmaStack.CurrentValue;
1664 }
1665 return result;
1666 }
1667
1673 };
1674
1675 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
1676 // Actions should be performed only if we enter / exit a C++ method body.
1678 public:
1679 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
1681
1682 private:
1683 Sema &S;
1684 StringRef SlotLabel;
1685 bool ShouldAct;
1686 };
1687
1688 /// Last section used with #pragma init_seg.
1691
1692 /// Sections used with #pragma alloc_text.
1693 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
1694
1695 /// VisContext - Manages the stack for \#pragma GCC visibility.
1696 void *VisContext; // Really a "PragmaVisStack*"
1697
1698 /// This an attribute introduced by \#pragma clang attribute.
1704 };
1705
1706 /// A push'd group of PragmaAttributeEntries.
1708 /// The location of the push attribute.
1710 /// The namespace of this push group.
1713 };
1714
1716
1717 /// The declaration that is currently receiving an attribute from the
1718 /// #pragma attribute stack.
1720
1721 /// This represents the last location of a "#pragma clang optimize off"
1722 /// directive if such a directive has not been closed by an "on" yet. If
1723 /// optimizations are currently "on", this is set to an invalid location.
1725
1726 /// Get the location for the currently active "\#pragma clang optimize
1727 /// off". If this location is invalid, then the state of the pragma is "on".
1730 }
1731
1732 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
1733 /// whether the optimizations in the list passed to the pragma should be
1734 /// turned off or on. This boolean is true by default because command line
1735 /// options are honored when `#pragma optimize("", on)`.
1736 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
1738
1739 /// Set of no-builtin functions listed by \#pragma function.
1741
1742 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
1743 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
1745
1746 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
1748
1749 /// Add gsl::Pointer attribute to std::container::iterator
1750 /// \param ND The declaration that introduces the name
1751 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
1752 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
1753
1754 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
1756
1757 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
1759
1760 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
1762
1763 /// Add [[gsl::Pointer]] attributes for std:: types.
1765
1766 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
1767 StringRef ParamName);
1768 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
1769 // can be the name of a function parameter, we need to parse the function
1770 // declaration and rest of the parameters before processesing 'X'. Therefore
1771 // do this lazily instead of processing while parsing the annotation itself.
1773
1774 /// Add _Nullable attributes for std:: types.
1776
1778 POAK_Native, // #pragma options align=native
1779 POAK_Natural, // #pragma options align=natural
1780 POAK_Packed, // #pragma options align=packed
1781 POAK_Power, // #pragma options align=power
1782 POAK_Mac68k, // #pragma options align=mac68k
1783 POAK_Reset // #pragma options align=reset
1785
1786 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
1789 PragmaClangSectionKind SecKind,
1790 StringRef SecName);
1791
1792 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
1794 SourceLocation PragmaLoc);
1795
1796 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
1797 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
1798 StringRef SlotLabel, Expr *Alignment);
1799
1800 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
1801 /// (unless they are value dependent or type dependent). Returns false
1802 /// and emits a diagnostic if one or more of the arguments could not be
1803 /// folded into a constant.
1806
1810 };
1811
1813 SourceLocation IncludeLoc);
1815
1816 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
1818
1819 /// ActOnPragmaMSComment - Called on well formed
1820 /// \#pragma comment(kind, "arg").
1822 StringRef Arg);
1823
1824 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
1825 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
1826 StringRef Value);
1827
1828 /// Are precise floating point semantics currently enabled?
1830 return !CurFPFeatures.getAllowFPReassociate() &&
1831 !CurFPFeatures.getNoSignedZero() &&
1832 !CurFPFeatures.getAllowReciprocal() &&
1833 !CurFPFeatures.getAllowApproxFunc();
1834 }
1835
1838
1839 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
1842
1843 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
1844 /// pointers_to_members(representation method[, general purpose
1845 /// representation]).
1848 SourceLocation PragmaLoc);
1849
1850 /// Called on well formed \#pragma vtordisp().
1853
1854 bool UnifySection(StringRef SectionName, int SectionFlags,
1855 NamedDecl *TheDecl);
1856 bool UnifySection(StringRef SectionName, int SectionFlags,
1857 SourceLocation PragmaSectionLocation);
1858
1859 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
1860 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
1861 PragmaMsStackAction Action,
1862 llvm::StringRef StackSlotLabel,
1863 StringLiteral *SegmentName, llvm::StringRef PragmaName);
1864
1865 /// Called on well formed \#pragma section().
1866 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
1867 StringLiteral *SegmentName);
1868
1869 /// Called on well-formed \#pragma init_seg().
1870 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
1871 StringLiteral *SegmentName);
1872
1873 /// Called on well-formed \#pragma alloc_text().
1875 SourceLocation PragmaLocation, StringRef Section,
1876 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
1877 &Functions);
1878
1879 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
1880 /// strict_gs_check.
1882 PragmaMsStackAction Action,
1883 bool Value);
1884
1885 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
1886 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
1887 SourceLocation PragmaLoc);
1888
1890 SourceLocation PragmaLoc,
1893 const IdentifierInfo *Namespace);
1894
1895 /// Called on well-formed '\#pragma clang attribute pop'.
1897 const IdentifierInfo *Namespace);
1898
1899 /// Adds the attributes that have been specified using the
1900 /// '\#pragma clang attribute push' directives to the given declaration.
1901 void AddPragmaAttributes(Scope *S, Decl *D);
1902
1904
1906
1907 /// Called on well formed \#pragma clang optimize.
1908 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
1909
1910 /// #pragma optimize("[optimization-list]", on | off).
1911 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
1912
1913 /// Call on well formed \#pragma function.
1914 void
1916 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
1917
1918 /// Only called on function definitions; if there is a pragma in scope
1919 /// with the effect of a range-based optnone, consider marking the function
1920 /// with attribute optnone.
1922
1923 /// Only called on function definitions; if there is a `#pragma alloc_text`
1924 /// that decides which code section the function should be in, add
1925 /// attribute section to the function.
1927
1928 /// Adds the 'optnone' attribute to the function declaration if there
1929 /// are no conflicts; Loc represents the location causing the 'optnone'
1930 /// attribute to be added (usually because of a pragma).
1932
1933 /// Only called on function definitions; if there is a MSVC #pragma optimize
1934 /// in scope, consider changing the function's attributes based on the
1935 /// optimization list passed to the pragma.
1937
1938 /// Only called on function definitions; if there is a pragma in scope
1939 /// with the effect of a range-based no_builtin, consider marking the function
1940 /// with attribute no_builtin.
1942
1943 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
1944 /// add an appropriate visibility attribute.
1946
1947 /// FreeVisContext - Deallocate and null out VisContext.
1948 void FreeVisContext();
1949
1950 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
1951 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
1952 SourceLocation PragmaLoc);
1953
1954 /// ActOnPragmaFPContract - Called on well formed
1955 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
1956 /// \#pragma clang fp contract
1958
1959 /// Called on well formed
1960 /// \#pragma clang fp reassociate
1961 /// or
1962 /// \#pragma clang fp reciprocal
1964 bool IsEnabled);
1965
1966 /// ActOnPragmaFenvAccess - Called on well formed
1967 /// \#pragma STDC FENV_ACCESS
1968 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
1969
1970 /// ActOnPragmaCXLimitedRange - Called on well formed
1971 /// \#pragma STDC CX_LIMITED_RANGE
1974
1975 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
1978
1979 /// Called to set constant rounding mode for floating point operations.
1980 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
1981
1982 /// Called to set exception behavior for floating point operations.
1984
1985 /// PushNamespaceVisibilityAttr - Note that we've entered a
1986 /// namespace with a visibility attribute.
1987 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
1989
1990 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
1991 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
1992 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
1993
1994 /// Handles semantic checking for features that are common to all attributes,
1995 /// such as checking whether a parameter was properly specified, or the
1996 /// correct number of arguments were passed, etc. Returns true if the
1997 /// attribute has been diagnosed.
1998 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
1999 bool SkipArgCountCheck = false);
2000 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2001 bool SkipArgCountCheck = false);
2002
2003 ///@}
2004
2005 //
2006 //
2007 // -------------------------------------------------------------------------
2008 //
2009 //
2010
2011 /// \name Availability Attribute Handling
2012 /// Implementations are in SemaAvailability.cpp
2013 ///@{
2014
2015public:
2016 /// Issue any -Wunguarded-availability warnings in \c FD
2018
2020
2021 /// Retrieve the current function, if any, that should be analyzed for
2022 /// potential availability violations.
2024
2026 const ObjCInterfaceDecl *UnknownObjCClass,
2027 bool ObjCPropertyAccess,
2028 bool AvoidPartialAvailabilityChecks = false,
2029 ObjCInterfaceDecl *ClassReceiver = nullptr);
2030
2031 ///@}
2032
2033 //
2034 //
2035 // -------------------------------------------------------------------------
2036 //
2037 //
2038
2039 /// \name Bounds Safety
2040 /// Implementations are in SemaBoundsSafety.cpp
2041 ///@{
2042public:
2043 /// Check if applying the specified attribute variant from the "counted by"
2044 /// family of attributes to FieldDecl \p FD is semantically valid. If
2045 /// semantically invalid diagnostics will be emitted explaining the problems.
2046 ///
2047 /// \param FD The FieldDecl to apply the attribute to
2048 /// \param E The count expression on the attribute
2049 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2050 /// attributes. If the false the attribute is from
2051 /// "counted_by" family of attributes.
2052 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2053 /// of attributes. If false the attribute does not have the
2054 /// suffix.
2055 ///
2056 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2057 /// \p CountInBytes and \p OrNull both being true indicates the
2058 /// `counted_by_or_null` attribute.
2059 ///
2060 /// \returns false iff semantically valid.
2061 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2062 bool OrNull);
2063
2064 ///@}
2065
2066 //
2067 //
2068 // -------------------------------------------------------------------------
2069 //
2070 //
2071
2072 /// \name Casts
2073 /// Implementations are in SemaCast.cpp
2074 ///@{
2075
2076public:
2078 return CCK == CheckedConversionKind::CStyleCast ||
2081 }
2082
2083 /// ActOnCXXNamedCast - Parse
2084 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2086 SourceLocation LAngleBracketLoc, Declarator &D,
2087 SourceLocation RAngleBracketLoc,
2088 SourceLocation LParenLoc, Expr *E,
2089 SourceLocation RParenLoc);
2090
2092 TypeSourceInfo *Ty, Expr *E,
2093 SourceRange AngleBrackets, SourceRange Parens);
2094
2096 ExprResult Operand,
2097 SourceLocation RParenLoc);
2098
2100 Expr *Operand, SourceLocation RParenLoc);
2101
2102 // Checks that reinterpret casts don't have undefined behavior.
2103 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2104 bool IsDereference, SourceRange Range);
2105
2106 // Checks that the vector type should be initialized from a scalar
2107 // by splatting the value rather than populating a single element.
2108 // This is the case for AltiVecVector types as well as with
2109 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2110 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2111
2112 // Checks if the -faltivec-src-compat=gcc option is specified.
2113 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2114 // treated the same way as they are when trying to initialize
2115 // these vectors on gcc (an error is emitted).
2117 QualType SrcTy);
2118
2120 SourceLocation RParenLoc, Expr *Op);
2121
2123 SourceLocation LParenLoc,
2124 Expr *CastExpr,
2125 SourceLocation RParenLoc);
2126
2127 ///@}
2128
2129 //
2130 //
2131 // -------------------------------------------------------------------------
2132 //
2133 //
2134
2135 /// \name Extra Semantic Checking
2136 /// Implementations are in SemaChecking.cpp
2137 ///@{
2138
2139public:
2140 /// Used to change context to isConstantEvaluated without pushing a heavy
2141 /// ExpressionEvaluationContextRecord object.
2143
2147 }
2148
2150 unsigned ByteNo) const;
2151
2153 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2154 FAPK_Variadic, // values to format are passed as variadic arguments
2155 FAPK_VAList, // values to format are passed in a va_list
2156 };
2157
2158 // Used to grab the relevant information from a FormatAttr and a
2159 // FunctionDeclaration.
2161 unsigned FormatIdx;
2164 };
2165
2166 /// Given a FunctionDecl's FormatAttr, attempts to populate the
2167 /// FomatStringInfo parameter with the FormatAttr's correct format_idx and
2168 /// firstDataArg. Returns true when the format fits the function and the
2169 /// FormatStringInfo has been populated.
2170 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2171 bool IsVariadic, FormatStringInfo *FSI);
2172
2173 // Used by C++ template instantiation.
2175
2176 /// ConvertVectorExpr - Handle __builtin_convertvector
2178 SourceLocation BuiltinLoc,
2179 SourceLocation RParenLoc);
2180
2194 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2195
2196 bool FormatStringHasSArg(const StringLiteral *FExpr);
2197
2198 /// Check for comparisons of floating-point values using == and !=. Issue a
2199 /// warning if the comparison is not likely to do what the programmer
2200 /// intended.
2202 BinaryOperatorKind Opcode);
2203
2204 /// Register a magic integral constant to be used as a type tag.
2205 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2206 uint64_t MagicValue, QualType Type,
2207 bool LayoutCompatible, bool MustBeNull);
2208
2211
2215
2217
2218 /// If true, \c Type should be compared with other expression's types for
2219 /// layout-compatibility.
2220 LLVM_PREFERRED_TYPE(bool)
2222 LLVM_PREFERRED_TYPE(bool)
2223 unsigned MustBeNull : 1;
2224 };
2225
2226 /// A pair of ArgumentKind identifier and magic value. This uniquely
2227 /// identifies the magic value.
2228 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2229
2230 /// Diagnoses the current set of gathered accesses. This typically
2231 /// happens at full expression level. The set is cleared after emitting the
2232 /// diagnostics.
2234
2235 /// This function checks if the expression is in the sef of potentially
2236 /// misaligned members and it is converted to some pointer type T with lower
2237 /// or equal alignment requirements. If so it removes it. This is used when
2238 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2239 /// void*).
2241
2242 /// This function calls Action when it determines that E designates a
2243 /// misaligned member due to the packed attribute. This is used to emit
2244 /// local diagnostics like in reference binding.
2246 Expr *E,
2247 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2248 Action);
2249
2250 enum class AtomicArgumentOrder { API, AST };
2252 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2253 SourceLocation RParenLoc, MultiExprArg Args,
2256
2257 /// Check to see if a given expression could have '.c_str()' called on it.
2258 bool hasCStrMethod(const Expr *E);
2259
2260 /// Diagnose pointers that are always non-null.
2261 /// \param E the expression containing the pointer
2262 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2263 /// compared to a null pointer
2264 /// \param IsEqual True when the comparison is equal to a null pointer
2265 /// \param Range Extra SourceRange to highlight in the diagnostic
2268 bool IsEqual, SourceRange Range);
2269
2270 /// CheckParmsForFunctionDef - Check that the parameters of the given
2271 /// function are appropriate for the definition of a function. This
2272 /// takes care of any checks that cannot be performed on the
2273 /// declaration itself, e.g., that the types of each of the function
2274 /// parameters are complete.
2276 bool CheckParameterNames);
2277
2278 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2279 /// pointer cast increases the alignment requirements.
2280 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2281
2282 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2283 /// to weak/__unsafe_unretained type.
2285
2286 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2287 /// to weak/__unsafe_unretained expression.
2289
2290 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2291 /// statement as a \p Body, and it is located on the same line.
2292 ///
2293 /// This helps prevent bugs due to typos, such as:
2294 /// if (condition);
2295 /// do_stuff();
2296 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2297 unsigned DiagID);
2298
2299 /// Warn if a for/while loop statement \p S, which is followed by
2300 /// \p PossibleBody, has a suspicious null statement as a body.
2301 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2302
2303 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2304 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2305 SourceLocation OpLoc);
2306
2307 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
2315
2316 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2318 const TypeSourceInfo *Derived);
2319
2320 /// CheckFunctionCall - Check a direct function call for various correctness
2321 /// and safety properties not strictly enforced by the C type system.
2322 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2323 const FunctionProtoType *Proto);
2324
2325 /// \param FPOnly restricts the arguments to floating-point types.
2326 bool BuiltinVectorMath(CallExpr *TheCall, QualType &Res, bool FPOnly = false);
2327 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2328
2329 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2330 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2331
2332 /// Handles the checks for format strings, non-POD arguments to vararg
2333 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2334 /// attributes and AArch64 SME attributes.
2335 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2336 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2337 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2338 VariadicCallType CallType);
2339
2340 /// \brief Enforce the bounds of a TCB
2341 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2342 /// directly calls other functions in the same TCB as marked by the
2343 /// enforce_tcb and enforce_tcb_leaf attributes.
2344 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2345 const NamedDecl *Callee);
2346
2347 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2348
2349 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2350 /// TheCall is a constant expression.
2351 bool BuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result);
2352
2353 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2354 /// TheCall is a constant expression in the range [Low, High].
2355 bool BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High,
2356 bool RangeIsError = true);
2357
2358 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2359 /// TheCall is a constant expression is a multiple of Num..
2360 bool BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
2361 unsigned Multiple);
2362
2363 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2364 /// constant expression representing a power of 2.
2365 bool BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
2366
2367 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2368 /// a constant expression representing an arbitrary byte value shifted left by
2369 /// a multiple of 8 bits.
2370 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
2371 unsigned ArgBits);
2372
2373 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2374 /// TheCall is a constant expression representing either a shifted byte value,
2375 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2376 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2377 /// Arm MVE intrinsics.
2378 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
2379 unsigned ArgBits);
2380
2381 /// Checks that a call expression's argument count is at least the desired
2382 /// number. This is useful when doing custom type-checking on a variadic
2383 /// function. Returns true on error.
2384 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2385
2386 /// Checks that a call expression's argument count is at most the desired
2387 /// number. This is useful when doing custom type-checking on a variadic
2388 /// function. Returns true on error.
2389 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2390
2391 /// Checks that a call expression's argument count is in the desired range.
2392 /// This is useful when doing custom type-checking on a variadic function.
2393 /// Returns true on error.
2394 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2395 unsigned MaxArgCount);
2396
2397 /// Checks that a call expression's argument count is the desired number.
2398 /// This is useful when doing custom type-checking. Returns true on error.
2399 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2400
2401 /// Returns true if the argument consists of one contiguous run of 1s with any
2402 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2403 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2404 /// since all 1s are not contiguous.
2405 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2406
2408 bool *ICContext = nullptr,
2409 bool IsListInit = false);
2410
2412 bool CheckForFloatArgs = true);
2414
2415private:
2416 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2417 const ArraySubscriptExpr *ASE = nullptr,
2418 bool AllowOnePastEnd = true, bool IndexNegated = false);
2419 void CheckArrayAccess(const Expr *E);
2420
2421 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2422 const FunctionProtoType *Proto);
2423
2424 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2425 /// such as function pointers returned from functions.
2426 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2427
2428 /// CheckConstructorCall - Check a constructor call for correctness and safety
2429 /// properties not enforced by the C type system.
2430 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2432 const FunctionProtoType *Proto, SourceLocation Loc);
2433
2434 /// Warn if a pointer or reference argument passed to a function points to an
2435 /// object that is less aligned than the parameter. This can happen when
2436 /// creating a typedef with a lower alignment than the original type and then
2437 /// calling functions defined in terms of the original type.
2438 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2439 StringRef ParamName, QualType ArgTy, QualType ParamTy);
2440
2441 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2442
2443 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2444 CallExpr *TheCall);
2445
2446 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2447 CallExpr *TheCall);
2448
2449 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2450
2451 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2452 /// for validity. Emit an error and return true on failure; return false
2453 /// on success.
2454 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2455 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2456
2457 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2458 /// friends. This is declared to take (...), so we have to check everything.
2459 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2460
2461 /// BuiltinSemaBuiltinFPClassification - Handle functions like
2462 /// __builtin_isnan and friends. This is declared to take (...), so we have
2463 /// to check everything.
2464 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
2465 unsigned BuiltinID);
2466
2467 /// Perform semantic analysis for a call to __builtin_complex.
2468 bool BuiltinComplex(CallExpr *TheCall);
2469 bool BuiltinOSLogFormat(CallExpr *TheCall);
2470
2471 /// BuiltinPrefetch - Handle __builtin_prefetch.
2472 /// This is declared to take (const void*, ...) and can take two
2473 /// optional constant int args.
2474 bool BuiltinPrefetch(CallExpr *TheCall);
2475
2476 /// Handle __builtin_alloca_with_align. This is declared
2477 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
2478 /// than 8.
2479 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
2480
2481 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
2482 bool BuiltinArithmeticFence(CallExpr *TheCall);
2483
2484 /// BuiltinAssume - Handle __assume (MS Extension).
2485 /// __assume does not evaluate its arguments, and should warn if its argument
2486 /// has side effects.
2487 bool BuiltinAssume(CallExpr *TheCall);
2488
2489 /// Handle __builtin_assume_aligned. This is declared
2490 /// as (const void*, size_t, ...) and can take one optional constant int arg.
2491 bool BuiltinAssumeAligned(CallExpr *TheCall);
2492
2493 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
2494 /// This checks that the target supports __builtin_longjmp and
2495 /// that val is a constant 1.
2496 bool BuiltinLongjmp(CallExpr *TheCall);
2497
2498 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2499 /// This checks that the target supports __builtin_setjmp.
2500 bool BuiltinSetjmp(CallExpr *TheCall);
2501
2502 /// We have a call to a function like __sync_fetch_and_add, which is an
2503 /// overloaded function based on the pointer type of its first argument.
2504 /// The main BuildCallExpr routines have already promoted the types of
2505 /// arguments because all of these calls are prototyped as void(...).
2506 ///
2507 /// This function goes through and does final semantic checking for these
2508 /// builtins, as well as generating any warnings.
2509 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
2510
2511 /// BuiltinNontemporalOverloaded - We have a call to
2512 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2513 /// overloaded function based on the pointer type of its last argument.
2514 ///
2515 /// This function goes through and does final semantic checking for these
2516 /// builtins.
2517 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
2518 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
2520
2521 /// \param FPOnly restricts the arguments to floating-point types.
2522 bool BuiltinElementwiseMath(CallExpr *TheCall, bool FPOnly = false);
2523 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
2524
2525 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
2526
2527 enum BuiltinCountedByRefKind {
2528 AssignmentKind,
2529 InitializerKind,
2530 FunctionArgKind,
2531 ReturnArgKind,
2532 ArraySubscriptKind,
2533 BinaryExprKind,
2534 };
2535
2536 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
2537 BuiltinCountedByRefKind K);
2538 bool BuiltinCountedByRef(CallExpr *TheCall);
2539
2540 // Matrix builtin handling.
2541 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
2542 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
2543 ExprResult CallResult);
2544 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
2545 ExprResult CallResult);
2546
2547 /// CheckFormatArguments - Check calls to printf and scanf (and similar
2548 /// functions) for correct use of format strings.
2549 /// Returns true if a format string has been fully checked.
2550 bool CheckFormatArguments(const FormatAttr *Format,
2551 ArrayRef<const Expr *> Args, bool IsCXXMember,
2552 VariadicCallType CallType, SourceLocation Loc,
2553 SourceRange Range,
2554 llvm::SmallBitVector &CheckedVarArgs);
2555 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
2556 FormatArgumentPassingKind FAPK, unsigned format_idx,
2557 unsigned firstDataArg, FormatStringType Type,
2558 VariadicCallType CallType, SourceLocation Loc,
2559 SourceRange range,
2560 llvm::SmallBitVector &CheckedVarArgs);
2561
2562 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
2563
2564 /// Warn when using the wrong abs() function.
2565 void CheckAbsoluteValueFunction(const CallExpr *Call,
2566 const FunctionDecl *FDecl);
2567
2568 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
2569
2570 /// Check for dangerous or invalid arguments to memset().
2571 ///
2572 /// This issues warnings on known problematic, dangerous or unspecified
2573 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2574 /// function calls.
2575 ///
2576 /// \param Call The call expression to diagnose.
2577 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
2578 IdentifierInfo *FnName);
2579
2580 // Warn if the user has made the 'size' argument to strlcpy or strlcat
2581 // be the size of the source, instead of the destination.
2582 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
2583
2584 // Warn on anti-patterns as the 'size' argument to strncat.
2585 // The correct size argument should look like following:
2586 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
2587 void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName);
2588
2589 /// Alerts the user that they are attempting to free a non-malloc'd object.
2590 void CheckFreeArguments(const CallExpr *E);
2591
2592 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
2593 SourceLocation ReturnLoc, bool isObjCMethod = false,
2594 const AttrVec *Attrs = nullptr,
2595 const FunctionDecl *FD = nullptr);
2596
2597 /// Diagnoses "dangerous" implicit conversions within the given
2598 /// expression (which is a full expression). Implements -Wconversion
2599 /// and -Wsign-compare.
2600 ///
2601 /// \param CC the "context" location of the implicit conversion, i.e.
2602 /// the most location of the syntactic entity requiring the implicit
2603 /// conversion
2604 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
2605
2606 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
2607 /// Input argument E is a logical expression.
2608 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
2609
2610 /// Diagnose when expression is an integer constant expression and its
2611 /// evaluation results in integer overflow
2612 void CheckForIntOverflow(const Expr *E);
2613 void CheckUnsequencedOperations(const Expr *E);
2614
2615 /// Perform semantic checks on a completed expression. This will either
2616 /// be a full-expression or a default argument expression.
2617 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
2618 bool IsConstexpr = false);
2619
2620 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
2621 Expr *Init);
2622
2623 /// A map from magic value to type information.
2624 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
2625 TypeTagForDatatypeMagicValues;
2626
2627 /// Peform checks on a call of a function with argument_with_type_tag
2628 /// or pointer_with_type_tag attributes.
2629 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
2630 const ArrayRef<const Expr *> ExprArgs,
2631 SourceLocation CallSiteLoc);
2632
2633 /// Check if we are taking the address of a packed field
2634 /// as this may be a problem if the pointer value is dereferenced.
2635 void CheckAddressOfPackedMember(Expr *rhs);
2636
2637 /// Helper class that collects misaligned member designations and
2638 /// their location info for delayed diagnostics.
2639 struct MisalignedMember {
2640 Expr *E;
2641 RecordDecl *RD;
2642 ValueDecl *MD;
2643 CharUnits Alignment;
2644
2645 MisalignedMember() : E(), RD(), MD() {}
2646 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
2647 CharUnits Alignment)
2648 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
2649 explicit MisalignedMember(Expr *E)
2650 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
2651
2652 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
2653 };
2654 /// Small set of gathered accesses to potentially misaligned members
2655 /// due to the packed attribute.
2656 SmallVector<MisalignedMember, 4> MisalignedMembers;
2657
2658 /// Adds an expression to the set of gathered misaligned members.
2659 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
2660 CharUnits Alignment);
2661 ///@}
2662
2663 //
2664 //
2665 // -------------------------------------------------------------------------
2666 //
2667 //
2668
2669 /// \name C++ Coroutines
2670 /// Implementations are in SemaCoroutine.cpp
2671 ///@{
2672
2673public:
2674 /// The C++ "std::coroutine_traits" template, which is defined in
2675 /// <coroutine_traits>
2677
2679 StringRef Keyword);
2683
2686 UnresolvedLookupExpr *Lookup);
2688 Expr *Awaiter, bool IsImplicit = false);
2690 UnresolvedLookupExpr *Lookup);
2693 bool IsImplicit = false);
2698
2699 // As a clang extension, enforces that a non-coroutine function must be marked
2700 // with [[clang::coro_wrapper]] if it returns a type marked with
2701 // [[clang::coro_return_type]].
2702 // Expects that FD is not a coroutine.
2704 /// Lookup 'coroutine_traits' in std namespace and std::experimental
2705 /// namespace. The namespace found is recorded in Namespace.
2707 SourceLocation FuncLoc);
2708 /// Check that the expression co_await promise.final_suspend() shall not be
2709 /// potentially-throwing.
2710 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
2711
2712 ///@}
2713
2714 //
2715 //
2716 // -------------------------------------------------------------------------
2717 //
2718 //
2719
2720 /// \name C++ Scope Specifiers
2721 /// Implementations are in SemaCXXScopeSpec.cpp
2722 ///@{
2723
2724public:
2725 // Marks SS invalid if it represents an incomplete type.
2727 // Complete an enum decl, maybe without a scope spec.
2729 CXXScopeSpec *SS = nullptr);
2730
2731 /// Compute the DeclContext that is associated with the given type.
2732 ///
2733 /// \param T the type for which we are attempting to find a DeclContext.
2734 ///
2735 /// \returns the declaration context represented by the type T,
2736 /// or NULL if the declaration context cannot be computed (e.g., because it is
2737 /// dependent and not the current instantiation).
2739
2740 /// Compute the DeclContext that is associated with the given
2741 /// scope specifier.
2742 ///
2743 /// \param SS the C++ scope specifier as it appears in the source
2744 ///
2745 /// \param EnteringContext when true, we will be entering the context of
2746 /// this scope specifier, so we can retrieve the declaration context of a
2747 /// class template or class template partial specialization even if it is
2748 /// not the current instantiation.
2749 ///
2750 /// \returns the declaration context represented by the scope specifier @p SS,
2751 /// or NULL if the declaration context cannot be computed (e.g., because it is
2752 /// dependent and not the current instantiation).
2754 bool EnteringContext = false);
2756
2757 /// If the given nested name specifier refers to the current
2758 /// instantiation, return the declaration that corresponds to that
2759 /// current instantiation (C++0x [temp.dep.type]p1).
2760 ///
2761 /// \param NNS a dependent nested name specifier.
2763
2764 /// The parser has parsed a global nested-name-specifier '::'.
2765 ///
2766 /// \param CCLoc The location of the '::'.
2767 ///
2768 /// \param SS The nested-name-specifier, which will be updated in-place
2769 /// to reflect the parsed nested-name-specifier.
2770 ///
2771 /// \returns true if an error occurred, false otherwise.
2773
2774 /// The parser has parsed a '__super' nested-name-specifier.
2775 ///
2776 /// \param SuperLoc The location of the '__super' keyword.
2777 ///
2778 /// \param ColonColonLoc The location of the '::'.
2779 ///
2780 /// \param SS The nested-name-specifier, which will be updated in-place
2781 /// to reflect the parsed nested-name-specifier.
2782 ///
2783 /// \returns true if an error occurred, false otherwise.
2785 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
2786
2787 /// Determines whether the given declaration is an valid acceptable
2788 /// result for name lookup of a nested-name-specifier.
2789 /// \param SD Declaration checked for nested-name-specifier.
2790 /// \param IsExtension If not null and the declaration is accepted as an
2791 /// extension, the pointed variable is assigned true.
2793 bool *CanCorrect = nullptr);
2794
2795 /// If the given nested-name-specifier begins with a bare identifier
2796 /// (e.g., Base::), perform name lookup for that identifier as a
2797 /// nested-name-specifier within the given scope, and return the result of
2798 /// that name lookup.
2800
2801 /// Keeps information about an identifier in a nested-name-spec.
2802 ///
2804 /// The type of the object, if we're parsing nested-name-specifier in
2805 /// a member access expression.
2807
2808 /// The identifier preceding the '::'.
2810
2811 /// The location of the identifier.
2813
2814 /// The location of the '::'.
2816
2817 /// Creates info object for the most typical case.
2819 SourceLocation ColonColonLoc,
2820 ParsedType ObjectType = ParsedType())
2821 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
2822 CCLoc(ColonColonLoc) {}
2823
2825 SourceLocation ColonColonLoc, QualType ObjectType)
2826 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
2827 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
2828 };
2829
2830 /// Build a new nested-name-specifier for "identifier::", as described
2831 /// by ActOnCXXNestedNameSpecifier.
2832 ///
2833 /// \param S Scope in which the nested-name-specifier occurs.
2834 /// \param IdInfo Parser information about an identifier in the
2835 /// nested-name-spec.
2836 /// \param EnteringContext If true, enter the context specified by the
2837 /// nested-name-specifier.
2838 /// \param SS Optional nested name specifier preceding the identifier.
2839 /// \param ScopeLookupResult Provides the result of name lookup within the
2840 /// scope of the nested-name-specifier that was computed at template
2841 /// definition time.
2842 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
2843 /// error recovery and what kind of recovery is performed.
2844 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
2845 /// are allowed. The bool value pointed by this parameter is set to
2846 /// 'true' if the identifier is treated as if it was followed by ':',
2847 /// not '::'.
2848 /// \param OnlyNamespace If true, only considers namespaces in lookup.
2849 ///
2850 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
2851 /// that it contains an extra parameter \p ScopeLookupResult, which provides
2852 /// the result of name lookup within the scope of the nested-name-specifier
2853 /// that was computed at template definition time.
2854 ///
2855 /// If ErrorRecoveryLookup is true, then this call is used to improve error
2856 /// recovery. This means that it should not emit diagnostics, it should
2857 /// just return true on failure. It also means it should only return a valid
2858 /// scope if it *knows* that the result is correct. It should not return in a
2859 /// dependent context, for example. Nor will it extend \p SS with the scope
2860 /// specifier.
2861 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
2862 bool EnteringContext, CXXScopeSpec &SS,
2863 NamedDecl *ScopeLookupResult,
2864 bool ErrorRecoveryLookup,
2865 bool *IsCorrectedToColon = nullptr,
2866 bool OnlyNamespace = false);
2867
2868 /// The parser has parsed a nested-name-specifier 'identifier::'.
2869 ///
2870 /// \param S The scope in which this nested-name-specifier occurs.
2871 ///
2872 /// \param IdInfo Parser information about an identifier in the
2873 /// nested-name-spec.
2874 ///
2875 /// \param EnteringContext Whether we're entering the context nominated by
2876 /// this nested-name-specifier.
2877 ///
2878 /// \param SS The nested-name-specifier, which is both an input
2879 /// parameter (the nested-name-specifier before this type) and an
2880 /// output parameter (containing the full nested-name-specifier,
2881 /// including this new type).
2882 ///
2883 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
2884 /// are allowed. The bool value pointed by this parameter is set to 'true'
2885 /// if the identifier is treated as if it was followed by ':', not '::'.
2886 ///
2887 /// \param OnlyNamespace If true, only considers namespaces in lookup.
2888 ///
2889 /// \returns true if an error occurred, false otherwise.
2890 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
2891 bool EnteringContext, CXXScopeSpec &SS,
2892 bool *IsCorrectedToColon = nullptr,
2893 bool OnlyNamespace = false);
2894
2895 /// The parser has parsed a nested-name-specifier
2896 /// 'template[opt] template-name < template-args >::'.
2897 ///
2898 /// \param S The scope in which this nested-name-specifier occurs.
2899 ///
2900 /// \param SS The nested-name-specifier, which is both an input
2901 /// parameter (the nested-name-specifier before this type) and an
2902 /// output parameter (containing the full nested-name-specifier,
2903 /// including this new type).
2904 ///
2905 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
2906 /// \param TemplateName the template name.
2907 /// \param TemplateNameLoc The location of the template name.
2908 /// \param LAngleLoc The location of the opening angle bracket ('<').
2909 /// \param TemplateArgs The template arguments.
2910 /// \param RAngleLoc The location of the closing angle bracket ('>').
2911 /// \param CCLoc The location of the '::'.
2912 ///
2913 /// \param EnteringContext Whether we're entering the context of the
2914 /// nested-name-specifier.
2915 ///
2916 ///
2917 /// \returns true if an error occurred, false otherwise.
2919 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2920 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
2921 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
2922 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
2923
2925 SourceLocation ColonColonLoc);
2926
2928 const DeclSpec &DS,
2929 SourceLocation ColonColonLoc,
2930 QualType Type);
2931
2932 /// IsInvalidUnlessNestedName - This method is used for error recovery
2933 /// purposes to determine whether the specified identifier is only valid as
2934 /// a nested name specifier, for example a namespace name. It is
2935 /// conservatively correct to always return false from this method.
2936 ///
2937 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
2939 NestedNameSpecInfo &IdInfo,
2940 bool EnteringContext);
2941
2942 /// Given a C++ nested-name-specifier, produce an annotation value
2943 /// that the parser can use later to reconstruct the given
2944 /// nested-name-specifier.
2945 ///
2946 /// \param SS A nested-name-specifier.
2947 ///
2948 /// \returns A pointer containing all of the information in the
2949 /// nested-name-specifier \p SS.
2951
2952 /// Given an annotation pointer for a nested-name-specifier, restore
2953 /// the nested-name-specifier structure.
2954 ///
2955 /// \param Annotation The annotation pointer, produced by
2956 /// \c SaveNestedNameSpecifierAnnotation().
2957 ///
2958 /// \param AnnotationRange The source range corresponding to the annotation.
2959 ///
2960 /// \param SS The nested-name-specifier that will be updated with the contents
2961 /// of the annotation pointer.
2962 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
2963 SourceRange AnnotationRange,
2964 CXXScopeSpec &SS);
2965
2966 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
2967
2968 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
2969 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
2970 /// After this method is called, according to [C++ 3.4.3p3], names should be
2971 /// looked up in the declarator-id's scope, until the declarator is parsed and
2972 /// ActOnCXXExitDeclaratorScope is called.
2973 /// The 'SS' should be a non-empty valid CXXScopeSpec.
2975
2976 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
2977 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
2978 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
2979 /// Used to indicate that names should revert to being looked up in the
2980 /// defining scope.
2982
2983 ///@}
2984
2985 //
2986 //
2987 // -------------------------------------------------------------------------
2988 //
2989 //
2990
2991 /// \name Declarations
2992 /// Implementations are in SemaDecl.cpp
2993 ///@{
2994
2995public:
2997
2998 /// The index of the first InventedParameterInfo that refers to the current
2999 /// context.
3001
3002 /// A RAII object to temporarily push a declaration context.
3004 private:
3005 Sema &S;
3006 DeclContext *SavedContext;
3007 ProcessingContextState SavedContextState;
3008 QualType SavedCXXThisTypeOverride;
3009 unsigned SavedFunctionScopesStart;
3010 unsigned SavedInventedParameterInfosStart;
3011
3012 public:
3013 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3014 : S(S), SavedContext(S.CurContext),
3015 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3016 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3017 SavedFunctionScopesStart(S.FunctionScopesStart),
3018 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3019 assert(ContextToPush && "pushing null context");
3020 S.CurContext = ContextToPush;
3021 if (NewThisContext)
3022 S.CXXThisTypeOverride = QualType();
3023 // Any saved FunctionScopes do not refer to this context.
3024 S.FunctionScopesStart = S.FunctionScopes.size();
3025 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3026 }
3027
3028 void pop() {
3029 if (!SavedContext)
3030 return;
3031 S.CurContext = SavedContext;
3032 S.DelayedDiagnostics.popUndelayed(SavedContextState);
3033 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3034 S.FunctionScopesStart = SavedFunctionScopesStart;
3035 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3036 SavedContext = nullptr;
3037 }
3038
3039 ~ContextRAII() { pop(); }
3040 };
3041
3042 void DiagnoseInvalidJumps(Stmt *Body);
3043
3044 /// The function definitions which were renamed as part of typo-correction
3045 /// to match their respective declarations. We want to keep track of them
3046 /// to ensure that we don't emit a "redefinition" error if we encounter a
3047 /// correctly named definition after the renamed definition.
3049
3050 /// A cache of the flags available in enumerations with the flag_bits
3051 /// attribute.
3052 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3053
3054 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3055 /// declared. Rare. May alias another identifier, declared or undeclared.
3056 ///
3057 /// For aliases, the target identifier is used as a key for eventual
3058 /// processing when the target is declared. For the single-identifier form,
3059 /// the sole identifier is used as the key. Each entry is a `SetVector`
3060 /// (ordered by parse order) of aliases (identified by the alias name) in case
3061 /// of multiple aliases to the same undeclared identifier.
3062 llvm::MapVector<
3064 llvm::SetVector<
3066 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3068
3069 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3070 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3071 /// to define functions that occur in multiple standards to call the version
3072 /// in the currently selected standard.
3073 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *> ExtnameUndeclaredIdentifiers;
3074
3075 /// Set containing all typedefs that are likely unused.
3078
3082
3083 /// The set of file scoped decls seen so far that have not been used
3084 /// and must warn if not used. Only contains the first declaration.
3086
3090
3091 /// All the tentative definitions encountered in the TU.
3093
3094 /// All the external declarations encoutered and used in the TU.
3096
3097 /// Generally null except when we temporarily switch decl contexts,
3098 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3100
3101 /// Is the module scope we are in a C++ Header Unit?
3103 return ModuleScopes.empty() ? false
3104 : ModuleScopes.back().Module->isHeaderUnit();
3105 }
3106
3107 /// Get the module owning an entity.
3108 Module *getOwningModule(const Decl *Entity) {
3109 return Entity->getOwningModule();
3110 }
3111
3112 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3113
3114 /// If the identifier refers to a type name within this scope,
3115 /// return the declaration of that type.
3116 ///
3117 /// This routine performs ordinary name lookup of the identifier II
3118 /// within the given scope, with optional C++ scope specifier SS, to
3119 /// determine whether the name refers to a type. If so, returns an
3120 /// opaque pointer (actually a QualType) corresponding to that
3121 /// type. Otherwise, returns NULL.
3123 Scope *S, CXXScopeSpec *SS = nullptr,
3124 bool isClassName = false, bool HasTrailingDot = false,
3125 ParsedType ObjectType = nullptr,
3126 bool IsCtorOrDtorName = false,
3127 bool WantNontrivialTypeSourceInfo = false,
3128 bool IsClassTemplateDeductionContext = true,
3129 ImplicitTypenameContext AllowImplicitTypename =
3131 IdentifierInfo **CorrectedII = nullptr);
3132
3133 /// isTagName() - This method is called *for error recovery purposes only*
3134 /// to determine if the specified name is a valid tag name ("struct foo"). If
3135 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3136 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3137 /// diagnose cases in C where the user forgot to specify the tag.
3139
3140 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3141 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3142 /// then downgrade the missing typename error to a warning.
3143 /// This is needed for MSVC compatibility; Example:
3144 /// @code
3145 /// template<class T> class A {
3146 /// public:
3147 /// typedef int TYPE;
3148 /// };
3149 /// template<class T> class B : public A<T> {
3150 /// public:
3151 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3152 /// };
3153 /// @endcode
3154 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3156 Scope *S, CXXScopeSpec *SS,
3157 ParsedType &SuggestedType,
3158 bool IsTemplateName = false);
3159
3160 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3161 /// type name has failed in a dependent context. In these situations, we
3162 /// automatically form a DependentTypeName that will retry lookup in a related
3163 /// scope during instantiation.
3165 SourceLocation NameLoc,
3166 bool IsTemplateTypeArg);
3167
3168 /// Describes the result of the name lookup and resolution performed
3169 /// by \c ClassifyName().
3171 /// This name is not a type or template in this context, but might be
3172 /// something else.
3174 /// Classification failed; an error has been produced.
3176 /// The name has been typo-corrected to a keyword.
3178 /// The name was classified as a type.
3180 /// The name was classified as a specific non-type, non-template
3181 /// declaration. ActOnNameClassifiedAsNonType should be called to
3182 /// convert the declaration to an expression.
3184 /// The name was classified as an ADL-only function name.
3185 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
3186 /// result to an expression.
3188 /// The name denotes a member of a dependent type that could not be
3189 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
3190 /// convert the result to an expression.
3192 /// The name was classified as an overload set, and an expression
3193 /// representing that overload set has been formed.
3194 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
3195 /// expression referencing the overload set.
3197 /// The name was classified as a template whose specializations are types.
3199 /// The name was classified as a variable template name.
3201 /// The name was classified as a function template name.
3203 /// The name was classified as an ADL-only function template name.
3205 /// The name was classified as a concept name.
3207 };
3208
3211 union {
3216 };
3217
3219
3220 public:
3222
3223 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
3224
3225 static NameClassification Error() { return NameClassification(NC_Error); }
3226
3228 return NameClassification(NC_Unknown);
3229 }
3230
3232 NameClassification Result(NC_OverloadSet);
3233 Result.Expr = E;
3234 return Result;
3235 }
3236
3238 NameClassification Result(NC_NonType);
3239 Result.NonTypeDecl = D;
3240 return Result;
3241 }
3242
3244 return NameClassification(NC_UndeclaredNonType);
3245 }
3246
3248 return NameClassification(NC_DependentNonType);
3249 }
3250
3252 NameClassification Result(NC_TypeTemplate);
3253 Result.Template = Name;
3254 return Result;
3255 }
3256
3258 NameClassification Result(NC_VarTemplate);
3259 Result.Template = Name;
3260 return Result;
3261 }
3262
3264 NameClassification Result(NC_FunctionTemplate);
3265 Result.Template = Name;
3266 return Result;
3267 }
3268
3270 NameClassification Result(NC_Concept);
3271 Result.Template = Name;
3272 return Result;
3273 }
3274
3276 NameClassification Result(NC_UndeclaredTemplate);
3277 Result.Template = Name;
3278 return Result;
3279 }
3280
3282
3284 assert(Kind == NC_OverloadSet);
3285 return Expr;
3286 }
3287
3289 assert(Kind == NC_Type);
3290 return Type;
3291 }
3292
3294 assert(Kind == NC_NonType);
3295 return NonTypeDecl;
3296 }
3297
3299 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
3300 Kind == NC_VarTemplate || Kind == NC_Concept ||
3301 Kind == NC_UndeclaredTemplate);
3302 return Template;
3303 }
3304
3306 switch (Kind) {
3307 case NC_TypeTemplate:
3308 return TNK_Type_template;
3309 case NC_FunctionTemplate:
3310 return TNK_Function_template;
3311 case NC_VarTemplate:
3312 return TNK_Var_template;
3313 case NC_Concept:
3314 return TNK_Concept_template;
3315 case NC_UndeclaredTemplate:
3317 default:
3318 llvm_unreachable("unsupported name classification.");
3319 }
3320 }
3321 };
3322
3323 /// Perform name lookup on the given name, classifying it based on
3324 /// the results of name lookup and the following token.
3325 ///
3326 /// This routine is used by the parser to resolve identifiers and help direct
3327 /// parsing. When the identifier cannot be found, this routine will attempt
3328 /// to correct the typo and classify based on the resulting name.
3329 ///
3330 /// \param S The scope in which we're performing name lookup.
3331 ///
3332 /// \param SS The nested-name-specifier that precedes the name.
3333 ///
3334 /// \param Name The identifier. If typo correction finds an alternative name,
3335 /// this pointer parameter will be updated accordingly.
3336 ///
3337 /// \param NameLoc The location of the identifier.
3338 ///
3339 /// \param NextToken The token following the identifier. Used to help
3340 /// disambiguate the name.
3341 ///
3342 /// \param CCC The correction callback, if typo correction is desired.
3343 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3344 IdentifierInfo *&Name, SourceLocation NameLoc,
3345 const Token &NextToken,
3346 CorrectionCandidateCallback *CCC = nullptr);
3347
3348 /// Act on the result of classifying a name as an undeclared (ADL-only)
3349 /// non-type declaration.
3351 SourceLocation NameLoc);
3352 /// Act on the result of classifying a name as an undeclared member of a
3353 /// dependent base class.
3355 IdentifierInfo *Name,
3356 SourceLocation NameLoc,
3357 bool IsAddressOfOperand);
3358 /// Act on the result of classifying a name as a specific non-type
3359 /// declaration.
3362 SourceLocation NameLoc,
3363 const Token &NextToken);
3364 /// Act on the result of classifying a name as an overload set.
3366
3367 /// Describes the detailed kind of a template name. Used in diagnostics.
3374 Concept,
3376 };
3379
3380 /// Determine whether it's plausible that E was intended to be a
3381 /// template-name.
3383 if (!getLangOpts().CPlusPlus || E.isInvalid())
3384 return false;
3385 Dependent = false;
3386 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
3387 return !DRE->hasExplicitTemplateArgs();
3388 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
3389 return !ME->hasExplicitTemplateArgs();
3390 Dependent = true;
3391 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
3392 return !DSDRE->hasExplicitTemplateArgs();
3393 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
3394 return !DSME->hasExplicitTemplateArgs();
3395 // Any additional cases recognized here should also be handled by
3396 // diagnoseExprIntendedAsTemplateName.
3397 return false;
3398 }
3399
3401
3403
3405 MultiTemplateParamsArg TemplateParameterLists);
3406
3407 /// Attempt to fold a variable-sized type to a constant-sized type, returning
3408 /// true if we were successful.
3411 unsigned FailedFoldDiagID);
3412
3413 /// Register the given locally-scoped extern "C" declaration so
3414 /// that it can be found later for redeclarations. We include any extern "C"
3415 /// declaration that is not visible in the translation unit here, not just
3416 /// function-scope declarations.
3418
3419 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3420 /// If T is the name of a class, then each of the following shall have a
3421 /// name different from T:
3422 /// - every static data member of class T;
3423 /// - every member function of class T
3424 /// - every member of class T that is itself a type;
3425 /// \returns true if the declaration name violates these rules.
3427
3428 /// Diagnose a declaration whose declarator-id has the given
3429 /// nested-name-specifier.
3430 ///
3431 /// \param SS The nested-name-specifier of the declarator-id.
3432 ///
3433 /// \param DC The declaration context to which the nested-name-specifier
3434 /// resolves.
3435 ///
3436 /// \param Name The name of the entity being declared.
3437 ///
3438 /// \param Loc The location of the name of the entity being declared.
3439 ///
3440 /// \param IsMemberSpecialization Whether we are declaring a member
3441 /// specialization.
3442 ///
3443 /// \param TemplateId The template-id, if any.
3444 ///
3445 /// \returns true if we cannot safely recover from this error, false
3446 /// otherwise.
3449 TemplateIdAnnotation *TemplateId,
3450 bool IsMemberSpecialization);
3451
3453
3454 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
3455
3456 /// Diagnose function specifiers on a declaration of an identifier that
3457 /// does not identify a function.
3458 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
3459
3460 /// Return the declaration shadowed by the given typedef \p D, or null
3461 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3463 const LookupResult &R);
3464
3465 /// Return the declaration shadowed by the given variable \p D, or null
3466 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3468
3469 /// Return the declaration shadowed by the given variable \p D, or null
3470 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3472 const LookupResult &R);
3473 /// Diagnose variable or built-in function shadowing. Implements
3474 /// -Wshadow.
3475 ///
3476 /// This method is called whenever a VarDecl is added to a "useful"
3477 /// scope.
3478 ///
3479 /// \param ShadowedDecl the declaration that is shadowed by the given variable
3480 /// \param R the lookup of the name
3481 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
3482 const LookupResult &R);
3483
3484 /// Check -Wshadow without the advantage of a previous lookup.
3485 void CheckShadow(Scope *S, VarDecl *D);
3486
3487 /// Warn if 'E', which is an expression that is about to be modified, refers
3488 /// to a shadowing declaration.
3490
3491 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
3492 /// when these variables are captured by the lambda.
3494
3495 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
3496 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3497 TypedefNameDecl *NewTD);
3500 TypeSourceInfo *TInfo,
3502
3503 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3504 /// declares a typedef-name, either using the 'typedef' type specifier or via
3505 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3507 LookupResult &Previous, bool &Redeclaration);
3509 TypeSourceInfo *TInfo,
3511 MultiTemplateParamsArg TemplateParamLists,
3512 bool &AddToScope,
3514
3515 /// Perform semantic checking on a newly-created variable
3516 /// declaration.
3517 ///
3518 /// This routine performs all of the type-checking required for a
3519 /// variable declaration once it has been built. It is used both to
3520 /// check variables after they have been parsed and their declarators
3521 /// have been translated into a declaration, and to check variables
3522 /// that have been instantiated from a template.
3523 ///
3524 /// Sets NewVD->isInvalidDecl() if an error was encountered.
3525 ///
3526 /// Returns true if the variable declaration is a redeclaration.
3527 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
3528 void CheckVariableDeclarationType(VarDecl *NewVD);
3529 void CheckCompleteVariableDeclaration(VarDecl *VD);
3530
3531 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
3532 TypeSourceInfo *TInfo,
3533 LookupResult &Previous,
3534 MultiTemplateParamsArg TemplateParamLists,
3535 bool &AddToScope);
3536
3537 /// AddOverriddenMethods - See if a method overrides any in the base classes,
3538 /// and if so, check that it's a valid override and remember it.
3539 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
3540
3541 /// Perform semantic checking of a new function declaration.
3542 ///
3543 /// Performs semantic analysis of the new function declaration
3544 /// NewFD. This routine performs all semantic checking that does not
3545 /// require the actual declarator involved in the declaration, and is
3546 /// used both for the declaration of functions as they are parsed
3547 /// (called via ActOnDeclarator) and for the declaration of functions
3548 /// that have been instantiated via C++ template instantiation (called
3549 /// via InstantiateDecl).
3550 ///
3551 /// \param IsMemberSpecialization whether this new function declaration is
3552 /// a member specialization (that replaces any definition provided by the
3553 /// previous declaration).
3554 ///
3555 /// This sets NewFD->isInvalidDecl() to true if there was an error.
3556 ///
3557 /// \returns true if the function declaration is a redeclaration.
3558 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
3559 LookupResult &Previous,
3560 bool IsMemberSpecialization, bool DeclIsDefn);
3561
3562 /// Checks if the new declaration declared in dependent context must be
3563 /// put in the same redeclaration chain as the specified declaration.
3564 ///
3565 /// \param D Declaration that is checked.
3566 /// \param PrevDecl Previous declaration found with proper lookup method for
3567 /// the same declaration name.
3568 /// \returns True if D must be added to the redeclaration chain which PrevDecl
3569 /// belongs to.
3570 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
3571
3572 /// Determines if we can perform a correct type check for \p D as a
3573 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
3574 /// best-effort check.
3575 ///
3576 /// \param NewD The new declaration.
3577 /// \param OldD The old declaration.
3578 /// \param NewT The portion of the type of the new declaration to check.
3579 /// \param OldT The portion of the type of the old declaration to check.
3580 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
3581 QualType NewT, QualType OldT);
3582 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
3583 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
3584
3585 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
3586 /// containing class. Otherwise it will return implicit SectionAttr if the
3587 /// function is a definition and there is an active value on CodeSegStack
3588 /// (from the current #pragma code-seg value).
3589 ///
3590 /// \param FD Function being declared.
3591 /// \param IsDefinition Whether it is a definition or just a declaration.
3592 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
3593 /// nullptr if no attribute should be added.
3594 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
3595 bool IsDefinition);
3596
3597 /// Common checks for a parameter-declaration that should apply to both
3598 /// function parameters and non-type template parameters.
3599 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
3600
3601 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
3602 /// to introduce parameters into function prototype scope.
3603 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
3604 SourceLocation ExplicitThisLoc = {});
3605
3606 /// Synthesizes a variable for a parameter arising from a
3607 /// typedef.
3608 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
3609 QualType T);
3610 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
3611 SourceLocation NameLoc,
3612 const IdentifierInfo *Name, QualType T,
3613 TypeSourceInfo *TSInfo, StorageClass SC);
3614
3615 // Contexts where using non-trivial C union types can be disallowed. This is
3616 // passed to err_non_trivial_c_union_in_invalid_context.
3618 // Function parameter.
3620 // Function return.
3622 // Default-initialized object.
3624 // Variable with automatic storage duration.
3626 // Initializer expression that might copy from another object.
3628 // Assignment.
3630 // Compound literal.
3632 // Block capture.
3634 // lvalue-to-rvalue conversion of volatile type.
3636 };
3637
3638 /// Emit diagnostics if the initializer or any of its explicit or
3639 /// implicitly-generated subexpressions require copying or
3640 /// default-initializing a type that is or contains a C union type that is
3641 /// non-trivial to copy or default-initialize.
3643
3644 // These flags are passed to checkNonTrivialCUnion.
3649 };
3650
3651 /// Emit diagnostics if a non-trivial C union type or a struct that contains
3652 /// a non-trivial C union is used in an invalid context.
3654 NonTrivialCUnionContext UseContext,
3655 unsigned NonTrivialKind);
3656
3657 /// AddInitializerToDecl - Adds the initializer Init to the
3658 /// declaration dcl. If DirectInit is true, this is C++ direct
3659 /// initialization rather than copy initialization.
3660 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
3661 void ActOnUninitializedDecl(Decl *dcl);
3662
3663 /// ActOnInitializerError - Given that there was an error parsing an
3664 /// initializer for the given declaration, try to at least re-establish
3665 /// invariants such as whether a variable's type is either dependent or
3666 /// complete.
3667 void ActOnInitializerError(Decl *Dcl);
3668
3671 IdentifierInfo *Ident,
3672 ParsedAttributes &Attrs);
3673
3674 /// Check if VD needs to be dllexport/dllimport due to being in a
3675 /// dllexport/import function.
3678
3679 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
3680 /// any semantic actions necessary after any initializer has been attached.
3681 void FinalizeDeclaration(Decl *D);
3683 ArrayRef<Decl *> Group);
3684
3685 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
3686 /// group, performing any necessary semantic checking.
3688
3689 /// Should be called on all declarations that might have attached
3690 /// documentation comments.
3693
3694 enum class FnBodyKind {
3695 /// C++26 [dcl.fct.def.general]p1
3696 /// function-body:
3697 /// ctor-initializer[opt] compound-statement
3698 /// function-try-block
3699 Other,
3700 /// = default ;
3701 Default,
3702 /// deleted-function-body
3703 ///
3704 /// deleted-function-body:
3705 /// = delete ;
3706 /// = delete ( unevaluated-string ) ;
3707 Delete
3708 };
3709
3711 SourceLocation LocAfterDecls);
3713 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3714 SkipBodyInfo *SkipBody = nullptr);
3716 MultiTemplateParamsArg TemplateParamLists,
3717 SkipBodyInfo *SkipBody = nullptr,
3718 FnBodyKind BodyKind = FnBodyKind::Other);
3720 SkipBodyInfo *SkipBody = nullptr,
3721 FnBodyKind BodyKind = FnBodyKind::Other);
3723
3724 /// Determine whether we can delay parsing the body of a function or
3725 /// function template until it is used, assuming we don't care about emitting
3726 /// code for that function.
3727 ///
3728 /// This will be \c false if we may need the body of the function in the
3729 /// middle of parsing an expression (where it's impractical to switch to
3730 /// parsing a different function), for instance, if it's constexpr in C++11
3731 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3732 bool canDelayFunctionBody(const Declarator &D);
3733
3734 /// Determine whether we can skip parsing the body of a function
3735 /// definition, assuming we don't care about analyzing its body or emitting
3736 /// code for that function.
3737 ///
3738 /// This will be \c false only if we may need the body of the function in
3739 /// order to parse the rest of the program (for instance, if it is
3740 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3741 bool canSkipFunctionBody(Decl *D);
3742
3743 /// Given the set of return statements within a function body,
3744 /// compute the variables that are subject to the named return value
3745 /// optimization.
3746 ///
3747 /// Each of the variables that is subject to the named return value
3748 /// optimization will be marked as NRVO variables in the AST, and any
3749 /// return statement that has a marked NRVO variable as its NRVO candidate can
3750 /// use the named return value optimization.
3751 ///
3752 /// This function applies a very simplistic algorithm for NRVO: if every
3753 /// return statement in the scope of a variable has the same NRVO candidate,
3754 /// that candidate is an NRVO variable.
3757 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3760
3761 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3762 /// attribute for which parsing is delayed.
3764
3765 /// Diagnose any unused parameters in the given sequence of
3766 /// ParmVarDecl pointers.
3768
3769 /// Diagnose whether the size of parameters or return value of a
3770 /// function or obj-c method definition is pass-by-value and larger than a
3771 /// specified threshold.
3772 void
3774 QualType ReturnTy, NamedDecl *D);
3775
3777 SourceLocation RParenLoc);
3778
3781
3783
3784 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3785 /// no declarator (e.g. "struct foo;") is parsed.
3787 const ParsedAttributesView &DeclAttrs,
3788 RecordDecl *&AnonRecord);
3789
3790 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3791 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3792 /// parameters to cope with template friend declarations.
3794 const ParsedAttributesView &DeclAttrs,
3795 MultiTemplateParamsArg TemplateParams,
3796 bool IsExplicitInstantiation,
3797 RecordDecl *&AnonRecord,
3798 SourceLocation EllipsisLoc = {});
3799
3800 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3801 /// anonymous structure or union. Anonymous unions are a C++ feature
3802 /// (C++ [class.union]) and a C11 feature; anonymous structures
3803 /// are a C11 feature and GNU C++ extension.
3804 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
3805 RecordDecl *Record,
3806 const PrintingPolicy &Policy);
3807
3808 /// Called once it is known whether
3809 /// a tag declaration is an anonymous union or struct.
3811
3812 /// Emit diagnostic warnings for placeholder members.
3813 /// We can only do that after the class is fully constructed,
3814 /// as anonymous union/structs can insert placeholders
3815 /// in their parent scope (which might be a Record).
3817
3818 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3819 /// Microsoft C anonymous structure.
3820 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3821 /// Example:
3822 ///
3823 /// struct A { int a; };
3824 /// struct B { struct A; int b; };
3825 ///
3826 /// void foo() {
3827 /// B var;
3828 /// var.a = 3;
3829 /// }
3830 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3831 RecordDecl *Record);
3832
3833 /// Common ways to introduce type names without a tag for use in diagnostics.
3834 /// Keep in sync with err_tag_reference_non_tag.
3845 };
3846
3847 /// Given a non-tag type declaration, returns an enum useful for indicating
3848 /// what kind of non-tag type this is.
3850
3851 /// Determine whether a tag with a given kind is acceptable
3852 /// as a redeclaration of the given tag declaration.
3853 ///
3854 /// \returns true if the new tag kind is acceptable, false otherwise.
3856 bool isDefinition, SourceLocation NewTagLoc,
3857 const IdentifierInfo *Name);
3858
3860 // Not parsing a type within __builtin_offsetof.
3862 // Parsing a type within __builtin_offsetof.
3864 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
3865 // To improve our diagnostic message.
3867 };
3868
3869 /// This is invoked when we see 'struct foo' or 'struct {'. In the
3870 /// former case, Name will be non-null. In the later case, Name will be null.
3871 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
3872 /// a reference/declaration/definition of a tag.
3873 ///
3874 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
3875 /// trailing-type-specifier) other than one in an alias-declaration.
3876 ///
3877 /// \param SkipBody If non-null, will be set to indicate if the caller should
3878 /// skip the definition of this tag and treat it as if it were a declaration.
3879 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3880 SourceLocation KWLoc, CXXScopeSpec &SS,
3881 IdentifierInfo *Name, SourceLocation NameLoc,
3883 SourceLocation ModulePrivateLoc,
3884 MultiTemplateParamsArg TemplateParameterLists,
3885 bool &OwnedDecl, bool &IsDependent,
3886 SourceLocation ScopedEnumKWLoc,
3887 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3888 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3889 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
3890
3891 /// ActOnField - Each field of a C struct/union is passed into this in order
3892 /// to create a FieldDecl object for it.
3893 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3894 Declarator &D, Expr *BitfieldWidth);
3895
3896 /// HandleField - Analyze a field of a C struct or a C++ data member.
3897 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3898 Declarator &D, Expr *BitfieldWidth,
3899 InClassInitStyle InitStyle, AccessSpecifier AS);
3900
3901 /// Build a new FieldDecl and check its well-formedness.
3902 ///
3903 /// This routine builds a new FieldDecl given the fields name, type,
3904 /// record, etc. \p PrevDecl should refer to any previous declaration
3905 /// with the same name and in the same scope as the field to be
3906 /// created.
3907 ///
3908 /// \returns a new FieldDecl.
3909 ///
3910 /// \todo The Declarator argument is a hack. It will be removed once
3913 SourceLocation Loc, bool Mutable,
3914 Expr *BitfieldWidth, InClassInitStyle InitStyle,
3916 NamedDecl *PrevDecl, Declarator *D = nullptr);
3917
3919
3920 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
3921 /// class and class extensions. For every class \@interface and class
3922 /// extension \@interface, if the last ivar is a bitfield of any type,
3923 /// then add an implicit `char :0` ivar to the end of that interface.
3924 void ActOnLastBitfield(SourceLocation DeclStart,
3925 SmallVectorImpl<Decl *> &AllIvarDecls);
3926
3927 // This is used for both record definitions and ObjC interface declarations.
3928 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3929 ArrayRef<Decl *> Fields, SourceLocation LBrac,
3930 SourceLocation RBrac, const ParsedAttributesView &AttrList);
3931
3932 /// ActOnTagStartDefinition - Invoked when we have entered the
3933 /// scope of a tag's definition (e.g., for an enumeration, class,
3934 /// struct, or union).
3936
3937 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3938 /// Differently from C++, actually parse the body and reject / error out
3939 /// in case of a structural mismatch.
3940 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3941
3943
3944 /// Invoked when we enter a tag definition that we're skipping.
3946
3947 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3948 /// C++ record definition's base-specifiers clause and are starting its
3949 /// member declarations.
3951 SourceLocation FinalLoc,
3952 bool IsFinalSpelledSealed,
3953 bool IsAbstract,
3954 SourceLocation LBraceLoc);
3955
3956 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3957 /// the definition of a tag (enumeration, class, struct, or union).
3959 SourceRange BraceRange);
3960
3962
3963 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3964 /// error parsing the definition of a tag.
3966
3968 EnumConstantDecl *LastEnumConst,
3970 Expr *val);
3971
3972 /// Check that this is a valid underlying type for an enum declaration.
3974
3975 /// Check whether this is a valid redeclaration of a previous enumeration.
3976 /// \return true if the redeclaration was invalid.
3977 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3978 QualType EnumUnderlyingTy, bool IsFixed,
3979 const EnumDecl *Prev);
3980
3981 /// Determine whether the body of an anonymous enumeration should be skipped.
3982 /// \param II The name of the first enumerator.
3984 SourceLocation IILoc);
3985
3986 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3988 const ParsedAttributesView &Attrs,
3989 SourceLocation EqualLoc, Expr *Val);
3990 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3991 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3992 const ParsedAttributesView &Attr);
3993
3994 /// Set the current declaration context until it gets popped.
3995 void PushDeclContext(Scope *S, DeclContext *DC);
3996 void PopDeclContext();
3997
3998 /// EnterDeclaratorContext - Used when we must lookup names in the context
3999 /// of a declarator's nested name specifier.
4002
4003 /// Enter a template parameter scope, after it's been associated with a
4004 /// particular DeclContext. Causes lookup within the scope to chain through
4005 /// enclosing contexts in the correct order.
4007
4008 /// Push the parameters of D, which must be a function, into scope.
4011
4012 /// Add this decl to the scope shadowed decl chains.
4013 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4014
4015 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4016 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4017 /// true if 'D' belongs to the given declaration context.
4018 ///
4019 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4020 /// enclosing namespace set of the context, rather than contained
4021 /// directly within it.
4022 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4023 bool AllowInlineNamespace = false) const;
4024
4025 /// Finds the scope corresponding to the given decl context, if it
4026 /// happens to be an enclosing scope. Otherwise return NULL.
4028
4029 /// Subroutines of ActOnDeclarator().
4031 TypeSourceInfo *TInfo);
4032 bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New);
4033
4034 /// Describes the kind of merge to perform for availability
4035 /// attributes (including "deprecated", "unavailable", and "availability").
4037 /// Don't merge availability attributes at all.
4039 /// Merge availability attributes for a redeclaration, which requires
4040 /// an exact match.
4042 /// Merge availability attributes for an override, which requires
4043 /// an exact match or a weakening of constraints.
4045 /// Merge availability attributes for an implementation of
4046 /// a protocol requirement.
4048 /// Merge availability attributes for an implementation of
4049 /// an optional protocol requirement.
4052
4053 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4054 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
4056
4057 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4058 /// same name and scope as a previous declaration 'Old'. Figure out
4059 /// how to resolve this situation, merging decls or emitting
4060 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4062 LookupResult &OldDecls);
4063
4064 /// MergeFunctionDecl - We just parsed a function 'New' from
4065 /// declarator D which has the same name and scope as a previous
4066 /// declaration 'Old'. Figure out how to resolve this situation,
4067 /// merging decls or emitting diagnostics as appropriate.
4068 ///
4069 /// In C++, New and Old must be declarations that are not
4070 /// overloaded. Use IsOverload to determine whether New and Old are
4071 /// overloaded, and to select the Old declaration that New should be
4072 /// merged with.
4073 ///
4074 /// Returns true if there was an error, false otherwise.
4075 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
4076 bool MergeTypeWithOld, bool NewDeclIsDefn);
4077
4078 /// Completes the merge of two function declarations that are
4079 /// known to be compatible.
4080 ///
4081 /// This routine handles the merging of attributes and other
4082 /// properties of function declarations from the old declaration to
4083 /// the new declaration, once we know that New is in fact a
4084 /// redeclaration of Old.
4085 ///
4086 /// \returns false
4088 Scope *S, bool MergeTypeWithOld);
4090
4091 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4092 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4093 /// situation, merging decls or emitting diagnostics as appropriate.
4094 ///
4095 /// Tentative definition rules (C99 6.9.2p2) are checked by
4096 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4097 /// definitions here, since the initializer hasn't been attached.
4099
4100 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4101 /// scope as a previous declaration 'Old'. Figure out how to merge their
4102 /// types, emitting diagnostics as appropriate.
4103 ///
4104 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4105 /// back to here in AddInitializerToDecl. We can't check them before the
4106 /// initializer is attached.
4107 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4108
4109 /// We've just determined that \p Old and \p New both appear to be definitions
4110 /// of the same variable. Either diagnose or fix the problem.
4111 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4112 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
4113
4114 /// Filters out lookup results that don't fall within the given scope
4115 /// as determined by isDeclInScope.
4117 bool ConsiderLinkage, bool AllowInlineNamespace);
4118
4119 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4120 /// have compatible owning modules.
4122
4123 /// [module.interface]p6:
4124 /// A redeclaration of an entity X is implicitly exported if X was introduced
4125 /// by an exported declaration; otherwise it shall not be exported.
4127
4128 /// A wrapper function for checking the semantic restrictions of
4129 /// a redeclaration within a module.
4131
4132 /// Check the redefinition in C++20 Modules.
4133 ///
4134 /// [basic.def.odr]p14:
4135 /// For any definable item D with definitions in multiple translation units,
4136 /// - if D is a non-inline non-templated function or variable, or
4137 /// - if the definitions in different translation units do not satisfy the
4138 /// following requirements,
4139 /// the program is ill-formed; a diagnostic is required only if the
4140 /// definable item is attached to a named module and a prior definition is
4141 /// reachable at the point where a later definition occurs.
4142 /// - Each such definition shall not be attached to a named module
4143 /// ([module.unit]).
4144 /// - Each such definition shall consist of the same sequence of tokens, ...
4145 /// ...
4146 ///
4147 /// Return true if the redefinition is not allowed. Return false otherwise.
4148 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4149
4151
4152 /// If it's a file scoped decl that must warn if not used, keep track
4153 /// of it.
4155
4156 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4158
4161 DiagReceiverTy DiagReceiver);
4162 void DiagnoseUnusedDecl(const NamedDecl *ND);
4163
4164 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4165 /// unless they are marked attr(unused).
4166 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4167
4168 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4169 /// variable.
4170 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4171
4172 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4173 /// from S, where a non-field would be declared. This routine copes
4174 /// with the difference between C and C++ scoping rules in structs and
4175 /// unions. For example, the following code is well-formed in C but
4176 /// ill-formed in C++:
4177 /// @code
4178 /// struct S6 {
4179 /// enum { BAR } e;
4180 /// };
4181 ///
4182 /// void test_S6() {
4183 /// struct S6 a;
4184 /// a.e = BAR;
4185 /// }
4186 /// @endcode
4187 /// For the declaration of BAR, this routine will return a different
4188 /// scope. The scope S will be the scope of the unnamed enumeration
4189 /// within S6. In C++, this routine will return the scope associated
4190 /// with S6, because the enumeration's scope is a transparent
4191 /// context but structures can contain non-field names. In C, this
4192 /// routine will return the translation unit scope, since the
4193 /// enumeration's scope is a transparent context and structures cannot
4194 /// contain non-field names.
4196
4199
4200 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4201 /// file scope. lazily create a decl for it. ForRedeclaration is true
4202 /// if we're creating this built-in in anticipation of redeclaring the
4203 /// built-in.
4205 bool ForRedeclaration, SourceLocation Loc);
4206
4207 /// Get the outermost AttributedType node that sets a calling convention.
4208 /// Valid types should not have multiple attributes with different CCs.
4210
4211 /// GetNameForDeclarator - Determine the full declaration name for the
4212 /// given Declarator.
4214
4215 /// Retrieves the declaration name from a parsed unqualified-id.
4217
4218 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4219 /// we are currently parsing the initializer.
4221
4222 /// Look for a locally scoped extern "C" declaration by the given name.
4224
4226
4227 /// Adjust the \c DeclContext for a function or variable that might be a
4228 /// function-local external declaration.
4230
4232
4233 /// Checks if the variant/multiversion functions are compatible.
4235 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4236 const PartialDiagnostic &NoProtoDiagID,
4237 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4238 const PartialDiagnosticAt &NoSupportDiagIDAt,
4239 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4240 bool ConstexprSupported, bool CLinkageMayDiffer);
4241
4242 /// type checking declaration initializers (C99 6.7.8)
4244 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4245
4249 Expr *Init);
4250
4252 Expr *Init);
4253
4255
4256 // Heuristically tells if the function is `get_return_object` member of a
4257 // coroutine promise_type by matching the function name.
4258 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4259 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4260
4261 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4262 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4264 Scope *S);
4265
4266 /// If this function is a C++ replaceable global allocation function
4267 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4268 /// adds any function attributes that we know a priori based on the standard.
4269 ///
4270 /// We need to check for duplicate attributes both here and where user-written
4271 /// attributes are applied to declarations.
4273 FunctionDecl *FD);
4274
4275 /// Adds any function attributes that we know a priori based on
4276 /// the declaration of this function.
4277 ///
4278 /// These attributes can apply both to implicitly-declared builtins
4279 /// (like __builtin___printf_chk) or to library-declared functions
4280 /// like NSLog or printf.
4281 ///
4282 /// We need to check for duplicate attributes both here and where user-written
4283 /// attributes are applied to declarations.
4285
4286 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4287 /// the correct width, and that the field type is valid.
4288 /// Returns false on success.
4290 const IdentifierInfo *FieldName, QualType FieldTy,
4291 bool IsMsStruct, Expr *BitWidth);
4292
4293 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4294 /// enum. If AllowMask is true, then we also allow the complement of a valid
4295 /// value, to be used as a mask.
4296 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4297 bool AllowMask) const;
4298
4299 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4300 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4301 SourceLocation WeakNameLoc);
4302
4303 /// ActOnPragmaRedefineExtname - Called on well formed
4304 /// \#pragma redefine_extname oldname newname.
4306 IdentifierInfo *AliasName,
4307 SourceLocation PragmaLoc,
4308 SourceLocation WeakNameLoc,
4309 SourceLocation AliasNameLoc);
4310
4311 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4312 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4313 SourceLocation PragmaLoc,
4314 SourceLocation WeakNameLoc,
4315 SourceLocation AliasNameLoc);
4316
4317 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4319 Emitted,
4320 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4321 OMPDiscarded, // Discarded due to OpenMP hostness
4322 TemplateDiscarded, // Discarded due to uninstantiated templates
4323 Unknown,
4324 };
4325 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4326 bool Final = false);
4327
4328 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4330
4331private:
4332 /// Function or variable declarations to be checked for whether the deferred
4333 /// diagnostics should be emitted.
4334 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
4335
4336 /// Map of current shadowing declarations to shadowed declarations. Warn if
4337 /// it looks like the user is trying to modify the shadowing declaration.
4338 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4339
4340 // We need this to handle
4341 //
4342 // typedef struct {
4343 // void *foo() { return 0; }
4344 // } A;
4345 //
4346 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4347 // for example. If 'A', foo will have external linkage. If we have '*A',
4348 // foo will have no linkage. Since we can't know until we get to the end
4349 // of the typedef, this function finds out if D might have non-external
4350 // linkage. Callers should verify at the end of the TU if it D has external
4351 // linkage or not.
4352 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4353
4354 ///@}
4355
4356 //
4357 //
4358 // -------------------------------------------------------------------------
4359 //
4360 //
4361
4362 /// \name Declaration Attribute Handling
4363 /// Implementations are in SemaDeclAttr.cpp
4364 ///@{
4365
4366public:
4367 /// Describes the kind of priority given to an availability attribute.
4368 ///
4369 /// The sum of priorities deteremines the final priority of the attribute.
4370 /// The final priority determines how the attribute will be merged.
4371 /// An attribute with a lower priority will always remove higher priority
4372 /// attributes for the specified platform when it is being applied. An
4373 /// attribute with a higher priority will not be applied if the declaration
4374 /// already has an availability attribute with a lower priority for the
4375 /// specified platform. The final prirority values are not expected to match
4376 /// the values in this enumeration, but instead should be treated as a plain
4377 /// integer value. This enumeration just names the priority weights that are
4378 /// used to calculate that final vaue.
4380 /// The availability attribute was specified explicitly next to the
4381 /// declaration.
4383
4384 /// The availability attribute was applied using '#pragma clang attribute'.
4386
4387 /// The availability attribute for a specific platform was inferred from
4388 /// an availability attribute for another platform.
4391
4392 /// Describes the reason a calling convention specification was ignored, used
4393 /// for diagnostics.
4395 ForThisTarget = 0,
4399 };
4400
4401 /// A helper function to provide Attribute Location for the Attr types
4402 /// AND the ParsedAttr.
4403 template <typename AttrInfo>
4404 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
4405 getAttrLoc(const AttrInfo &AL) {
4406 return AL.getLocation();
4407 }
4409
4410 /// If Expr is a valid integer constant, get the value of the integer
4411 /// expression and return success or failure. May output an error.
4412 ///
4413 /// Negative argument is implicitly converted to unsigned, unless
4414 /// \p StrictlyUnsigned is true.
4415 template <typename AttrInfo>
4416 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4417 unsigned Idx = UINT_MAX,
4418 bool StrictlyUnsigned = false) {
4419 std::optional<llvm::APSInt> I = llvm::APSInt(32);
4420 if (Expr->isTypeDependent() ||
4422 if (Idx != UINT_MAX)
4423 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4424 << &AI << Idx << AANT_ArgumentIntegerConstant
4425 << Expr->getSourceRange();
4426 else
4427 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4429 return false;
4430 }
4431
4432 if (!I->isIntN(32)) {
4433 Diag(Expr->getExprLoc(), diag::err_ice_too_large)
4434 << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
4435 return false;
4436 }
4437
4438 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
4439 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
4440 << &AI << /*non-negative*/ 1;
4441 return false;
4442 }
4443
4444 Val = (uint32_t)I->getZExtValue();
4445 return true;
4446 }
4447
4448 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
4449 /// \#pragma weak during processing of other Decls.
4450 /// I couldn't figure out a clean way to generate these in-line, so
4451 /// we store them here and handle separately -- which is a hack.
4452 /// It would be best to refactor this.
4454
4455 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
4457
4461
4462 /// ExtVectorDecls - This is a list all the extended vector types. This allows
4463 /// us to associate a raw vector type with one of the ext_vector type names.
4464 /// This is only necessary for issuing pretty diagnostics.
4466
4467 /// Check if the argument \p E is a ASCII string literal. If not emit an error
4468 /// and return false, otherwise set \p Str to the value of the string literal
4469 /// and return true.
4471 const Expr *E, StringRef &Str,
4472 SourceLocation *ArgLocation = nullptr);
4473
4474 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
4475 /// If not emit an error and return false. If the argument is an identifier it
4476 /// will emit an error with a fixit hint and treat it as if it was a string
4477 /// literal.
4478 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4479 StringRef &Str,
4480 SourceLocation *ArgLocation = nullptr);
4481
4482 /// Determine if type T is a valid subject for a nonnull and similar
4483 /// attributes. Dependent types are considered valid so they can be checked
4484 /// during instantiation time. By default, we look through references (the
4485 /// behavior used by nonnull), but if the second parameter is true, then we
4486 /// treat a reference type as valid.
4487 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4488
4489 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
4490 /// declaration.
4492 Expr *OE);
4493
4494 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
4495 /// declaration.
4497 Expr *ParamExpr);
4498
4499 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4500 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4501
4502 AvailabilityAttr *mergeAvailabilityAttr(
4503 NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
4504 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
4505 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
4506 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
4507 int Priority, IdentifierInfo *IIEnvironment);
4508
4509 TypeVisibilityAttr *
4511 TypeVisibilityAttr::VisibilityType Vis);
4512 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
4513 VisibilityAttr::VisibilityType Vis);
4514 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
4515 StringRef Name);
4516
4517 /// Used to implement to perform semantic checking on
4518 /// attribute((section("foo"))) specifiers.
4519 ///
4520 /// In this case, "foo" is passed in to be checked. If the section
4521 /// specifier is invalid, return an Error that indicates the problem.
4522 ///
4523 /// This is a simple quality of implementation feature to catch errors
4524 /// and give good diagnostics in cases when the assembler or code generator
4525 /// would otherwise reject the section specifier.
4526 llvm::Error isValidSectionSpecifier(StringRef Str);
4527 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4528 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
4529 StringRef Name);
4530
4531 // Check for things we'd like to warn about. Multiversioning issues are
4532 // handled later in the process, once we know how many exist.
4533 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4534
4535 /// Check Target Version attrs
4536 bool checkTargetVersionAttr(SourceLocation Loc, Decl *D, StringRef Str);
4538 SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal,
4539 Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault,
4540 SmallVectorImpl<SmallString<64>> &StringsBuffer);
4541
4542 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
4543 StringRef NewUserDiagnostic);
4544 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
4545 IdentifierInfo *Format, int FormatIdx,
4546 int FirstArg);
4547
4548 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
4549 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4550 bool IsPackExpansion);
4552 bool IsPackExpansion);
4553
4554 /// AddAlignValueAttr - Adds an align_value attribute to a particular
4555 /// declaration.
4556 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
4557
4558 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
4559 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
4562
4564 bool BestCase,
4565 MSInheritanceModel SemanticSpelling);
4566
4568
4569 /// AddModeAttr - Adds a mode attribute to a particular declaration.
4570 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
4571 bool InInstantiation = false);
4572 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
4573 const AttributeCommonInfo &CI,
4574 const IdentifierInfo *Ident);
4575 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
4576 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
4577 const AttributeCommonInfo &CI);
4578 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
4579 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
4580 const InternalLinkageAttr &AL);
4581
4582 /// Check validaty of calling convention attribute \p attr. If \p FD
4583 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
4584 /// target. Otherwise, it is specified by \p CFT.
4586 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
4588
4589 /// Checks a regparm attribute, returning true if it is ill-formed and
4590 /// otherwise setting numParams to the appropriate value.
4591 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4592
4593 /// Create an CUDALaunchBoundsAttr attribute.
4594 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
4595 Expr *MaxThreads,
4596 Expr *MinBlocks,
4597 Expr *MaxBlocks);
4598
4599 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
4600 /// declaration.
4602 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
4603
4604 enum class RetainOwnershipKind { NS, CF, OS };
4605
4606 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
4607 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
4608
4609 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
4610
4611 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
4612 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
4613 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
4614 const AttributeCommonInfo &CI,
4615 bool BestCase,
4616 MSInheritanceModel Model);
4617
4618 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
4619 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
4620 const EnforceTCBLeafAttr &AL);
4621
4622 /// Helper for delayed processing TransparentUnion or
4623 /// BPFPreserveAccessIndexAttr attribute.
4625 const ParsedAttributesView &AttrList);
4626
4627 // Options for ProcessDeclAttributeList().
4630 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
4631
4633 ProcessDeclAttributeOptions Result = *this;
4634 Result.IncludeCXX11Attributes = Val;
4635 return Result;
4636 }
4637
4639 ProcessDeclAttributeOptions Result = *this;
4640 Result.IgnoreTypeAttributes = Val;
4641 return Result;
4642 }
4643
4644 // Should C++11 attributes be processed?
4646
4647<