1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements type-related semantic analysis.
11 //===----------------------------------------------------------------------===//
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/ASTStructuralEquivalence.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/LocInfoType.h"
25 #include "clang/AST/Type.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeLocVisitor.h"
28 #include "clang/Basic/LangOptions.h"
29 #include "clang/Basic/SourceLocation.h"
30 #include "clang/Basic/Specifiers.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/DelayedDiagnostic.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedAttr.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaCUDA.h"
40 #include "clang/Sema/SemaHLSL.h"
41 #include "clang/Sema/SemaObjC.h"
42 #include "clang/Sema/SemaOpenMP.h"
43 #include "clang/Sema/Template.h"
44 #include "clang/Sema/TemplateInstCallback.h"
45 #include "llvm/ADT/ArrayRef.h"
46 #include "llvm/ADT/STLForwardCompat.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include "llvm/IR/DerivedTypes.h"
49 #include "llvm/Support/ErrorHandling.h"
53 using namespace clang
;
55 enum TypeDiagSelector
{
61 /// isOmittedBlockReturnType - Return true if this declarator is missing a
62 /// return type because this is a omitted return type on a block literal.
63 static bool isOmittedBlockReturnType(const Declarator
&D
) {
64 if (D
.getContext() != DeclaratorContext::BlockLiteral
||
65 D
.getDeclSpec().hasTypeSpecifier())
68 if (D
.getNumTypeObjects() == 0)
69 return true; // ^{ ... }
71 if (D
.getNumTypeObjects() == 1 &&
72 D
.getTypeObject(0).Kind
== DeclaratorChunk::Function
)
73 return true; // ^(int X, float Y) { ... }
78 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
79 /// doesn't apply to the given type.
80 static void diagnoseBadTypeAttribute(Sema
&S
, const ParsedAttr
&attr
,
82 TypeDiagSelector WhichType
;
83 bool useExpansionLoc
= true;
84 switch (attr
.getKind()) {
85 case ParsedAttr::AT_ObjCGC
:
86 WhichType
= TDS_Pointer
;
88 case ParsedAttr::AT_ObjCOwnership
:
89 WhichType
= TDS_ObjCObjOrBlock
;
92 // Assume everything else was a function attribute.
93 WhichType
= TDS_Function
;
94 useExpansionLoc
= false;
98 SourceLocation loc
= attr
.getLoc();
99 StringRef name
= attr
.getAttrName()->getName();
101 // The GC attributes are usually written with macros; special-case them.
102 IdentifierInfo
*II
= attr
.isArgIdent(0) ? attr
.getArgAsIdent(0)->Ident
104 if (useExpansionLoc
&& loc
.isMacroID() && II
) {
105 if (II
->isStr("strong")) {
106 if (S
.findMacroSpelling(loc
, "__strong")) name
= "__strong";
107 } else if (II
->isStr("weak")) {
108 if (S
.findMacroSpelling(loc
, "__weak")) name
= "__weak";
112 S
.Diag(loc
, attr
.isRegularKeywordAttribute()
113 ? diag::err_type_attribute_wrong_type
114 : diag::warn_type_attribute_wrong_type
)
115 << name
<< WhichType
<< type
;
118 // objc_gc applies to Objective-C pointers or, otherwise, to the
119 // smallest available pointer type (i.e. 'void*' in 'void**').
120 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
121 case ParsedAttr::AT_ObjCGC: \
122 case ParsedAttr::AT_ObjCOwnership
124 // Calling convention attributes.
125 #define CALLING_CONV_ATTRS_CASELIST \
126 case ParsedAttr::AT_CDecl: \
127 case ParsedAttr::AT_FastCall: \
128 case ParsedAttr::AT_StdCall: \
129 case ParsedAttr::AT_ThisCall: \
130 case ParsedAttr::AT_RegCall: \
131 case ParsedAttr::AT_Pascal: \
132 case ParsedAttr::AT_SwiftCall: \
133 case ParsedAttr::AT_SwiftAsyncCall: \
134 case ParsedAttr::AT_VectorCall: \
135 case ParsedAttr::AT_AArch64VectorPcs: \
136 case ParsedAttr::AT_AArch64SVEPcs: \
137 case ParsedAttr::AT_AMDGPUKernelCall: \
138 case ParsedAttr::AT_MSABI: \
139 case ParsedAttr::AT_SysVABI: \
140 case ParsedAttr::AT_Pcs: \
141 case ParsedAttr::AT_IntelOclBicc: \
142 case ParsedAttr::AT_PreserveMost: \
143 case ParsedAttr::AT_PreserveAll: \
144 case ParsedAttr::AT_M68kRTD: \
145 case ParsedAttr::AT_PreserveNone: \
146 case ParsedAttr::AT_RISCVVectorCC
148 // Function type attributes.
149 #define FUNCTION_TYPE_ATTRS_CASELIST \
150 case ParsedAttr::AT_NSReturnsRetained: \
151 case ParsedAttr::AT_NoReturn: \
152 case ParsedAttr::AT_NonBlocking: \
153 case ParsedAttr::AT_NonAllocating: \
154 case ParsedAttr::AT_Blocking: \
155 case ParsedAttr::AT_Allocating: \
156 case ParsedAttr::AT_Regparm: \
157 case ParsedAttr::AT_CmseNSCall: \
158 case ParsedAttr::AT_ArmStreaming: \
159 case ParsedAttr::AT_ArmStreamingCompatible: \
160 case ParsedAttr::AT_ArmPreserves: \
161 case ParsedAttr::AT_ArmIn: \
162 case ParsedAttr::AT_ArmOut: \
163 case ParsedAttr::AT_ArmInOut: \
164 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
165 case ParsedAttr::AT_AnyX86NoCfCheck: \
166 CALLING_CONV_ATTRS_CASELIST
168 // Microsoft-specific type qualifiers.
169 #define MS_TYPE_ATTRS_CASELIST \
170 case ParsedAttr::AT_Ptr32: \
171 case ParsedAttr::AT_Ptr64: \
172 case ParsedAttr::AT_SPtr: \
173 case ParsedAttr::AT_UPtr
175 // Nullability qualifiers.
176 #define NULLABILITY_TYPE_ATTRS_CASELIST \
177 case ParsedAttr::AT_TypeNonNull: \
178 case ParsedAttr::AT_TypeNullable: \
179 case ParsedAttr::AT_TypeNullableResult: \
180 case ParsedAttr::AT_TypeNullUnspecified
183 /// An object which stores processing state for the entire
184 /// GetTypeForDeclarator process.
185 class TypeProcessingState
{
188 /// The declarator being processed.
189 Declarator
&declarator
;
191 /// The index of the declarator chunk we're currently processing.
192 /// May be the total number of valid chunks, indicating the
196 /// The original set of attributes on the DeclSpec.
197 SmallVector
<ParsedAttr
*, 2> savedAttrs
;
199 /// A list of attributes to diagnose the uselessness of when the
200 /// processing is complete.
201 SmallVector
<ParsedAttr
*, 2> ignoredTypeAttrs
;
203 /// Attributes corresponding to AttributedTypeLocs that we have not yet
205 // FIXME: The two-phase mechanism by which we construct Types and fill
206 // their TypeLocs makes it hard to correctly assign these. We keep the
207 // attributes in creation order as an attempt to make them line up
209 using TypeAttrPair
= std::pair
<const AttributedType
*, const Attr
*>;
210 SmallVector
<TypeAttrPair
, 8> AttrsForTypes
;
211 bool AttrsForTypesSorted
= true;
213 /// MacroQualifiedTypes mapping to macro expansion locations that will be
214 /// stored in a MacroQualifiedTypeLoc.
215 llvm::DenseMap
<const MacroQualifiedType
*, SourceLocation
> LocsForMacros
;
217 /// Flag to indicate we parsed a noderef attribute. This is used for
218 /// validating that noderef was used on a pointer or array.
221 // Flag to indicate that we already parsed a HLSL parameter modifier
222 // attribute. This prevents double-mutating the type.
223 bool ParsedHLSLParamMod
;
226 TypeProcessingState(Sema
&sema
, Declarator
&declarator
)
227 : sema(sema
), declarator(declarator
),
228 chunkIndex(declarator
.getNumTypeObjects()), parsedNoDeref(false),
229 ParsedHLSLParamMod(false) {}
231 Sema
&getSema() const {
235 Declarator
&getDeclarator() const {
239 bool isProcessingDeclSpec() const {
240 return chunkIndex
== declarator
.getNumTypeObjects();
243 unsigned getCurrentChunkIndex() const {
247 void setCurrentChunkIndex(unsigned idx
) {
248 assert(idx
<= declarator
.getNumTypeObjects());
252 ParsedAttributesView
&getCurrentAttributes() const {
253 if (isProcessingDeclSpec())
254 return getMutableDeclSpec().getAttributes();
255 return declarator
.getTypeObject(chunkIndex
).getAttrs();
258 /// Save the current set of attributes on the DeclSpec.
259 void saveDeclSpecAttrs() {
260 // Don't try to save them multiple times.
261 if (!savedAttrs
.empty())
264 DeclSpec
&spec
= getMutableDeclSpec();
265 llvm::append_range(savedAttrs
,
266 llvm::make_pointer_range(spec
.getAttributes()));
269 /// Record that we had nowhere to put the given type attribute.
270 /// We will diagnose such attributes later.
271 void addIgnoredTypeAttr(ParsedAttr
&attr
) {
272 ignoredTypeAttrs
.push_back(&attr
);
275 /// Diagnose all the ignored type attributes, given that the
276 /// declarator worked out to the given type.
277 void diagnoseIgnoredTypeAttrs(QualType type
) const {
278 for (auto *Attr
: ignoredTypeAttrs
)
279 diagnoseBadTypeAttribute(getSema(), *Attr
, type
);
282 /// Get an attributed type for the given attribute, and remember the Attr
283 /// object so that we can attach it to the AttributedTypeLoc.
284 QualType
getAttributedType(Attr
*A
, QualType ModifiedType
,
285 QualType EquivType
) {
287 sema
.Context
.getAttributedType(A
, ModifiedType
, EquivType
);
288 AttrsForTypes
.push_back({cast
<AttributedType
>(T
.getTypePtr()), A
});
289 AttrsForTypesSorted
= false;
293 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
294 QualType
getBTFTagAttributedType(const BTFTypeTagAttr
*BTFAttr
,
295 QualType WrappedType
) {
296 return sema
.Context
.getBTFTagAttributedType(BTFAttr
, WrappedType
);
299 /// Completely replace the \c auto in \p TypeWithAuto by
300 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
302 QualType
ReplaceAutoType(QualType TypeWithAuto
, QualType Replacement
) {
303 QualType T
= sema
.ReplaceAutoType(TypeWithAuto
, Replacement
);
304 if (auto *AttrTy
= TypeWithAuto
->getAs
<AttributedType
>()) {
305 // Attributed type still should be an attributed type after replacement.
306 auto *NewAttrTy
= cast
<AttributedType
>(T
.getTypePtr());
307 for (TypeAttrPair
&A
: AttrsForTypes
) {
308 if (A
.first
== AttrTy
)
311 AttrsForTypesSorted
= false;
316 /// Extract and remove the Attr* for a given attributed type.
317 const Attr
*takeAttrForAttributedType(const AttributedType
*AT
) {
318 if (!AttrsForTypesSorted
) {
319 llvm::stable_sort(AttrsForTypes
, llvm::less_first());
320 AttrsForTypesSorted
= true;
323 // FIXME: This is quadratic if we have lots of reuses of the same
325 for (auto It
= std::partition_point(
326 AttrsForTypes
.begin(), AttrsForTypes
.end(),
327 [=](const TypeAttrPair
&A
) { return A
.first
< AT
; });
328 It
!= AttrsForTypes
.end() && It
->first
== AT
; ++It
) {
330 const Attr
*Result
= It
->second
;
331 It
->second
= nullptr;
336 llvm_unreachable("no Attr* for AttributedType*");
340 getExpansionLocForMacroQualifiedType(const MacroQualifiedType
*MQT
) const {
341 auto FoundLoc
= LocsForMacros
.find(MQT
);
342 assert(FoundLoc
!= LocsForMacros
.end() &&
343 "Unable to find macro expansion location for MacroQualifedType");
344 return FoundLoc
->second
;
347 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType
*MQT
,
348 SourceLocation Loc
) {
349 LocsForMacros
[MQT
] = Loc
;
352 void setParsedNoDeref(bool parsed
) { parsedNoDeref
= parsed
; }
354 bool didParseNoDeref() const { return parsedNoDeref
; }
356 void setParsedHLSLParamMod(bool Parsed
) { ParsedHLSLParamMod
= Parsed
; }
358 bool didParseHLSLParamMod() const { return ParsedHLSLParamMod
; }
360 ~TypeProcessingState() {
361 if (savedAttrs
.empty())
364 getMutableDeclSpec().getAttributes().clearListOnly();
365 for (ParsedAttr
*AL
: savedAttrs
)
366 getMutableDeclSpec().getAttributes().addAtEnd(AL
);
370 DeclSpec
&getMutableDeclSpec() const {
371 return const_cast<DeclSpec
&>(declarator
.getDeclSpec());
374 } // end anonymous namespace
376 static void moveAttrFromListToList(ParsedAttr
&attr
,
377 ParsedAttributesView
&fromList
,
378 ParsedAttributesView
&toList
) {
379 fromList
.remove(&attr
);
380 toList
.addAtEnd(&attr
);
383 /// The location of a type attribute.
384 enum TypeAttrLocation
{
385 /// The attribute is in the decl-specifier-seq.
387 /// The attribute is part of a DeclaratorChunk.
389 /// The attribute is immediately after the declaration's name.
394 processTypeAttrs(TypeProcessingState
&state
, QualType
&type
,
395 TypeAttrLocation TAL
, const ParsedAttributesView
&attrs
,
396 CUDAFunctionTarget CFT
= CUDAFunctionTarget::HostDevice
);
398 static bool handleFunctionTypeAttr(TypeProcessingState
&state
, ParsedAttr
&attr
,
399 QualType
&type
, CUDAFunctionTarget CFT
);
401 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState
&state
,
402 ParsedAttr
&attr
, QualType
&type
);
404 static bool handleObjCGCTypeAttr(TypeProcessingState
&state
, ParsedAttr
&attr
,
407 static bool handleObjCOwnershipTypeAttr(TypeProcessingState
&state
,
408 ParsedAttr
&attr
, QualType
&type
);
410 static bool handleObjCPointerTypeAttr(TypeProcessingState
&state
,
411 ParsedAttr
&attr
, QualType
&type
) {
412 if (attr
.getKind() == ParsedAttr::AT_ObjCGC
)
413 return handleObjCGCTypeAttr(state
, attr
, type
);
414 assert(attr
.getKind() == ParsedAttr::AT_ObjCOwnership
);
415 return handleObjCOwnershipTypeAttr(state
, attr
, type
);
418 /// Given the index of a declarator chunk, check whether that chunk
419 /// directly specifies the return type of a function and, if so, find
420 /// an appropriate place for it.
422 /// \param i - a notional index which the search will start
423 /// immediately inside
425 /// \param onlyBlockPointers Whether we should only look into block
426 /// pointer types (vs. all pointer types).
427 static DeclaratorChunk
*maybeMovePastReturnType(Declarator
&declarator
,
429 bool onlyBlockPointers
) {
430 assert(i
<= declarator
.getNumTypeObjects());
432 DeclaratorChunk
*result
= nullptr;
434 // First, look inwards past parens for a function declarator.
435 for (; i
!= 0; --i
) {
436 DeclaratorChunk
&fnChunk
= declarator
.getTypeObject(i
-1);
437 switch (fnChunk
.Kind
) {
438 case DeclaratorChunk::Paren
:
441 // If we find anything except a function, bail out.
442 case DeclaratorChunk::Pointer
:
443 case DeclaratorChunk::BlockPointer
:
444 case DeclaratorChunk::Array
:
445 case DeclaratorChunk::Reference
:
446 case DeclaratorChunk::MemberPointer
:
447 case DeclaratorChunk::Pipe
:
450 // If we do find a function declarator, scan inwards from that,
451 // looking for a (block-)pointer declarator.
452 case DeclaratorChunk::Function
:
453 for (--i
; i
!= 0; --i
) {
454 DeclaratorChunk
&ptrChunk
= declarator
.getTypeObject(i
-1);
455 switch (ptrChunk
.Kind
) {
456 case DeclaratorChunk::Paren
:
457 case DeclaratorChunk::Array
:
458 case DeclaratorChunk::Function
:
459 case DeclaratorChunk::Reference
:
460 case DeclaratorChunk::Pipe
:
463 case DeclaratorChunk::MemberPointer
:
464 case DeclaratorChunk::Pointer
:
465 if (onlyBlockPointers
)
470 case DeclaratorChunk::BlockPointer
:
474 llvm_unreachable("bad declarator chunk kind");
477 // If we run out of declarators doing that, we're done.
480 llvm_unreachable("bad declarator chunk kind");
482 // Okay, reconsider from our new point.
486 // Ran out of chunks, bail out.
490 /// Given that an objc_gc attribute was written somewhere on a
491 /// declaration *other* than on the declarator itself (for which, use
492 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
493 /// didn't apply in whatever position it was written in, try to move
494 /// it to a more appropriate position.
495 static void distributeObjCPointerTypeAttr(TypeProcessingState
&state
,
496 ParsedAttr
&attr
, QualType type
) {
497 Declarator
&declarator
= state
.getDeclarator();
499 // Move it to the outermost normal or block pointer declarator.
500 for (unsigned i
= state
.getCurrentChunkIndex(); i
!= 0; --i
) {
501 DeclaratorChunk
&chunk
= declarator
.getTypeObject(i
-1);
502 switch (chunk
.Kind
) {
503 case DeclaratorChunk::Pointer
:
504 case DeclaratorChunk::BlockPointer
: {
505 // But don't move an ARC ownership attribute to the return type
507 DeclaratorChunk
*destChunk
= nullptr;
508 if (state
.isProcessingDeclSpec() &&
509 attr
.getKind() == ParsedAttr::AT_ObjCOwnership
)
510 destChunk
= maybeMovePastReturnType(declarator
, i
- 1,
511 /*onlyBlockPointers=*/true);
512 if (!destChunk
) destChunk
= &chunk
;
514 moveAttrFromListToList(attr
, state
.getCurrentAttributes(),
515 destChunk
->getAttrs());
519 case DeclaratorChunk::Paren
:
520 case DeclaratorChunk::Array
:
523 // We may be starting at the return type of a block.
524 case DeclaratorChunk::Function
:
525 if (state
.isProcessingDeclSpec() &&
526 attr
.getKind() == ParsedAttr::AT_ObjCOwnership
) {
527 if (DeclaratorChunk
*dest
= maybeMovePastReturnType(
529 /*onlyBlockPointers=*/true)) {
530 moveAttrFromListToList(attr
, state
.getCurrentAttributes(),
537 // Don't walk through these.
538 case DeclaratorChunk::Reference
:
539 case DeclaratorChunk::MemberPointer
:
540 case DeclaratorChunk::Pipe
:
546 diagnoseBadTypeAttribute(state
.getSema(), attr
, type
);
549 /// Distribute an objc_gc type attribute that was written on the
551 static void distributeObjCPointerTypeAttrFromDeclarator(
552 TypeProcessingState
&state
, ParsedAttr
&attr
, QualType
&declSpecType
) {
553 Declarator
&declarator
= state
.getDeclarator();
555 // objc_gc goes on the innermost pointer to something that's not a
557 unsigned innermost
= -1U;
558 bool considerDeclSpec
= true;
559 for (unsigned i
= 0, e
= declarator
.getNumTypeObjects(); i
!= e
; ++i
) {
560 DeclaratorChunk
&chunk
= declarator
.getTypeObject(i
);
561 switch (chunk
.Kind
) {
562 case DeclaratorChunk::Pointer
:
563 case DeclaratorChunk::BlockPointer
:
567 case DeclaratorChunk::Reference
:
568 case DeclaratorChunk::MemberPointer
:
569 case DeclaratorChunk::Paren
:
570 case DeclaratorChunk::Array
:
571 case DeclaratorChunk::Pipe
:
574 case DeclaratorChunk::Function
:
575 considerDeclSpec
= false;
581 // That might actually be the decl spec if we weren't blocked by
582 // anything in the declarator.
583 if (considerDeclSpec
) {
584 if (handleObjCPointerTypeAttr(state
, attr
, declSpecType
)) {
585 // Splice the attribute into the decl spec. Prevents the
586 // attribute from being applied multiple times and gives
587 // the source-location-filler something to work with.
588 state
.saveDeclSpecAttrs();
589 declarator
.getMutableDeclSpec().getAttributes().takeOneFrom(
590 declarator
.getAttributes(), &attr
);
595 // Otherwise, if we found an appropriate chunk, splice the attribute
597 if (innermost
!= -1U) {
598 moveAttrFromListToList(attr
, declarator
.getAttributes(),
599 declarator
.getTypeObject(innermost
).getAttrs());
603 // Otherwise, diagnose when we're done building the type.
604 declarator
.getAttributes().remove(&attr
);
605 state
.addIgnoredTypeAttr(attr
);
608 /// A function type attribute was written somewhere in a declaration
609 /// *other* than on the declarator itself or in the decl spec. Given
610 /// that it didn't apply in whatever position it was written in, try
611 /// to move it to a more appropriate position.
612 static void distributeFunctionTypeAttr(TypeProcessingState
&state
,
613 ParsedAttr
&attr
, QualType type
) {
614 Declarator
&declarator
= state
.getDeclarator();
616 // Try to push the attribute from the return type of a function to
617 // the function itself.
618 for (unsigned i
= state
.getCurrentChunkIndex(); i
!= 0; --i
) {
619 DeclaratorChunk
&chunk
= declarator
.getTypeObject(i
-1);
620 switch (chunk
.Kind
) {
621 case DeclaratorChunk::Function
:
622 moveAttrFromListToList(attr
, state
.getCurrentAttributes(),
626 case DeclaratorChunk::Paren
:
627 case DeclaratorChunk::Pointer
:
628 case DeclaratorChunk::BlockPointer
:
629 case DeclaratorChunk::Array
:
630 case DeclaratorChunk::Reference
:
631 case DeclaratorChunk::MemberPointer
:
632 case DeclaratorChunk::Pipe
:
637 diagnoseBadTypeAttribute(state
.getSema(), attr
, type
);
640 /// Try to distribute a function type attribute to the innermost
641 /// function chunk or type. Returns true if the attribute was
642 /// distributed, false if no location was found.
643 static bool distributeFunctionTypeAttrToInnermost(
644 TypeProcessingState
&state
, ParsedAttr
&attr
,
645 ParsedAttributesView
&attrList
, QualType
&declSpecType
,
646 CUDAFunctionTarget CFT
) {
647 Declarator
&declarator
= state
.getDeclarator();
649 // Put it on the innermost function chunk, if there is one.
650 for (unsigned i
= 0, e
= declarator
.getNumTypeObjects(); i
!= e
; ++i
) {
651 DeclaratorChunk
&chunk
= declarator
.getTypeObject(i
);
652 if (chunk
.Kind
!= DeclaratorChunk::Function
) continue;
654 moveAttrFromListToList(attr
, attrList
, chunk
.getAttrs());
658 return handleFunctionTypeAttr(state
, attr
, declSpecType
, CFT
);
661 /// A function type attribute was written in the decl spec. Try to
662 /// apply it somewhere.
663 static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState
&state
,
665 QualType
&declSpecType
,
666 CUDAFunctionTarget CFT
) {
667 state
.saveDeclSpecAttrs();
669 // Try to distribute to the innermost.
670 if (distributeFunctionTypeAttrToInnermost(
671 state
, attr
, state
.getCurrentAttributes(), declSpecType
, CFT
))
674 // If that failed, diagnose the bad attribute when the declarator is
676 state
.addIgnoredTypeAttr(attr
);
679 /// A function type attribute was written on the declarator or declaration.
680 /// Try to apply it somewhere.
681 /// `Attrs` is the attribute list containing the declaration (either of the
682 /// declarator or the declaration).
683 static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState
&state
,
685 QualType
&declSpecType
,
686 CUDAFunctionTarget CFT
) {
687 Declarator
&declarator
= state
.getDeclarator();
689 // Try to distribute to the innermost.
690 if (distributeFunctionTypeAttrToInnermost(
691 state
, attr
, declarator
.getAttributes(), declSpecType
, CFT
))
694 // If that failed, diagnose the bad attribute when the declarator is
696 declarator
.getAttributes().remove(&attr
);
697 state
.addIgnoredTypeAttr(attr
);
700 /// Given that there are attributes written on the declarator or declaration
701 /// itself, try to distribute any type attributes to the appropriate
702 /// declarator chunk.
704 /// These are attributes like the following:
707 /// but not necessarily this:
710 /// `Attrs` is the attribute list containing the declaration (either of the
711 /// declarator or the declaration).
712 static void distributeTypeAttrsFromDeclarator(TypeProcessingState
&state
,
713 QualType
&declSpecType
,
714 CUDAFunctionTarget CFT
) {
715 // The called functions in this loop actually remove things from the current
716 // list, so iterating over the existing list isn't possible. Instead, make a
717 // non-owning copy and iterate over that.
718 ParsedAttributesView AttrsCopy
{state
.getDeclarator().getAttributes()};
719 for (ParsedAttr
&attr
: AttrsCopy
) {
720 // Do not distribute [[]] attributes. They have strict rules for what
721 // they appertain to.
722 if (attr
.isStandardAttributeSyntax() || attr
.isRegularKeywordAttribute())
725 switch (attr
.getKind()) {
726 OBJC_POINTER_TYPE_ATTRS_CASELIST
:
727 distributeObjCPointerTypeAttrFromDeclarator(state
, attr
, declSpecType
);
730 FUNCTION_TYPE_ATTRS_CASELIST
:
731 distributeFunctionTypeAttrFromDeclarator(state
, attr
, declSpecType
, CFT
);
734 MS_TYPE_ATTRS_CASELIST
:
735 // Microsoft type attributes cannot go after the declarator-id.
738 NULLABILITY_TYPE_ATTRS_CASELIST
:
739 // Nullability specifiers cannot go after the declarator-id.
741 // Objective-C __kindof does not get distributed.
742 case ParsedAttr::AT_ObjCKindOf
:
751 /// Add a synthetic '()' to a block-literal declarator if it is
752 /// required, given the return type.
753 static void maybeSynthesizeBlockSignature(TypeProcessingState
&state
,
754 QualType declSpecType
) {
755 Declarator
&declarator
= state
.getDeclarator();
757 // First, check whether the declarator would produce a function,
758 // i.e. whether the innermost semantic chunk is a function.
759 if (declarator
.isFunctionDeclarator()) {
760 // If so, make that declarator a prototyped declarator.
761 declarator
.getFunctionTypeInfo().hasPrototype
= true;
765 // If there are any type objects, the type as written won't name a
766 // function, regardless of the decl spec type. This is because a
767 // block signature declarator is always an abstract-declarator, and
768 // abstract-declarators can't just be parentheses chunks. Therefore
769 // we need to build a function chunk unless there are no type
770 // objects and the decl spec type is a function.
771 if (!declarator
.getNumTypeObjects() && declSpecType
->isFunctionType())
774 // Note that there *are* cases with invalid declarators where
775 // declarators consist solely of parentheses. In general, these
776 // occur only in failed efforts to make function declarators, so
777 // faking up the function chunk is still the right thing to do.
779 // Otherwise, we need to fake up a function declarator.
780 SourceLocation loc
= declarator
.getBeginLoc();
782 // ...and *prepend* it to the declarator.
783 SourceLocation NoLoc
;
784 declarator
.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
786 /*IsAmbiguous=*/false,
790 /*EllipsisLoc=*/NoLoc
,
792 /*RefQualifierIsLvalueRef=*/true,
793 /*RefQualifierLoc=*/NoLoc
,
794 /*MutableLoc=*/NoLoc
, EST_None
,
795 /*ESpecRange=*/SourceRange(),
796 /*Exceptions=*/nullptr,
797 /*ExceptionRanges=*/nullptr,
799 /*NoexceptExpr=*/nullptr,
800 /*ExceptionSpecTokens=*/nullptr,
801 /*DeclsInPrototype=*/{}, loc
, loc
, declarator
));
803 // For consistency, make sure the state still has us as processing
805 assert(state
.getCurrentChunkIndex() == declarator
.getNumTypeObjects() - 1);
806 state
.setCurrentChunkIndex(declarator
.getNumTypeObjects());
809 static void diagnoseAndRemoveTypeQualifiers(Sema
&S
, const DeclSpec
&DS
,
814 // If this occurs outside a template instantiation, warn the user about
815 // it; they probably didn't mean to specify a redundant qualifier.
816 typedef std::pair
<DeclSpec::TQ
, SourceLocation
> QualLoc
;
817 for (QualLoc Qual
: {QualLoc(DeclSpec::TQ_const
, DS
.getConstSpecLoc()),
818 QualLoc(DeclSpec::TQ_restrict
, DS
.getRestrictSpecLoc()),
819 QualLoc(DeclSpec::TQ_volatile
, DS
.getVolatileSpecLoc()),
820 QualLoc(DeclSpec::TQ_atomic
, DS
.getAtomicSpecLoc())}) {
821 if (!(RemoveTQs
& Qual
.first
))
824 if (!S
.inTemplateInstantiation()) {
825 if (TypeQuals
& Qual
.first
)
826 S
.Diag(Qual
.second
, DiagID
)
827 << DeclSpec::getSpecifierName(Qual
.first
) << TypeSoFar
828 << FixItHint::CreateRemoval(Qual
.second
);
831 TypeQuals
&= ~Qual
.first
;
835 /// Return true if this is omitted block return type. Also check type
836 /// attributes and type qualifiers when returning true.
837 static bool checkOmittedBlockReturnType(Sema
&S
, Declarator
&declarator
,
839 if (!isOmittedBlockReturnType(declarator
))
842 // Warn if we see type attributes for omitted return type on a block literal.
843 SmallVector
<ParsedAttr
*, 2> ToBeRemoved
;
844 for (ParsedAttr
&AL
: declarator
.getMutableDeclSpec().getAttributes()) {
845 if (AL
.isInvalid() || !AL
.isTypeAttr())
848 diag::warn_block_literal_attributes_on_omitted_return_type
)
850 ToBeRemoved
.push_back(&AL
);
852 // Remove bad attributes from the list.
853 for (ParsedAttr
*AL
: ToBeRemoved
)
854 declarator
.getMutableDeclSpec().getAttributes().remove(AL
);
856 // Warn if we see type qualifiers for omitted return type on a block literal.
857 const DeclSpec
&DS
= declarator
.getDeclSpec();
858 unsigned TypeQuals
= DS
.getTypeQualifiers();
859 diagnoseAndRemoveTypeQualifiers(S
, DS
, TypeQuals
, Result
, (unsigned)-1,
860 diag::warn_block_literal_qualifiers_on_omitted_return_type
);
861 declarator
.getMutableDeclSpec().ClearTypeQualifiers();
866 static OpenCLAccessAttr::Spelling
867 getImageAccess(const ParsedAttributesView
&Attrs
) {
868 for (const ParsedAttr
&AL
: Attrs
)
869 if (AL
.getKind() == ParsedAttr::AT_OpenCLAccess
)
870 return static_cast<OpenCLAccessAttr::Spelling
>(AL
.getSemanticSpelling());
871 return OpenCLAccessAttr::Keyword_read_only
;
874 static UnaryTransformType::UTTKind
875 TSTToUnaryTransformType(DeclSpec::TST SwitchTST
) {
877 #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
879 return UnaryTransformType::Enum;
880 #include "clang/Basic/TransformTypeTraits.def"
882 llvm_unreachable("attempted to parse a non-unary transform builtin");
886 /// Convert the specified declspec to the appropriate type
888 /// \param state Specifies the declarator containing the declaration specifier
889 /// to be converted, along with other associated processing state.
890 /// \returns The type described by the declaration specifiers. This function
891 /// never returns null.
892 static QualType
ConvertDeclSpecToType(TypeProcessingState
&state
) {
893 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
896 Sema
&S
= state
.getSema();
897 Declarator
&declarator
= state
.getDeclarator();
898 DeclSpec
&DS
= declarator
.getMutableDeclSpec();
899 SourceLocation DeclLoc
= declarator
.getIdentifierLoc();
900 if (DeclLoc
.isInvalid())
901 DeclLoc
= DS
.getBeginLoc();
903 ASTContext
&Context
= S
.Context
;
906 switch (DS
.getTypeSpecType()) {
907 case DeclSpec::TST_void
:
908 Result
= Context
.VoidTy
;
910 case DeclSpec::TST_char
:
911 if (DS
.getTypeSpecSign() == TypeSpecifierSign::Unspecified
)
912 Result
= Context
.CharTy
;
913 else if (DS
.getTypeSpecSign() == TypeSpecifierSign::Signed
)
914 Result
= Context
.SignedCharTy
;
916 assert(DS
.getTypeSpecSign() == TypeSpecifierSign::Unsigned
&&
917 "Unknown TSS value");
918 Result
= Context
.UnsignedCharTy
;
921 case DeclSpec::TST_wchar
:
922 if (DS
.getTypeSpecSign() == TypeSpecifierSign::Unspecified
)
923 Result
= Context
.WCharTy
;
924 else if (DS
.getTypeSpecSign() == TypeSpecifierSign::Signed
) {
925 S
.Diag(DS
.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec
)
926 << DS
.getSpecifierName(DS
.getTypeSpecType(),
927 Context
.getPrintingPolicy());
928 Result
= Context
.getSignedWCharType();
930 assert(DS
.getTypeSpecSign() == TypeSpecifierSign::Unsigned
&&
931 "Unknown TSS value");
932 S
.Diag(DS
.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec
)
933 << DS
.getSpecifierName(DS
.getTypeSpecType(),
934 Context
.getPrintingPolicy());
935 Result
= Context
.getUnsignedWCharType();
938 case DeclSpec::TST_char8
:
939 assert(DS
.getTypeSpecSign() == TypeSpecifierSign::Unspecified
&&
940 "Unknown TSS value");
941 Result
= Context
.Char8Ty
;
943 case DeclSpec::TST_char16
:
944 assert(DS
.getTypeSpecSign() == TypeSpecifierSign::Unspecified
&&
945 "Unknown TSS value");
946 Result
= Context
.Char16Ty
;
948 case DeclSpec::TST_char32
:
949 assert(DS
.getTypeSpecSign() == TypeSpecifierSign::Unspecified
&&
950 "Unknown TSS value");
951 Result
= Context
.Char32Ty
;
953 case DeclSpec::TST_unspecified
:
954 // If this is a missing declspec in a block literal return context, then it
955 // is inferred from the return statements inside the block.
956 // The declspec is always missing in a lambda expr context; it is either
957 // specified with a trailing return type or inferred.
958 if (S
.getLangOpts().CPlusPlus14
&&
959 declarator
.getContext() == DeclaratorContext::LambdaExpr
) {
960 // In C++1y, a lambda's implicit return type is 'auto'.
961 Result
= Context
.getAutoDeductType();
963 } else if (declarator
.getContext() == DeclaratorContext::LambdaExpr
||
964 checkOmittedBlockReturnType(S
, declarator
,
965 Context
.DependentTy
)) {
966 Result
= Context
.DependentTy
;
970 // Unspecified typespec defaults to int in C90. However, the C90 grammar
971 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
972 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
973 // Note that the one exception to this is function definitions, which are
974 // allowed to be completely missing a declspec. This is handled in the
975 // parser already though by it pretending to have seen an 'int' in this
977 if (S
.getLangOpts().isImplicitIntRequired()) {
978 S
.Diag(DeclLoc
, diag::warn_missing_type_specifier
)
979 << DS
.getSourceRange()
980 << FixItHint::CreateInsertion(DS
.getBeginLoc(), "int");
981 } else if (!DS
.hasTypeSpecifier()) {
982 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
983 // "At least one type specifier shall be given in the declaration
984 // specifiers in each declaration, and in the specifier-qualifier list in
985 // each struct declaration and type name."
986 if (!S
.getLangOpts().isImplicitIntAllowed() && !DS
.isTypeSpecPipe()) {
987 S
.Diag(DeclLoc
, diag::err_missing_type_specifier
)
988 << DS
.getSourceRange();
990 // When this occurs, often something is very broken with the value
991 // being declared, poison it as invalid so we don't get chains of
993 declarator
.setInvalidType(true);
994 } else if (S
.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
995 DS
.isTypeSpecPipe()) {
996 S
.Diag(DeclLoc
, diag::err_missing_actual_pipe_type
)
997 << DS
.getSourceRange();
998 declarator
.setInvalidType(true);
1000 assert(S
.getLangOpts().isImplicitIntAllowed() &&
1001 "implicit int is disabled?");
1002 S
.Diag(DeclLoc
, diag::ext_missing_type_specifier
)
1003 << DS
.getSourceRange()
1004 << FixItHint::CreateInsertion(DS
.getBeginLoc(), "int");
1009 case DeclSpec::TST_int
: {
1010 if (DS
.getTypeSpecSign() != TypeSpecifierSign::Unsigned
) {
1011 switch (DS
.getTypeSpecWidth()) {
1012 case TypeSpecifierWidth::Unspecified
:
1013 Result
= Context
.IntTy
;
1015 case TypeSpecifierWidth::Short
:
1016 Result
= Context
.ShortTy
;
1018 case TypeSpecifierWidth::Long
:
1019 Result
= Context
.LongTy
;
1021 case TypeSpecifierWidth::LongLong
:
1022 Result
= Context
.LongLongTy
;
1024 // 'long long' is a C99 or C++11 feature.
1025 if (!S
.getLangOpts().C99
) {
1026 if (S
.getLangOpts().CPlusPlus
)
1027 S
.Diag(DS
.getTypeSpecWidthLoc(),
1028 S
.getLangOpts().CPlusPlus11
?
1029 diag::warn_cxx98_compat_longlong
: diag::ext_cxx11_longlong
);
1031 S
.Diag(DS
.getTypeSpecWidthLoc(), diag::ext_c99_longlong
);
1036 switch (DS
.getTypeSpecWidth()) {
1037 case TypeSpecifierWidth::Unspecified
:
1038 Result
= Context
.UnsignedIntTy
;
1040 case TypeSpecifierWidth::Short
:
1041 Result
= Context
.UnsignedShortTy
;
1043 case TypeSpecifierWidth::Long
:
1044 Result
= Context
.UnsignedLongTy
;
1046 case TypeSpecifierWidth::LongLong
:
1047 Result
= Context
.UnsignedLongLongTy
;
1049 // 'long long' is a C99 or C++11 feature.
1050 if (!S
.getLangOpts().C99
) {
1051 if (S
.getLangOpts().CPlusPlus
)
1052 S
.Diag(DS
.getTypeSpecWidthLoc(),
1053 S
.getLangOpts().CPlusPlus11
?
1054 diag::warn_cxx98_compat_longlong
: diag::ext_cxx11_longlong
);
1056 S
.Diag(DS
.getTypeSpecWidthLoc(), diag::ext_c99_longlong
);
1063 case DeclSpec::TST_bitint
: {
1064 if (!S
.Context
.getTargetInfo().hasBitIntType())
1065 S
.Diag(DS
.getTypeSpecTypeLoc(), diag::err_type_unsupported
) << "_BitInt";
1067 S
.BuildBitIntType(DS
.getTypeSpecSign() == TypeSpecifierSign::Unsigned
,
1068 DS
.getRepAsExpr(), DS
.getBeginLoc());
1069 if (Result
.isNull()) {
1070 Result
= Context
.IntTy
;
1071 declarator
.setInvalidType(true);
1075 case DeclSpec::TST_accum
: {
1076 switch (DS
.getTypeSpecWidth()) {
1077 case TypeSpecifierWidth::Short
:
1078 Result
= Context
.ShortAccumTy
;
1080 case TypeSpecifierWidth::Unspecified
:
1081 Result
= Context
.AccumTy
;
1083 case TypeSpecifierWidth::Long
:
1084 Result
= Context
.LongAccumTy
;
1086 case TypeSpecifierWidth::LongLong
:
1087 llvm_unreachable("Unable to specify long long as _Accum width");
1090 if (DS
.getTypeSpecSign() == TypeSpecifierSign::Unsigned
)
1091 Result
= Context
.getCorrespondingUnsignedType(Result
);
1093 if (DS
.isTypeSpecSat())
1094 Result
= Context
.getCorrespondingSaturatedType(Result
);
1098 case DeclSpec::TST_fract
: {
1099 switch (DS
.getTypeSpecWidth()) {
1100 case TypeSpecifierWidth::Short
:
1101 Result
= Context
.ShortFractTy
;
1103 case TypeSpecifierWidth::Unspecified
:
1104 Result
= Context
.FractTy
;
1106 case TypeSpecifierWidth::Long
:
1107 Result
= Context
.LongFractTy
;
1109 case TypeSpecifierWidth::LongLong
:
1110 llvm_unreachable("Unable to specify long long as _Fract width");
1113 if (DS
.getTypeSpecSign() == TypeSpecifierSign::Unsigned
)
1114 Result
= Context
.getCorrespondingUnsignedType(Result
);
1116 if (DS
.isTypeSpecSat())
1117 Result
= Context
.getCorrespondingSaturatedType(Result
);
1121 case DeclSpec::TST_int128
:
1122 if (!S
.Context
.getTargetInfo().hasInt128Type() &&
1123 !(S
.getLangOpts().SYCLIsDevice
|| S
.getLangOpts().CUDAIsDevice
||
1124 (S
.getLangOpts().OpenMP
&& S
.getLangOpts().OpenMPIsTargetDevice
)))
1125 S
.Diag(DS
.getTypeSpecTypeLoc(), diag::err_type_unsupported
)
1127 if (DS
.getTypeSpecSign() == TypeSpecifierSign::Unsigned
)
1128 Result
= Context
.UnsignedInt128Ty
;
1130 Result
= Context
.Int128Ty
;
1132 case DeclSpec::TST_float16
:
1133 // CUDA host and device may have different _Float16 support, therefore
1134 // do not diagnose _Float16 usage to avoid false alarm.
1135 // ToDo: more precise diagnostics for CUDA.
1136 if (!S
.Context
.getTargetInfo().hasFloat16Type() && !S
.getLangOpts().CUDA
&&
1137 !(S
.getLangOpts().OpenMP
&& S
.getLangOpts().OpenMPIsTargetDevice
))
1138 S
.Diag(DS
.getTypeSpecTypeLoc(), diag::err_type_unsupported
)
1140 Result
= Context
.Float16Ty
;
1142 case DeclSpec::TST_half
: Result
= Context
.HalfTy
; break;
1143 case DeclSpec::TST_BFloat16
:
1144 if (!S
.Context
.getTargetInfo().hasBFloat16Type() &&
1145 !(S
.getLangOpts().OpenMP
&& S
.getLangOpts().OpenMPIsTargetDevice
) &&
1146 !S
.getLangOpts().SYCLIsDevice
)
1147 S
.Diag(DS
.getTypeSpecTypeLoc(), diag::err_type_unsupported
) << "__bf16";
1148 Result
= Context
.BFloat16Ty
;
1150 case DeclSpec::TST_float
: Result
= Context
.FloatTy
; break;
1151 case DeclSpec::TST_double
:
1152 if (DS
.getTypeSpecWidth() == TypeSpecifierWidth::Long
)
1153 Result
= Context
.LongDoubleTy
;
1155 Result
= Context
.DoubleTy
;
1156 if (S
.getLangOpts().OpenCL
) {
1157 if (!S
.getOpenCLOptions().isSupported("cl_khr_fp64", S
.getLangOpts()))
1158 S
.Diag(DS
.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension
)
1160 << (S
.getLangOpts().getOpenCLCompatibleVersion() == 300
1161 ? "cl_khr_fp64 and __opencl_c_fp64"
1163 else if (!S
.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S
.getLangOpts()))
1164 S
.Diag(DS
.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma
);
1167 case DeclSpec::TST_float128
:
1168 if (!S
.Context
.getTargetInfo().hasFloat128Type() &&
1169 !S
.getLangOpts().SYCLIsDevice
&& !S
.getLangOpts().CUDAIsDevice
&&
1170 !(S
.getLangOpts().OpenMP
&& S
.getLangOpts().OpenMPIsTargetDevice
))
1171 S
.Diag(DS
.getTypeSpecTypeLoc(), diag::err_type_unsupported
)
1173 Result
= Context
.Float128Ty
;
1175 case DeclSpec::TST_ibm128
:
1176 if (!S
.Context
.getTargetInfo().hasIbm128Type() &&
1177 !S
.getLangOpts().SYCLIsDevice
&&
1178 !(S
.getLangOpts().OpenMP
&& S
.getLangOpts().OpenMPIsTargetDevice
))
1179 S
.Diag(DS
.getTypeSpecTypeLoc(), diag::err_type_unsupported
) << "__ibm128";
1180 Result
= Context
.Ibm128Ty
;
1182 case DeclSpec::TST_bool
:
1183 Result
= Context
.BoolTy
; // _Bool or bool
1185 case DeclSpec::TST_decimal32
: // _Decimal32
1186 case DeclSpec::TST_decimal64
: // _Decimal64
1187 case DeclSpec::TST_decimal128
: // _Decimal128
1188 S
.Diag(DS
.getTypeSpecTypeLoc(), diag::err_decimal_unsupported
);
1189 Result
= Context
.IntTy
;
1190 declarator
.setInvalidType(true);
1192 case DeclSpec::TST_class
:
1193 case DeclSpec::TST_enum
:
1194 case DeclSpec::TST_union
:
1195 case DeclSpec::TST_struct
:
1196 case DeclSpec::TST_interface
: {
1197 TagDecl
*D
= dyn_cast_or_null
<TagDecl
>(DS
.getRepAsDecl());
1199 // This can happen in C++ with ambiguous lookups.
1200 Result
= Context
.IntTy
;
1201 declarator
.setInvalidType(true);
1205 // If the type is deprecated or unavailable, diagnose it.
1206 S
.DiagnoseUseOfDecl(D
, DS
.getTypeSpecTypeNameLoc());
1208 assert(DS
.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified
&&
1209 DS
.getTypeSpecComplex() == 0 &&
1210 DS
.getTypeSpecSign() == TypeSpecifierSign::Unspecified
&&
1211 "No qualifiers on tag names!");
1213 // TypeQuals handled by caller.
1214 Result
= Context
.getTypeDeclType(D
);
1216 // In both C and C++, make an ElaboratedType.
1217 ElaboratedTypeKeyword Keyword
1218 = ElaboratedType::getKeywordForTypeSpec(DS
.getTypeSpecType());
1219 Result
= S
.getElaboratedType(Keyword
, DS
.getTypeSpecScope(), Result
,
1220 DS
.isTypeSpecOwned() ? D
: nullptr);
1223 case DeclSpec::TST_typename
: {
1224 assert(DS
.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified
&&
1225 DS
.getTypeSpecComplex() == 0 &&
1226 DS
.getTypeSpecSign() == TypeSpecifierSign::Unspecified
&&
1227 "Can't handle qualifiers on typedef names yet!");
1228 Result
= S
.GetTypeFromParser(DS
.getRepAsType());
1229 if (Result
.isNull()) {
1230 declarator
.setInvalidType(true);
1233 // TypeQuals handled by caller.
1236 case DeclSpec::TST_typeof_unqualType
:
1237 case DeclSpec::TST_typeofType
:
1238 // FIXME: Preserve type source info.
1239 Result
= S
.GetTypeFromParser(DS
.getRepAsType());
1240 assert(!Result
.isNull() && "Didn't get a type for typeof?");
1241 if (!Result
->isDependentType())
1242 if (const TagType
*TT
= Result
->getAs
<TagType
>())
1243 S
.DiagnoseUseOfDecl(TT
->getDecl(), DS
.getTypeSpecTypeLoc());
1244 // TypeQuals handled by caller.
1245 Result
= Context
.getTypeOfType(
1246 Result
, DS
.getTypeSpecType() == DeclSpec::TST_typeof_unqualType
1247 ? TypeOfKind::Unqualified
1248 : TypeOfKind::Qualified
);
1250 case DeclSpec::TST_typeof_unqualExpr
:
1251 case DeclSpec::TST_typeofExpr
: {
1252 Expr
*E
= DS
.getRepAsExpr();
1253 assert(E
&& "Didn't get an expression for typeof?");
1254 // TypeQuals handled by caller.
1255 Result
= S
.BuildTypeofExprType(E
, DS
.getTypeSpecType() ==
1256 DeclSpec::TST_typeof_unqualExpr
1257 ? TypeOfKind::Unqualified
1258 : TypeOfKind::Qualified
);
1259 if (Result
.isNull()) {
1260 Result
= Context
.IntTy
;
1261 declarator
.setInvalidType(true);
1265 case DeclSpec::TST_decltype
: {
1266 Expr
*E
= DS
.getRepAsExpr();
1267 assert(E
&& "Didn't get an expression for decltype?");
1268 // TypeQuals handled by caller.
1269 Result
= S
.BuildDecltypeType(E
);
1270 if (Result
.isNull()) {
1271 Result
= Context
.IntTy
;
1272 declarator
.setInvalidType(true);
1276 case DeclSpec::TST_typename_pack_indexing
: {
1277 Expr
*E
= DS
.getPackIndexingExpr();
1278 assert(E
&& "Didn't get an expression for pack indexing");
1279 QualType Pattern
= S
.GetTypeFromParser(DS
.getRepAsType());
1280 Result
= S
.BuildPackIndexingType(Pattern
, E
, DS
.getBeginLoc(),
1281 DS
.getEllipsisLoc());
1282 if (Result
.isNull()) {
1283 declarator
.setInvalidType(true);
1284 Result
= Context
.IntTy
;
1289 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1290 #include "clang/Basic/TransformTypeTraits.def"
1291 Result
= S
.GetTypeFromParser(DS
.getRepAsType());
1292 assert(!Result
.isNull() && "Didn't get a type for the transformation?");
1293 Result
= S
.BuildUnaryTransformType(
1294 Result
, TSTToUnaryTransformType(DS
.getTypeSpecType()),
1295 DS
.getTypeSpecTypeLoc());
1296 if (Result
.isNull()) {
1297 Result
= Context
.IntTy
;
1298 declarator
.setInvalidType(true);
1302 case DeclSpec::TST_auto
:
1303 case DeclSpec::TST_decltype_auto
: {
1304 auto AutoKW
= DS
.getTypeSpecType() == DeclSpec::TST_decltype_auto
1305 ? AutoTypeKeyword::DecltypeAuto
1306 : AutoTypeKeyword::Auto
;
1308 ConceptDecl
*TypeConstraintConcept
= nullptr;
1309 llvm::SmallVector
<TemplateArgument
, 8> TemplateArgs
;
1310 if (DS
.isConstrainedAuto()) {
1311 if (TemplateIdAnnotation
*TemplateId
= DS
.getRepAsTemplateId()) {
1312 TypeConstraintConcept
=
1313 cast
<ConceptDecl
>(TemplateId
->Template
.get().getAsTemplateDecl());
1314 TemplateArgumentListInfo TemplateArgsInfo
;
1315 TemplateArgsInfo
.setLAngleLoc(TemplateId
->LAngleLoc
);
1316 TemplateArgsInfo
.setRAngleLoc(TemplateId
->RAngleLoc
);
1317 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateId
->getTemplateArgs(),
1318 TemplateId
->NumArgs
);
1319 S
.translateTemplateArguments(TemplateArgsPtr
, TemplateArgsInfo
);
1320 for (const auto &ArgLoc
: TemplateArgsInfo
.arguments())
1321 TemplateArgs
.push_back(ArgLoc
.getArgument());
1323 declarator
.setInvalidType(true);
1326 Result
= S
.Context
.getAutoType(QualType(), AutoKW
,
1327 /*IsDependent*/ false, /*IsPack=*/false,
1328 TypeConstraintConcept
, TemplateArgs
);
1332 case DeclSpec::TST_auto_type
:
1333 Result
= Context
.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType
, false);
1336 case DeclSpec::TST_unknown_anytype
:
1337 Result
= Context
.UnknownAnyTy
;
1340 case DeclSpec::TST_atomic
:
1341 Result
= S
.GetTypeFromParser(DS
.getRepAsType());
1342 assert(!Result
.isNull() && "Didn't get a type for _Atomic?");
1343 Result
= S
.BuildAtomicType(Result
, DS
.getTypeSpecTypeLoc());
1344 if (Result
.isNull()) {
1345 Result
= Context
.IntTy
;
1346 declarator
.setInvalidType(true);
1350 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1351 case DeclSpec::TST_##ImgType##_t: \
1352 switch (getImageAccess(DS.getAttributes())) { \
1353 case OpenCLAccessAttr::Keyword_write_only: \
1354 Result = Context.Id##WOTy; \
1356 case OpenCLAccessAttr::Keyword_read_write: \
1357 Result = Context.Id##RWTy; \
1359 case OpenCLAccessAttr::Keyword_read_only: \
1360 Result = Context.Id##ROTy; \
1362 case OpenCLAccessAttr::SpellingNotCalculated: \
1363 llvm_unreachable("Spelling not yet calculated"); \
1366 #include "clang/Basic/OpenCLImageTypes.def"
1368 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1369 case DeclSpec::TST_##Name: \
1370 Result = Context.SingletonId; \
1372 #include "clang/Basic/HLSLIntangibleTypes.def"
1374 case DeclSpec::TST_error
:
1375 Result
= Context
.IntTy
;
1376 declarator
.setInvalidType(true);
1380 // FIXME: we want resulting declarations to be marked invalid, but claiming
1381 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1383 if (Result
->containsErrors())
1384 declarator
.setInvalidType();
1386 if (S
.getLangOpts().OpenCL
) {
1387 const auto &OpenCLOptions
= S
.getOpenCLOptions();
1388 bool IsOpenCLC30Compatible
=
1389 S
.getLangOpts().getOpenCLCompatibleVersion() == 300;
1390 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1392 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1393 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1394 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1395 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1396 // only when the optional feature is supported
1397 if ((Result
->isImageType() || Result
->isSamplerT()) &&
1398 (IsOpenCLC30Compatible
&&
1399 !OpenCLOptions
.isSupported("__opencl_c_images", S
.getLangOpts()))) {
1400 S
.Diag(DS
.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension
)
1401 << 0 << Result
<< "__opencl_c_images";
1402 declarator
.setInvalidType();
1403 } else if (Result
->isOCLImage3dWOType() &&
1404 !OpenCLOptions
.isSupported("cl_khr_3d_image_writes",
1406 S
.Diag(DS
.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension
)
1408 << (IsOpenCLC30Compatible
1409 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1410 : "cl_khr_3d_image_writes");
1411 declarator
.setInvalidType();
1415 bool IsFixedPointType
= DS
.getTypeSpecType() == DeclSpec::TST_accum
||
1416 DS
.getTypeSpecType() == DeclSpec::TST_fract
;
1418 // Only fixed point types can be saturated
1419 if (DS
.isTypeSpecSat() && !IsFixedPointType
)
1420 S
.Diag(DS
.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec
)
1421 << DS
.getSpecifierName(DS
.getTypeSpecType(),
1422 Context
.getPrintingPolicy());
1424 // Handle complex types.
1425 if (DS
.getTypeSpecComplex() == DeclSpec::TSC_complex
) {
1426 if (S
.getLangOpts().Freestanding
)
1427 S
.Diag(DS
.getTypeSpecComplexLoc(), diag::ext_freestanding_complex
);
1428 Result
= Context
.getComplexType(Result
);
1429 } else if (DS
.isTypeAltiVecVector()) {
1430 unsigned typeSize
= static_cast<unsigned>(Context
.getTypeSize(Result
));
1431 assert(typeSize
> 0 && "type size for vector must be greater than 0 bits");
1432 VectorKind VecKind
= VectorKind::AltiVecVector
;
1433 if (DS
.isTypeAltiVecPixel())
1434 VecKind
= VectorKind::AltiVecPixel
;
1435 else if (DS
.isTypeAltiVecBool())
1436 VecKind
= VectorKind::AltiVecBool
;
1437 Result
= Context
.getVectorType(Result
, 128/typeSize
, VecKind
);
1440 // _Imaginary was a feature of C99 through C23 but was never supported in
1441 // Clang. The feature was removed in C2y, but we retain the unsupported
1442 // diagnostic for an improved user experience.
1443 if (DS
.getTypeSpecComplex() == DeclSpec::TSC_imaginary
)
1444 S
.Diag(DS
.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported
);
1446 // Before we process any type attributes, synthesize a block literal
1447 // function declarator if necessary.
1448 if (declarator
.getContext() == DeclaratorContext::BlockLiteral
)
1449 maybeSynthesizeBlockSignature(state
, Result
);
1451 // Apply any type attributes from the decl spec. This may cause the
1452 // list of type attributes to be temporarily saved while the type
1453 // attributes are pushed around.
1454 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1455 if (!DS
.isTypeSpecPipe()) {
1456 // We also apply declaration attributes that "slide" to the decl spec.
1457 // Ordering can be important for attributes. The decalaration attributes
1458 // come syntactically before the decl spec attributes, so we process them
1460 ParsedAttributesView SlidingAttrs
;
1461 for (ParsedAttr
&AL
: declarator
.getDeclarationAttributes()) {
1462 if (AL
.slidesFromDeclToDeclSpecLegacyBehavior()) {
1463 SlidingAttrs
.addAtEnd(&AL
);
1465 // For standard syntax attributes, which would normally appertain to the
1466 // declaration here, suggest moving them to the type instead. But only
1467 // do this for our own vendor attributes; moving other vendors'
1468 // attributes might hurt portability.
1469 // There's one special case that we need to deal with here: The
1470 // `MatrixType` attribute may only be used in a typedef declaration. If
1471 // it's being used anywhere else, don't output the warning as
1472 // ProcessDeclAttributes() will output an error anyway.
1473 if (AL
.isStandardAttributeSyntax() && AL
.isClangScope() &&
1474 !(AL
.getKind() == ParsedAttr::AT_MatrixType
&&
1475 DS
.getStorageClassSpec() != DeclSpec::SCS_typedef
)) {
1476 S
.Diag(AL
.getLoc(), diag::warn_type_attribute_deprecated_on_decl
)
1481 // During this call to processTypeAttrs(),
1482 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1483 // reference to the DeclSpec attributes, rather than the declaration
1484 // attributes. However, this doesn't matter, as getCurrentAttributes()
1485 // is only called when distributing attributes from one attribute list
1486 // to another. Declaration attributes are always C++11 attributes, and these
1487 // are never distributed.
1488 processTypeAttrs(state
, Result
, TAL_DeclSpec
, SlidingAttrs
);
1489 processTypeAttrs(state
, Result
, TAL_DeclSpec
, DS
.getAttributes());
1492 // Apply const/volatile/restrict qualifiers to T.
1493 if (unsigned TypeQuals
= DS
.getTypeQualifiers()) {
1494 // Warn about CV qualifiers on function types.
1496 // If the specification of a function type includes any type qualifiers,
1497 // the behavior is undefined.
1498 // C2y changed this behavior to be implementation-defined. Clang defines
1499 // the behavior in all cases to ignore the qualifier, as in C++.
1500 // C++11 [dcl.fct]p7:
1501 // The effect of a cv-qualifier-seq in a function declarator is not the
1502 // same as adding cv-qualification on top of the function type. In the
1503 // latter case, the cv-qualifiers are ignored.
1504 if (Result
->isFunctionType()) {
1505 unsigned DiagId
= diag::warn_typecheck_function_qualifiers_ignored
;
1506 if (!S
.getLangOpts().CPlusPlus
&& !S
.getLangOpts().C2y
)
1507 DiagId
= diag::ext_typecheck_function_qualifiers_unspecified
;
1508 diagnoseAndRemoveTypeQualifiers(
1509 S
, DS
, TypeQuals
, Result
, DeclSpec::TQ_const
| DeclSpec::TQ_volatile
,
1511 // No diagnostic for 'restrict' or '_Atomic' applied to a
1512 // function type; we'll diagnose those later, in BuildQualifiedType.
1515 // C++11 [dcl.ref]p1:
1516 // Cv-qualified references are ill-formed except when the
1517 // cv-qualifiers are introduced through the use of a typedef-name
1518 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1520 // There don't appear to be any other contexts in which a cv-qualified
1521 // reference type could be formed, so the 'ill-formed' clause here appears
1523 if (TypeQuals
&& Result
->isReferenceType()) {
1524 diagnoseAndRemoveTypeQualifiers(
1525 S
, DS
, TypeQuals
, Result
,
1526 DeclSpec::TQ_const
| DeclSpec::TQ_volatile
| DeclSpec::TQ_atomic
,
1527 diag::warn_typecheck_reference_qualifiers
);
1530 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1531 // than once in the same specifier-list or qualifier-list, either directly
1532 // or via one or more typedefs."
1533 if (!S
.getLangOpts().C99
&& !S
.getLangOpts().CPlusPlus
1534 && TypeQuals
& Result
.getCVRQualifiers()) {
1535 if (TypeQuals
& DeclSpec::TQ_const
&& Result
.isConstQualified()) {
1536 S
.Diag(DS
.getConstSpecLoc(), diag::ext_duplicate_declspec
)
1540 if (TypeQuals
& DeclSpec::TQ_volatile
&& Result
.isVolatileQualified()) {
1541 S
.Diag(DS
.getVolatileSpecLoc(), diag::ext_duplicate_declspec
)
1545 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1546 // produce a warning in this case.
1549 QualType Qualified
= S
.BuildQualifiedType(Result
, DeclLoc
, TypeQuals
, &DS
);
1551 // If adding qualifiers fails, just use the unqualified type.
1552 if (Qualified
.isNull())
1553 declarator
.setInvalidType(true);
1558 if (S
.getLangOpts().HLSL
)
1559 Result
= S
.HLSL().ProcessResourceTypeAttributes(Result
);
1561 assert(!Result
.isNull() && "This function should not return a null type");
1565 static std::string
getPrintableNameForEntity(DeclarationName Entity
) {
1567 return Entity
.getAsString();
1572 static bool isDependentOrGNUAutoType(QualType T
) {
1573 if (T
->isDependentType())
1576 const auto *AT
= dyn_cast
<AutoType
>(T
);
1577 return AT
&& AT
->isGNUAutoType();
1580 QualType
Sema::BuildQualifiedType(QualType T
, SourceLocation Loc
,
1581 Qualifiers Qs
, const DeclSpec
*DS
) {
1585 // Ignore any attempt to form a cv-qualified reference.
1586 if (T
->isReferenceType()) {
1588 Qs
.removeVolatile();
1591 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1592 // object or incomplete types shall not be restrict-qualified."
1593 if (Qs
.hasRestrict()) {
1594 unsigned DiagID
= 0;
1597 if (T
->isAnyPointerType() || T
->isReferenceType() ||
1598 T
->isMemberPointerType()) {
1600 if (T
->isObjCObjectPointerType())
1602 else if (const MemberPointerType
*PTy
= T
->getAs
<MemberPointerType
>())
1603 EltTy
= PTy
->getPointeeType();
1605 EltTy
= T
->getPointeeType();
1607 // If we have a pointer or reference, the pointee must have an object
1609 if (!EltTy
->isIncompleteOrObjectType()) {
1610 DiagID
= diag::err_typecheck_invalid_restrict_invalid_pointee
;
1613 } else if (!isDependentOrGNUAutoType(T
)) {
1614 // For an __auto_type variable, we may not have seen the initializer yet
1615 // and so have no idea whether the underlying type is a pointer type or
1617 DiagID
= diag::err_typecheck_invalid_restrict_not_pointer
;
1622 Diag(DS
? DS
->getRestrictSpecLoc() : Loc
, DiagID
) << ProblemTy
;
1623 Qs
.removeRestrict();
1627 return Context
.getQualifiedType(T
, Qs
);
1630 QualType
Sema::BuildQualifiedType(QualType T
, SourceLocation Loc
,
1631 unsigned CVRAU
, const DeclSpec
*DS
) {
1635 // Ignore any attempt to form a cv-qualified reference.
1636 if (T
->isReferenceType())
1638 ~(DeclSpec::TQ_const
| DeclSpec::TQ_volatile
| DeclSpec::TQ_atomic
);
1640 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1642 unsigned CVR
= CVRAU
& ~(DeclSpec::TQ_atomic
| DeclSpec::TQ_unaligned
);
1645 // If the same qualifier appears more than once in the same
1646 // specifier-qualifier-list, either directly or via one or more typedefs,
1647 // the behavior is the same as if it appeared only once.
1649 // It's not specified what happens when the _Atomic qualifier is applied to
1650 // a type specified with the _Atomic specifier, but we assume that this
1651 // should be treated as if the _Atomic qualifier appeared multiple times.
1652 if (CVRAU
& DeclSpec::TQ_atomic
&& !T
->isAtomicType()) {
1654 // If other qualifiers appear along with the _Atomic qualifier in a
1655 // specifier-qualifier-list, the resulting type is the so-qualified
1658 // Don't need to worry about array types here, since _Atomic can't be
1659 // applied to such types.
1660 SplitQualType Split
= T
.getSplitUnqualifiedType();
1661 T
= BuildAtomicType(QualType(Split
.Ty
, 0),
1662 DS
? DS
->getAtomicSpecLoc() : Loc
);
1665 Split
.Quals
.addCVRQualifiers(CVR
);
1666 return BuildQualifiedType(T
, Loc
, Split
.Quals
);
1669 Qualifiers Q
= Qualifiers::fromCVRMask(CVR
);
1670 Q
.setUnaligned(CVRAU
& DeclSpec::TQ_unaligned
);
1671 return BuildQualifiedType(T
, Loc
, Q
, DS
);
1674 QualType
Sema::BuildParenType(QualType T
) {
1675 return Context
.getParenType(T
);
1678 /// Given that we're building a pointer or reference to the given
1679 static QualType
inferARCLifetimeForPointee(Sema
&S
, QualType type
,
1682 // Bail out if retention is unrequired or already specified.
1683 if (!type
->isObjCLifetimeType() ||
1684 type
.getObjCLifetime() != Qualifiers::OCL_None
)
1687 Qualifiers::ObjCLifetime implicitLifetime
= Qualifiers::OCL_None
;
1689 // If the object type is const-qualified, we can safely use
1690 // __unsafe_unretained. This is safe (because there are no read
1691 // barriers), and it'll be safe to coerce anything but __weak* to
1692 // the resulting type.
1693 if (type
.isConstQualified()) {
1694 implicitLifetime
= Qualifiers::OCL_ExplicitNone
;
1696 // Otherwise, check whether the static type does not require
1697 // retaining. This currently only triggers for Class (possibly
1698 // protocol-qualifed, and arrays thereof).
1699 } else if (type
->isObjCARCImplicitlyUnretainedType()) {
1700 implicitLifetime
= Qualifiers::OCL_ExplicitNone
;
1702 // If we are in an unevaluated context, like sizeof, skip adding a
1704 } else if (S
.isUnevaluatedContext()) {
1707 // If that failed, give an error and recover using __strong. __strong
1708 // is the option most likely to prevent spurious second-order diagnostics,
1709 // like when binding a reference to a field.
1711 // These types can show up in private ivars in system headers, so
1712 // we need this to not be an error in those cases. Instead we
1714 if (S
.DelayedDiagnostics
.shouldDelayDiagnostics()) {
1715 S
.DelayedDiagnostics
.add(
1716 sema::DelayedDiagnostic::makeForbiddenType(loc
,
1717 diag::err_arc_indirect_no_ownership
, type
, isReference
));
1719 S
.Diag(loc
, diag::err_arc_indirect_no_ownership
) << type
<< isReference
;
1721 implicitLifetime
= Qualifiers::OCL_Strong
;
1723 assert(implicitLifetime
&& "didn't infer any lifetime!");
1726 qs
.addObjCLifetime(implicitLifetime
);
1727 return S
.Context
.getQualifiedType(type
, qs
);
1730 static std::string
getFunctionQualifiersAsString(const FunctionProtoType
*FnTy
){
1731 std::string Quals
= FnTy
->getMethodQuals().getAsString();
1733 switch (FnTy
->getRefQualifier()) {
1754 /// Kinds of declarator that cannot contain a qualified function type.
1756 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1757 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1758 /// at the topmost level of a type.
1760 /// Parens and member pointers are permitted. We don't diagnose array and
1761 /// function declarators, because they don't allow function types at all.
1763 /// The values of this enum are used in diagnostics.
1764 enum QualifiedFunctionKind
{ QFK_BlockPointer
, QFK_Pointer
, QFK_Reference
};
1765 } // end anonymous namespace
1767 /// Check whether the type T is a qualified function type, and if it is,
1768 /// diagnose that it cannot be contained within the given kind of declarator.
1769 static bool checkQualifiedFunction(Sema
&S
, QualType T
, SourceLocation Loc
,
1770 QualifiedFunctionKind QFK
) {
1771 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1772 const FunctionProtoType
*FPT
= T
->getAs
<FunctionProtoType
>();
1774 (FPT
->getMethodQuals().empty() && FPT
->getRefQualifier() == RQ_None
))
1777 S
.Diag(Loc
, diag::err_compound_qualified_function_type
)
1778 << QFK
<< isa
<FunctionType
>(T
.IgnoreParens()) << T
1779 << getFunctionQualifiersAsString(FPT
);
1783 bool Sema::CheckQualifiedFunctionForTypeId(QualType T
, SourceLocation Loc
) {
1784 const FunctionProtoType
*FPT
= T
->getAs
<FunctionProtoType
>();
1786 (FPT
->getMethodQuals().empty() && FPT
->getRefQualifier() == RQ_None
))
1789 Diag(Loc
, diag::err_qualified_function_typeid
)
1790 << T
<< getFunctionQualifiersAsString(FPT
);
1794 // Helper to deduce addr space of a pointee type in OpenCL mode.
1795 static QualType
deduceOpenCLPointeeAddrSpace(Sema
&S
, QualType PointeeType
) {
1796 if (!PointeeType
->isUndeducedAutoType() && !PointeeType
->isDependentType() &&
1797 !PointeeType
->isSamplerT() &&
1798 !PointeeType
.hasAddressSpace())
1799 PointeeType
= S
.getASTContext().getAddrSpaceQualType(
1800 PointeeType
, S
.getASTContext().getDefaultOpenCLPointeeAddrSpace());
1804 QualType
Sema::BuildPointerType(QualType T
,
1805 SourceLocation Loc
, DeclarationName Entity
) {
1806 if (T
->isReferenceType()) {
1807 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1808 Diag(Loc
, diag::err_illegal_decl_pointer_to_reference
)
1809 << getPrintableNameForEntity(Entity
) << T
;
1813 if (T
->isFunctionType() && getLangOpts().OpenCL
&&
1814 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1816 Diag(Loc
, diag::err_opencl_function_pointer
) << /*pointer*/ 0;
1820 if (getLangOpts().HLSL
&& Loc
.isValid()) {
1821 Diag(Loc
, diag::err_hlsl_pointers_unsupported
) << 0;
1825 if (checkQualifiedFunction(*this, T
, Loc
, QFK_Pointer
))
1828 assert(!T
->isObjCObjectType() && "Should build ObjCObjectPointerType");
1830 // In ARC, it is forbidden to build pointers to unqualified pointers.
1831 if (getLangOpts().ObjCAutoRefCount
)
1832 T
= inferARCLifetimeForPointee(*this, T
, Loc
, /*reference*/ false);
1834 if (getLangOpts().OpenCL
)
1835 T
= deduceOpenCLPointeeAddrSpace(*this, T
);
1837 // In WebAssembly, pointers to reference types and pointers to tables are
1839 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
1840 if (T
.isWebAssemblyReferenceType()) {
1841 Diag(Loc
, diag::err_wasm_reference_pr
) << 0;
1845 // We need to desugar the type here in case T is a ParenType.
1846 if (T
->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
1847 Diag(Loc
, diag::err_wasm_table_pr
) << 0;
1852 // Build the pointer type.
1853 return Context
.getPointerType(T
);
1856 QualType
Sema::BuildReferenceType(QualType T
, bool SpelledAsLValue
,
1858 DeclarationName Entity
) {
1859 assert(Context
.getCanonicalType(T
) != Context
.OverloadTy
&&
1860 "Unresolved overloaded function type");
1862 // C++0x [dcl.ref]p6:
1863 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1864 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1865 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1866 // the type "lvalue reference to T", while an attempt to create the type
1867 // "rvalue reference to cv TR" creates the type TR.
1868 bool LValueRef
= SpelledAsLValue
|| T
->getAs
<LValueReferenceType
>();
1870 // C++ [dcl.ref]p4: There shall be no references to references.
1872 // According to C++ DR 106, references to references are only
1873 // diagnosed when they are written directly (e.g., "int & &"),
1874 // but not when they happen via a typedef:
1876 // typedef int& intref;
1877 // typedef intref& intref2;
1879 // Parser::ParseDeclaratorInternal diagnoses the case where
1880 // references are written directly; here, we handle the
1881 // collapsing of references-to-references as described in C++0x.
1882 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1885 // A declarator that specifies the type "reference to cv void"
1887 if (T
->isVoidType()) {
1888 Diag(Loc
, diag::err_reference_to_void
);
1892 if (getLangOpts().HLSL
&& Loc
.isValid()) {
1893 Diag(Loc
, diag::err_hlsl_pointers_unsupported
) << 1;
1897 if (checkQualifiedFunction(*this, T
, Loc
, QFK_Reference
))
1900 if (T
->isFunctionType() && getLangOpts().OpenCL
&&
1901 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1903 Diag(Loc
, diag::err_opencl_function_pointer
) << /*reference*/ 1;
1907 // In ARC, it is forbidden to build references to unqualified pointers.
1908 if (getLangOpts().ObjCAutoRefCount
)
1909 T
= inferARCLifetimeForPointee(*this, T
, Loc
, /*reference*/ true);
1911 if (getLangOpts().OpenCL
)
1912 T
= deduceOpenCLPointeeAddrSpace(*this, T
);
1914 // In WebAssembly, references to reference types and tables are illegal.
1915 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
1916 T
.isWebAssemblyReferenceType()) {
1917 Diag(Loc
, diag::err_wasm_reference_pr
) << 1;
1920 if (T
->isWebAssemblyTableType()) {
1921 Diag(Loc
, diag::err_wasm_table_pr
) << 1;
1925 // Handle restrict on references.
1927 return Context
.getLValueReferenceType(T
, SpelledAsLValue
);
1928 return Context
.getRValueReferenceType(T
);
1931 QualType
Sema::BuildReadPipeType(QualType T
, SourceLocation Loc
) {
1932 return Context
.getReadPipeType(T
);
1935 QualType
Sema::BuildWritePipeType(QualType T
, SourceLocation Loc
) {
1936 return Context
.getWritePipeType(T
);
1939 QualType
Sema::BuildBitIntType(bool IsUnsigned
, Expr
*BitWidth
,
1940 SourceLocation Loc
) {
1941 if (BitWidth
->isInstantiationDependent())
1942 return Context
.getDependentBitIntType(IsUnsigned
, BitWidth
);
1944 llvm::APSInt
Bits(32);
1946 VerifyIntegerConstantExpression(BitWidth
, &Bits
, /*FIXME*/ AllowFold
);
1948 if (ICE
.isInvalid())
1951 size_t NumBits
= Bits
.getZExtValue();
1952 if (!IsUnsigned
&& NumBits
< 2) {
1953 Diag(Loc
, diag::err_bit_int_bad_size
) << 0;
1957 if (IsUnsigned
&& NumBits
< 1) {
1958 Diag(Loc
, diag::err_bit_int_bad_size
) << 1;
1962 const TargetInfo
&TI
= getASTContext().getTargetInfo();
1963 if (NumBits
> TI
.getMaxBitIntWidth()) {
1964 Diag(Loc
, diag::err_bit_int_max_size
)
1965 << IsUnsigned
<< static_cast<uint64_t>(TI
.getMaxBitIntWidth());
1969 return Context
.getBitIntType(IsUnsigned
, NumBits
);
1972 /// Check whether the specified array bound can be evaluated using the relevant
1973 /// language rules. If so, returns the possibly-converted expression and sets
1974 /// SizeVal to the size. If not, but the expression might be a VLA bound,
1975 /// returns ExprResult(). Otherwise, produces a diagnostic and returns
1977 static ExprResult
checkArraySize(Sema
&S
, Expr
*&ArraySize
,
1978 llvm::APSInt
&SizeVal
, unsigned VLADiag
,
1980 if (S
.getLangOpts().CPlusPlus14
&&
1982 !ArraySize
->getType()->isIntegralOrUnscopedEnumerationType())) {
1983 // C++14 [dcl.array]p1:
1984 // The constant-expression shall be a converted constant expression of
1985 // type std::size_t.
1987 // Don't apply this rule if we might be forming a VLA: in that case, we
1988 // allow non-constant expressions and constant-folding. We only need to use
1989 // the converted constant expression rules (to properly convert the source)
1990 // when the source expression is of class type.
1991 return S
.CheckConvertedConstantExpression(
1992 ArraySize
, S
.Context
.getSizeType(), SizeVal
, Sema::CCEK_ArrayBound
);
1995 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1996 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1997 class VLADiagnoser
: public Sema::VerifyICEDiagnoser
{
2003 VLADiagnoser(unsigned VLADiag
, bool VLAIsError
)
2004 : VLADiag(VLADiag
), VLAIsError(VLAIsError
) {}
2006 Sema::SemaDiagnosticBuilder
diagnoseNotICEType(Sema
&S
, SourceLocation Loc
,
2007 QualType T
) override
{
2008 return S
.Diag(Loc
, diag::err_array_size_non_int
) << T
;
2011 Sema::SemaDiagnosticBuilder
diagnoseNotICE(Sema
&S
,
2012 SourceLocation Loc
) override
{
2013 IsVLA
= !VLAIsError
;
2014 return S
.Diag(Loc
, VLADiag
);
2017 Sema::SemaDiagnosticBuilder
diagnoseFold(Sema
&S
,
2018 SourceLocation Loc
) override
{
2019 return S
.Diag(Loc
, diag::ext_vla_folded_to_constant
);
2021 } Diagnoser(VLADiag
, VLAIsError
);
2024 S
.VerifyIntegerConstantExpression(ArraySize
, &SizeVal
, Diagnoser
);
2025 if (Diagnoser
.IsVLA
)
2026 return ExprResult();
2030 bool Sema::checkArrayElementAlignment(QualType EltTy
, SourceLocation Loc
) {
2031 EltTy
= Context
.getBaseElementType(EltTy
);
2032 if (EltTy
->isIncompleteType() || EltTy
->isDependentType() ||
2033 EltTy
->isUndeducedType())
2036 CharUnits Size
= Context
.getTypeSizeInChars(EltTy
);
2037 CharUnits Alignment
= Context
.getTypeAlignInChars(EltTy
);
2039 if (Size
.isMultipleOf(Alignment
))
2042 Diag(Loc
, diag::err_array_element_alignment
)
2043 << EltTy
<< Size
.getQuantity() << Alignment
.getQuantity();
2047 QualType
Sema::BuildArrayType(QualType T
, ArraySizeModifier ASM
,
2048 Expr
*ArraySize
, unsigned Quals
,
2049 SourceRange Brackets
, DeclarationName Entity
) {
2051 SourceLocation Loc
= Brackets
.getBegin();
2052 if (getLangOpts().CPlusPlus
) {
2053 // C++ [dcl.array]p1:
2054 // T is called the array element type; this type shall not be a reference
2055 // type, the (possibly cv-qualified) type void, a function type or an
2056 // abstract class type.
2058 // C++ [dcl.array]p3:
2059 // When several "array of" specifications are adjacent, [...] only the
2060 // first of the constant expressions that specify the bounds of the arrays
2063 // Note: function types are handled in the common path with C.
2064 if (T
->isReferenceType()) {
2065 Diag(Loc
, diag::err_illegal_decl_array_of_references
)
2066 << getPrintableNameForEntity(Entity
) << T
;
2070 if (T
->isVoidType() || T
->isIncompleteArrayType()) {
2071 Diag(Loc
, diag::err_array_incomplete_or_sizeless_type
) << 0 << T
;
2075 if (RequireNonAbstractType(Brackets
.getBegin(), T
,
2076 diag::err_array_of_abstract_type
))
2079 // Mentioning a member pointer type for an array type causes us to lock in
2080 // an inheritance model, even if it's inside an unused typedef.
2081 if (Context
.getTargetInfo().getCXXABI().isMicrosoft())
2082 if (const MemberPointerType
*MPTy
= T
->getAs
<MemberPointerType
>())
2083 if (!MPTy
->getClass()->isDependentType())
2084 (void)isCompleteType(Loc
, T
);
2087 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2088 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2089 if (!T
.isWebAssemblyReferenceType() &&
2090 RequireCompleteSizedType(Loc
, T
,
2091 diag::err_array_incomplete_or_sizeless_type
))
2095 // Multi-dimensional arrays of WebAssembly references are not allowed.
2096 if (Context
.getTargetInfo().getTriple().isWasm() && T
->isArrayType()) {
2097 const auto *ATy
= dyn_cast
<ArrayType
>(T
);
2098 if (ATy
&& ATy
->getElementType().isWebAssemblyReferenceType()) {
2099 Diag(Loc
, diag::err_wasm_reftype_multidimensional_array
);
2104 if (T
->isSizelessType() && !T
.isWebAssemblyReferenceType()) {
2105 Diag(Loc
, diag::err_array_incomplete_or_sizeless_type
) << 1 << T
;
2109 if (T
->isFunctionType()) {
2110 Diag(Loc
, diag::err_illegal_decl_array_of_functions
)
2111 << getPrintableNameForEntity(Entity
) << T
;
2115 if (const RecordType
*EltTy
= T
->getAs
<RecordType
>()) {
2116 // If the element type is a struct or union that contains a variadic
2117 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2118 if (EltTy
->getDecl()->hasFlexibleArrayMember())
2119 Diag(Loc
, diag::ext_flexible_array_in_array
) << T
;
2120 } else if (T
->isObjCObjectType()) {
2121 Diag(Loc
, diag::err_objc_array_of_interfaces
) << T
;
2125 if (!checkArrayElementAlignment(T
, Loc
))
2128 // Do placeholder conversions on the array size expression.
2129 if (ArraySize
&& ArraySize
->hasPlaceholderType()) {
2130 ExprResult Result
= CheckPlaceholderExpr(ArraySize
);
2131 if (Result
.isInvalid()) return QualType();
2132 ArraySize
= Result
.get();
2135 // Do lvalue-to-rvalue conversions on the array size expression.
2136 if (ArraySize
&& !ArraySize
->isPRValue()) {
2137 ExprResult Result
= DefaultLvalueConversion(ArraySize
);
2138 if (Result
.isInvalid())
2141 ArraySize
= Result
.get();
2144 // C99 6.7.5.2p1: The size expression shall have integer type.
2145 // C++11 allows contextual conversions to such types.
2146 if (!getLangOpts().CPlusPlus11
&&
2147 ArraySize
&& !ArraySize
->isTypeDependent() &&
2148 !ArraySize
->getType()->isIntegralOrUnscopedEnumerationType()) {
2149 Diag(ArraySize
->getBeginLoc(), diag::err_array_size_non_int
)
2150 << ArraySize
->getType() << ArraySize
->getSourceRange();
2154 auto IsStaticAssertLike
= [](const Expr
*ArraySize
, ASTContext
&Context
) {
2158 // If the array size expression is a conditional expression whose branches
2159 // are both integer constant expressions, one negative and one positive,
2160 // then it's assumed to be like an old-style static assertion. e.g.,
2161 // int old_style_assert[expr ? 1 : -1];
2162 // We will accept any integer constant expressions instead of assuming the
2163 // values 1 and -1 are always used.
2164 if (const auto *CondExpr
= dyn_cast_if_present
<ConditionalOperator
>(
2165 ArraySize
->IgnoreParenImpCasts())) {
2166 std::optional
<llvm::APSInt
> LHS
=
2167 CondExpr
->getLHS()->getIntegerConstantExpr(Context
);
2168 std::optional
<llvm::APSInt
> RHS
=
2169 CondExpr
->getRHS()->getIntegerConstantExpr(Context
);
2170 return LHS
&& RHS
&& LHS
->isNegative() != RHS
->isNegative();
2175 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2178 if (getLangOpts().OpenCL
) {
2179 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2180 VLADiag
= diag::err_opencl_vla
;
2182 } else if (getLangOpts().C99
) {
2183 VLADiag
= diag::warn_vla_used
;
2185 } else if (isSFINAEContext()) {
2186 VLADiag
= diag::err_vla_in_sfinae
;
2188 } else if (getLangOpts().OpenMP
&& OpenMP().isInOpenMPTaskUntiedContext()) {
2189 VLADiag
= diag::err_openmp_vla_in_task_untied
;
2191 } else if (getLangOpts().CPlusPlus
) {
2192 if (getLangOpts().CPlusPlus11
&& IsStaticAssertLike(ArraySize
, Context
))
2193 VLADiag
= getLangOpts().GNUMode
2194 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2195 : diag::ext_vla_cxx_static_assert
;
2197 VLADiag
= getLangOpts().GNUMode
? diag::ext_vla_cxx_in_gnu_mode
2198 : diag::ext_vla_cxx
;
2201 VLADiag
= diag::ext_vla
;
2205 llvm::APSInt
ConstVal(Context
.getTypeSize(Context
.getSizeType()));
2207 if (ASM
== ArraySizeModifier::Star
) {
2212 T
= Context
.getVariableArrayType(T
, nullptr, ASM
, Quals
, Brackets
);
2214 T
= Context
.getIncompleteArrayType(T
, ASM
, Quals
);
2216 } else if (ArraySize
->isTypeDependent() || ArraySize
->isValueDependent()) {
2217 T
= Context
.getDependentSizedArrayType(T
, ArraySize
, ASM
, Quals
, Brackets
);
2220 checkArraySize(*this, ArraySize
, ConstVal
, VLADiag
, VLAIsError
);
2224 if (!R
.isUsable()) {
2225 // C99: an array with a non-ICE size is a VLA. We accept any expression
2226 // that we can fold to a non-zero positive value as a non-VLA as an
2228 T
= Context
.getVariableArrayType(T
, ArraySize
, ASM
, Quals
, Brackets
);
2229 } else if (!T
->isDependentType() && !T
->isIncompleteType() &&
2230 !T
->isConstantSizeType()) {
2231 // C99: an array with an element type that has a non-constant-size is a
2233 // FIXME: Add a note to explain why this isn't a VLA.
2237 T
= Context
.getVariableArrayType(T
, ArraySize
, ASM
, Quals
, Brackets
);
2239 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2240 // have a value greater than zero.
2241 // In C++, this follows from narrowing conversions being disallowed.
2242 if (ConstVal
.isSigned() && ConstVal
.isNegative()) {
2244 Diag(ArraySize
->getBeginLoc(), diag::err_decl_negative_array_size
)
2245 << getPrintableNameForEntity(Entity
)
2246 << ArraySize
->getSourceRange();
2248 Diag(ArraySize
->getBeginLoc(),
2249 diag::err_typecheck_negative_array_size
)
2250 << ArraySize
->getSourceRange();
2253 if (ConstVal
== 0 && !T
.isWebAssemblyReferenceType()) {
2254 // GCC accepts zero sized static arrays. We allow them when
2255 // we're not in a SFINAE context.
2256 Diag(ArraySize
->getBeginLoc(),
2257 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2258 : diag::ext_typecheck_zero_array_size
)
2259 << 0 << ArraySize
->getSourceRange();
2262 // Is the array too large?
2263 unsigned ActiveSizeBits
=
2264 (!T
->isDependentType() && !T
->isVariablyModifiedType() &&
2265 !T
->isIncompleteType() && !T
->isUndeducedType())
2266 ? ConstantArrayType::getNumAddressingBits(Context
, T
, ConstVal
)
2267 : ConstVal
.getActiveBits();
2268 if (ActiveSizeBits
> ConstantArrayType::getMaxSizeBits(Context
)) {
2269 Diag(ArraySize
->getBeginLoc(), diag::err_array_too_large
)
2270 << toString(ConstVal
, 10) << ArraySize
->getSourceRange();
2274 T
= Context
.getConstantArrayType(T
, ConstVal
, ArraySize
, ASM
, Quals
);
2278 if (T
->isVariableArrayType()) {
2279 if (!Context
.getTargetInfo().isVLASupported()) {
2280 // CUDA device code and some other targets don't support VLAs.
2281 bool IsCUDADevice
= (getLangOpts().CUDA
&& getLangOpts().CUDAIsDevice
);
2283 IsCUDADevice
? diag::err_cuda_vla
: diag::err_vla_unsupported
)
2284 << (IsCUDADevice
? llvm::to_underlying(CUDA().CurrentTarget()) : 0);
2285 } else if (sema::FunctionScopeInfo
*FSI
= getCurFunction()) {
2286 // VLAs are supported on this target, but we may need to do delayed
2287 // checking that the VLA is not being used within a coroutine.
2288 FSI
->setHasVLA(Loc
);
2292 // If this is not C99, diagnose array size modifiers on non-VLAs.
2293 if (!getLangOpts().C99
&& !T
->isVariableArrayType() &&
2294 (ASM
!= ArraySizeModifier::Normal
|| Quals
!= 0)) {
2295 Diag(Loc
, getLangOpts().CPlusPlus
? diag::err_c99_array_usage_cxx
2296 : diag::ext_c99_array_usage
)
2297 << llvm::to_underlying(ASM
);
2300 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2301 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2302 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2303 if (getLangOpts().OpenCL
) {
2304 const QualType ArrType
= Context
.getBaseElementType(T
);
2305 if (ArrType
->isBlockPointerType() || ArrType
->isPipeType() ||
2306 ArrType
->isSamplerT() || ArrType
->isImageType()) {
2307 Diag(Loc
, diag::err_opencl_invalid_type_array
) << ArrType
;
2315 QualType
Sema::BuildVectorType(QualType CurType
, Expr
*SizeExpr
,
2316 SourceLocation AttrLoc
) {
2317 // The base type must be integer (not Boolean or enumeration) or float, and
2318 // can't already be a vector.
2319 if ((!CurType
->isDependentType() &&
2320 (!CurType
->isBuiltinType() || CurType
->isBooleanType() ||
2321 (!CurType
->isIntegerType() && !CurType
->isRealFloatingType())) &&
2322 !CurType
->isBitIntType()) ||
2323 CurType
->isArrayType()) {
2324 Diag(AttrLoc
, diag::err_attribute_invalid_vector_type
) << CurType
;
2327 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2328 if (const auto *BIT
= CurType
->getAs
<BitIntType
>()) {
2329 unsigned NumBits
= BIT
->getNumBits();
2330 if (!llvm::isPowerOf2_32(NumBits
) || NumBits
< 8) {
2331 Diag(AttrLoc
, diag::err_attribute_invalid_bitint_vector_type
)
2337 if (SizeExpr
->isTypeDependent() || SizeExpr
->isValueDependent())
2338 return Context
.getDependentVectorType(CurType
, SizeExpr
, AttrLoc
,
2339 VectorKind::Generic
);
2341 std::optional
<llvm::APSInt
> VecSize
=
2342 SizeExpr
->getIntegerConstantExpr(Context
);
2344 Diag(AttrLoc
, diag::err_attribute_argument_type
)
2345 << "vector_size" << AANT_ArgumentIntegerConstant
2346 << SizeExpr
->getSourceRange();
2350 if (CurType
->isDependentType())
2351 return Context
.getDependentVectorType(CurType
, SizeExpr
, AttrLoc
,
2352 VectorKind::Generic
);
2354 // vecSize is specified in bytes - convert to bits.
2355 if (!VecSize
->isIntN(61)) {
2356 // Bit size will overflow uint64.
2357 Diag(AttrLoc
, diag::err_attribute_size_too_large
)
2358 << SizeExpr
->getSourceRange() << "vector";
2361 uint64_t VectorSizeBits
= VecSize
->getZExtValue() * 8;
2362 unsigned TypeSize
= static_cast<unsigned>(Context
.getTypeSize(CurType
));
2364 if (VectorSizeBits
== 0) {
2365 Diag(AttrLoc
, diag::err_attribute_zero_size
)
2366 << SizeExpr
->getSourceRange() << "vector";
2370 if (!TypeSize
|| VectorSizeBits
% TypeSize
) {
2371 Diag(AttrLoc
, diag::err_attribute_invalid_size
)
2372 << SizeExpr
->getSourceRange();
2376 if (VectorSizeBits
/ TypeSize
> std::numeric_limits
<uint32_t>::max()) {
2377 Diag(AttrLoc
, diag::err_attribute_size_too_large
)
2378 << SizeExpr
->getSourceRange() << "vector";
2382 return Context
.getVectorType(CurType
, VectorSizeBits
/ TypeSize
,
2383 VectorKind::Generic
);
2386 QualType
Sema::BuildExtVectorType(QualType T
, Expr
*ArraySize
,
2387 SourceLocation AttrLoc
) {
2388 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2389 // in conjunction with complex types (pointers, arrays, functions, etc.).
2391 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2392 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2393 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2394 // of bool aren't allowed.
2396 // We explicitly allow bool elements in ext_vector_type for C/C++.
2397 bool IsNoBoolVecLang
= getLangOpts().OpenCL
|| getLangOpts().OpenCLCPlusPlus
;
2398 if ((!T
->isDependentType() && !T
->isIntegerType() &&
2399 !T
->isRealFloatingType()) ||
2400 (IsNoBoolVecLang
&& T
->isBooleanType())) {
2401 Diag(AttrLoc
, diag::err_attribute_invalid_vector_type
) << T
;
2405 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2406 if (T
->isBitIntType()) {
2407 unsigned NumBits
= T
->castAs
<BitIntType
>()->getNumBits();
2408 if (!llvm::isPowerOf2_32(NumBits
) || NumBits
< 8) {
2409 Diag(AttrLoc
, diag::err_attribute_invalid_bitint_vector_type
)
2415 if (!ArraySize
->isTypeDependent() && !ArraySize
->isValueDependent()) {
2416 std::optional
<llvm::APSInt
> vecSize
=
2417 ArraySize
->getIntegerConstantExpr(Context
);
2419 Diag(AttrLoc
, diag::err_attribute_argument_type
)
2420 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2421 << ArraySize
->getSourceRange();
2425 if (!vecSize
->isIntN(32)) {
2426 Diag(AttrLoc
, diag::err_attribute_size_too_large
)
2427 << ArraySize
->getSourceRange() << "vector";
2430 // Unlike gcc's vector_size attribute, the size is specified as the
2431 // number of elements, not the number of bytes.
2432 unsigned vectorSize
= static_cast<unsigned>(vecSize
->getZExtValue());
2434 if (vectorSize
== 0) {
2435 Diag(AttrLoc
, diag::err_attribute_zero_size
)
2436 << ArraySize
->getSourceRange() << "vector";
2440 return Context
.getExtVectorType(T
, vectorSize
);
2443 return Context
.getDependentSizedExtVectorType(T
, ArraySize
, AttrLoc
);
2446 QualType
Sema::BuildMatrixType(QualType ElementTy
, Expr
*NumRows
, Expr
*NumCols
,
2447 SourceLocation AttrLoc
) {
2448 assert(Context
.getLangOpts().MatrixTypes
&&
2449 "Should never build a matrix type when it is disabled");
2451 // Check element type, if it is not dependent.
2452 if (!ElementTy
->isDependentType() &&
2453 !MatrixType::isValidElementType(ElementTy
)) {
2454 Diag(AttrLoc
, diag::err_attribute_invalid_matrix_type
) << ElementTy
;
2458 if (NumRows
->isTypeDependent() || NumCols
->isTypeDependent() ||
2459 NumRows
->isValueDependent() || NumCols
->isValueDependent())
2460 return Context
.getDependentSizedMatrixType(ElementTy
, NumRows
, NumCols
,
2463 std::optional
<llvm::APSInt
> ValueRows
=
2464 NumRows
->getIntegerConstantExpr(Context
);
2465 std::optional
<llvm::APSInt
> ValueColumns
=
2466 NumCols
->getIntegerConstantExpr(Context
);
2468 auto const RowRange
= NumRows
->getSourceRange();
2469 auto const ColRange
= NumCols
->getSourceRange();
2471 // Both are row and column expressions are invalid.
2472 if (!ValueRows
&& !ValueColumns
) {
2473 Diag(AttrLoc
, diag::err_attribute_argument_type
)
2474 << "matrix_type" << AANT_ArgumentIntegerConstant
<< RowRange
2479 // Only the row expression is invalid.
2481 Diag(AttrLoc
, diag::err_attribute_argument_type
)
2482 << "matrix_type" << AANT_ArgumentIntegerConstant
<< RowRange
;
2486 // Only the column expression is invalid.
2487 if (!ValueColumns
) {
2488 Diag(AttrLoc
, diag::err_attribute_argument_type
)
2489 << "matrix_type" << AANT_ArgumentIntegerConstant
<< ColRange
;
2493 // Check the matrix dimensions.
2494 unsigned MatrixRows
= static_cast<unsigned>(ValueRows
->getZExtValue());
2495 unsigned MatrixColumns
= static_cast<unsigned>(ValueColumns
->getZExtValue());
2496 if (MatrixRows
== 0 && MatrixColumns
== 0) {
2497 Diag(AttrLoc
, diag::err_attribute_zero_size
)
2498 << "matrix" << RowRange
<< ColRange
;
2501 if (MatrixRows
== 0) {
2502 Diag(AttrLoc
, diag::err_attribute_zero_size
) << "matrix" << RowRange
;
2505 if (MatrixColumns
== 0) {
2506 Diag(AttrLoc
, diag::err_attribute_zero_size
) << "matrix" << ColRange
;
2509 if (!ConstantMatrixType::isDimensionValid(MatrixRows
)) {
2510 Diag(AttrLoc
, diag::err_attribute_size_too_large
)
2511 << RowRange
<< "matrix row";
2514 if (!ConstantMatrixType::isDimensionValid(MatrixColumns
)) {
2515 Diag(AttrLoc
, diag::err_attribute_size_too_large
)
2516 << ColRange
<< "matrix column";
2519 return Context
.getConstantMatrixType(ElementTy
, MatrixRows
, MatrixColumns
);
2522 bool Sema::CheckFunctionReturnType(QualType T
, SourceLocation Loc
) {
2523 if (T
->isArrayType() || T
->isFunctionType()) {
2524 Diag(Loc
, diag::err_func_returning_array_function
)
2525 << T
->isFunctionType() << T
;
2529 // Functions cannot return half FP.
2530 if (T
->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns
&&
2531 !Context
.getTargetInfo().allowHalfArgsAndReturns()) {
2532 Diag(Loc
, diag::err_parameters_retval_cannot_have_fp16_type
) << 1 <<
2533 FixItHint::CreateInsertion(Loc
, "*");
2537 // Methods cannot return interface types. All ObjC objects are
2538 // passed by reference.
2539 if (T
->isObjCObjectType()) {
2540 Diag(Loc
, diag::err_object_cannot_be_passed_returned_by_value
)
2541 << 0 << T
<< FixItHint::CreateInsertion(Loc
, "*");
2545 if (T
.hasNonTrivialToPrimitiveDestructCUnion() ||
2546 T
.hasNonTrivialToPrimitiveCopyCUnion())
2547 checkNonTrivialCUnion(T
, Loc
, NTCUC_FunctionReturn
,
2548 NTCUK_Destruct
|NTCUK_Copy
);
2550 // C++2a [dcl.fct]p12:
2551 // A volatile-qualified return type is deprecated
2552 if (T
.isVolatileQualified() && getLangOpts().CPlusPlus20
)
2553 Diag(Loc
, diag::warn_deprecated_volatile_return
) << T
;
2555 if (T
.getAddressSpace() != LangAS::Default
&& getLangOpts().HLSL
)
2560 /// Check the extended parameter information. Most of the necessary
2561 /// checking should occur when applying the parameter attribute; the
2562 /// only other checks required are positional restrictions.
2563 static void checkExtParameterInfos(Sema
&S
, ArrayRef
<QualType
> paramTypes
,
2564 const FunctionProtoType::ExtProtoInfo
&EPI
,
2565 llvm::function_ref
<SourceLocation(unsigned)> getParamLoc
) {
2566 assert(EPI
.ExtParameterInfos
&& "shouldn't get here without param infos");
2568 bool emittedError
= false;
2569 auto actualCC
= EPI
.ExtInfo
.getCC();
2570 enum class RequiredCC
{ OnlySwift
, SwiftOrSwiftAsync
};
2571 auto checkCompatible
= [&](unsigned paramIndex
, RequiredCC required
) {
2573 (required
== RequiredCC::OnlySwift
)
2574 ? (actualCC
== CC_Swift
)
2575 : (actualCC
== CC_Swift
|| actualCC
== CC_SwiftAsync
);
2576 if (isCompatible
|| emittedError
)
2578 S
.Diag(getParamLoc(paramIndex
), diag::err_swift_param_attr_not_swiftcall
)
2579 << getParameterABISpelling(EPI
.ExtParameterInfos
[paramIndex
].getABI())
2580 << (required
== RequiredCC::OnlySwift
);
2581 emittedError
= true;
2583 for (size_t paramIndex
= 0, numParams
= paramTypes
.size();
2584 paramIndex
!= numParams
; ++paramIndex
) {
2585 switch (EPI
.ExtParameterInfos
[paramIndex
].getABI()) {
2586 // Nothing interesting to check for orindary-ABI parameters.
2587 case ParameterABI::Ordinary
:
2588 case ParameterABI::HLSLOut
:
2589 case ParameterABI::HLSLInOut
:
2592 // swift_indirect_result parameters must be a prefix of the function
2594 case ParameterABI::SwiftIndirectResult
:
2595 checkCompatible(paramIndex
, RequiredCC::SwiftOrSwiftAsync
);
2596 if (paramIndex
!= 0 &&
2597 EPI
.ExtParameterInfos
[paramIndex
- 1].getABI()
2598 != ParameterABI::SwiftIndirectResult
) {
2599 S
.Diag(getParamLoc(paramIndex
),
2600 diag::err_swift_indirect_result_not_first
);
2604 case ParameterABI::SwiftContext
:
2605 checkCompatible(paramIndex
, RequiredCC::SwiftOrSwiftAsync
);
2608 // SwiftAsyncContext is not limited to swiftasynccall functions.
2609 case ParameterABI::SwiftAsyncContext
:
2612 // swift_error parameters must be preceded by a swift_context parameter.
2613 case ParameterABI::SwiftErrorResult
:
2614 checkCompatible(paramIndex
, RequiredCC::OnlySwift
);
2615 if (paramIndex
== 0 ||
2616 EPI
.ExtParameterInfos
[paramIndex
- 1].getABI() !=
2617 ParameterABI::SwiftContext
) {
2618 S
.Diag(getParamLoc(paramIndex
),
2619 diag::err_swift_error_result_not_after_swift_context
);
2623 llvm_unreachable("bad ABI kind");
2627 QualType
Sema::BuildFunctionType(QualType T
,
2628 MutableArrayRef
<QualType
> ParamTypes
,
2629 SourceLocation Loc
, DeclarationName Entity
,
2630 const FunctionProtoType::ExtProtoInfo
&EPI
) {
2631 bool Invalid
= false;
2633 Invalid
|= CheckFunctionReturnType(T
, Loc
);
2635 for (unsigned Idx
= 0, Cnt
= ParamTypes
.size(); Idx
< Cnt
; ++Idx
) {
2636 // FIXME: Loc is too inprecise here, should use proper locations for args.
2637 QualType ParamType
= Context
.getAdjustedParameterType(ParamTypes
[Idx
]);
2638 if (ParamType
->isVoidType()) {
2639 Diag(Loc
, diag::err_param_with_void_type
);
2641 } else if (ParamType
->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns
&&
2642 !Context
.getTargetInfo().allowHalfArgsAndReturns()) {
2643 // Disallow half FP arguments.
2644 Diag(Loc
, diag::err_parameters_retval_cannot_have_fp16_type
) << 0 <<
2645 FixItHint::CreateInsertion(Loc
, "*");
2647 } else if (ParamType
->isWebAssemblyTableType()) {
2648 Diag(Loc
, diag::err_wasm_table_as_function_parameter
);
2652 // C++2a [dcl.fct]p4:
2653 // A parameter with volatile-qualified type is deprecated
2654 if (ParamType
.isVolatileQualified() && getLangOpts().CPlusPlus20
)
2655 Diag(Loc
, diag::warn_deprecated_volatile_param
) << ParamType
;
2657 ParamTypes
[Idx
] = ParamType
;
2660 if (EPI
.ExtParameterInfos
) {
2661 checkExtParameterInfos(*this, ParamTypes
, EPI
,
2662 [=](unsigned i
) { return Loc
; });
2665 if (EPI
.ExtInfo
.getProducesResult()) {
2666 // This is just a warning, so we can't fail to build if we see it.
2667 ObjC().checkNSReturnsRetainedReturnType(Loc
, T
);
2673 return Context
.getFunctionType(T
, ParamTypes
, EPI
);
2676 QualType
Sema::BuildMemberPointerType(QualType T
, QualType Class
,
2678 DeclarationName Entity
) {
2679 // Verify that we're not building a pointer to pointer to function with
2680 // exception specification.
2681 if (CheckDistantExceptionSpec(T
)) {
2682 Diag(Loc
, diag::err_distant_exception_spec
);
2686 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2687 // with reference type, or "cv void."
2688 if (T
->isReferenceType()) {
2689 Diag(Loc
, diag::err_illegal_decl_mempointer_to_reference
)
2690 << getPrintableNameForEntity(Entity
) << T
;
2694 if (T
->isVoidType()) {
2695 Diag(Loc
, diag::err_illegal_decl_mempointer_to_void
)
2696 << getPrintableNameForEntity(Entity
);
2700 if (!Class
->isDependentType() && !Class
->isRecordType()) {
2701 Diag(Loc
, diag::err_mempointer_in_nonclass_type
) << Class
;
2705 if (T
->isFunctionType() && getLangOpts().OpenCL
&&
2706 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2708 Diag(Loc
, diag::err_opencl_function_pointer
) << /*pointer*/ 0;
2712 if (getLangOpts().HLSL
&& Loc
.isValid()) {
2713 Diag(Loc
, diag::err_hlsl_pointers_unsupported
) << 0;
2717 // Adjust the default free function calling convention to the default method
2718 // calling convention.
2720 (Entity
.getNameKind() == DeclarationName::CXXConstructorName
) ||
2721 (Entity
.getNameKind() == DeclarationName::CXXDestructorName
);
2722 if (T
->isFunctionType())
2723 adjustMemberFunctionCC(T
, /*HasThisPointer=*/true, IsCtorOrDtor
, Loc
);
2725 return Context
.getMemberPointerType(T
, Class
.getTypePtr());
2728 QualType
Sema::BuildBlockPointerType(QualType T
,
2730 DeclarationName Entity
) {
2731 if (!T
->isFunctionType()) {
2732 Diag(Loc
, diag::err_nonfunction_block_type
);
2736 if (checkQualifiedFunction(*this, T
, Loc
, QFK_BlockPointer
))
2739 if (getLangOpts().OpenCL
)
2740 T
= deduceOpenCLPointeeAddrSpace(*this, T
);
2742 return Context
.getBlockPointerType(T
);
2745 QualType
Sema::GetTypeFromParser(ParsedType Ty
, TypeSourceInfo
**TInfo
) {
2746 QualType QT
= Ty
.get();
2748 if (TInfo
) *TInfo
= nullptr;
2752 TypeSourceInfo
*DI
= nullptr;
2753 if (const LocInfoType
*LIT
= dyn_cast
<LocInfoType
>(QT
)) {
2754 QT
= LIT
->getType();
2755 DI
= LIT
->getTypeSourceInfo();
2758 if (TInfo
) *TInfo
= DI
;
2762 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState
&state
,
2763 Qualifiers::ObjCLifetime ownership
,
2764 unsigned chunkIndex
);
2766 /// Given that this is the declaration of a parameter under ARC,
2767 /// attempt to infer attributes and such for pointer-to-whatever
2769 static void inferARCWriteback(TypeProcessingState
&state
,
2770 QualType
&declSpecType
) {
2771 Sema
&S
= state
.getSema();
2772 Declarator
&declarator
= state
.getDeclarator();
2774 // TODO: should we care about decl qualifiers?
2776 // Check whether the declarator has the expected form. We walk
2777 // from the inside out in order to make the block logic work.
2778 unsigned outermostPointerIndex
= 0;
2779 bool isBlockPointer
= false;
2780 unsigned numPointers
= 0;
2781 for (unsigned i
= 0, e
= declarator
.getNumTypeObjects(); i
!= e
; ++i
) {
2782 unsigned chunkIndex
= i
;
2783 DeclaratorChunk
&chunk
= declarator
.getTypeObject(chunkIndex
);
2784 switch (chunk
.Kind
) {
2785 case DeclaratorChunk::Paren
:
2789 case DeclaratorChunk::Reference
:
2790 case DeclaratorChunk::Pointer
:
2791 // Count the number of pointers. Treat references
2792 // interchangeably as pointers; if they're mis-ordered, normal
2793 // type building will discover that.
2794 outermostPointerIndex
= chunkIndex
;
2798 case DeclaratorChunk::BlockPointer
:
2799 // If we have a pointer to block pointer, that's an acceptable
2800 // indirect reference; anything else is not an application of
2802 if (numPointers
!= 1) return;
2804 outermostPointerIndex
= chunkIndex
;
2805 isBlockPointer
= true;
2807 // We don't care about pointer structure in return values here.
2810 case DeclaratorChunk::Array
: // suppress if written (id[])?
2811 case DeclaratorChunk::Function
:
2812 case DeclaratorChunk::MemberPointer
:
2813 case DeclaratorChunk::Pipe
:
2819 // If we have *one* pointer, then we want to throw the qualifier on
2820 // the declaration-specifiers, which means that it needs to be a
2821 // retainable object type.
2822 if (numPointers
== 1) {
2823 // If it's not a retainable object type, the rule doesn't apply.
2824 if (!declSpecType
->isObjCRetainableType()) return;
2826 // If it already has lifetime, don't do anything.
2827 if (declSpecType
.getObjCLifetime()) return;
2829 // Otherwise, modify the type in-place.
2832 if (declSpecType
->isObjCARCImplicitlyUnretainedType())
2833 qs
.addObjCLifetime(Qualifiers::OCL_ExplicitNone
);
2835 qs
.addObjCLifetime(Qualifiers::OCL_Autoreleasing
);
2836 declSpecType
= S
.Context
.getQualifiedType(declSpecType
, qs
);
2838 // If we have *two* pointers, then we want to throw the qualifier on
2839 // the outermost pointer.
2840 } else if (numPointers
== 2) {
2841 // If we don't have a block pointer, we need to check whether the
2842 // declaration-specifiers gave us something that will turn into a
2843 // retainable object pointer after we slap the first pointer on it.
2844 if (!isBlockPointer
&& !declSpecType
->isObjCObjectType())
2847 // Look for an explicit lifetime attribute there.
2848 DeclaratorChunk
&chunk
= declarator
.getTypeObject(outermostPointerIndex
);
2849 if (chunk
.Kind
!= DeclaratorChunk::Pointer
&&
2850 chunk
.Kind
!= DeclaratorChunk::BlockPointer
)
2852 for (const ParsedAttr
&AL
: chunk
.getAttrs())
2853 if (AL
.getKind() == ParsedAttr::AT_ObjCOwnership
)
2856 transferARCOwnershipToDeclaratorChunk(state
, Qualifiers::OCL_Autoreleasing
,
2857 outermostPointerIndex
);
2859 // Any other number of pointers/references does not trigger the rule.
2862 // TODO: mark whether we did this inference?
2865 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID
, unsigned Quals
,
2866 SourceLocation FallbackLoc
,
2867 SourceLocation ConstQualLoc
,
2868 SourceLocation VolatileQualLoc
,
2869 SourceLocation RestrictQualLoc
,
2870 SourceLocation AtomicQualLoc
,
2871 SourceLocation UnalignedQualLoc
) {
2879 } const QualKinds
[5] = {
2880 { "const", DeclSpec::TQ_const
, ConstQualLoc
},
2881 { "volatile", DeclSpec::TQ_volatile
, VolatileQualLoc
},
2882 { "restrict", DeclSpec::TQ_restrict
, RestrictQualLoc
},
2883 { "__unaligned", DeclSpec::TQ_unaligned
, UnalignedQualLoc
},
2884 { "_Atomic", DeclSpec::TQ_atomic
, AtomicQualLoc
}
2887 SmallString
<32> QualStr
;
2888 unsigned NumQuals
= 0;
2890 FixItHint FixIts
[5];
2892 // Build a string naming the redundant qualifiers.
2893 for (auto &E
: QualKinds
) {
2894 if (Quals
& E
.Mask
) {
2895 if (!QualStr
.empty()) QualStr
+= ' ';
2898 // If we have a location for the qualifier, offer a fixit.
2899 SourceLocation QualLoc
= E
.Loc
;
2900 if (QualLoc
.isValid()) {
2901 FixIts
[NumQuals
] = FixItHint::CreateRemoval(QualLoc
);
2902 if (Loc
.isInvalid() ||
2903 getSourceManager().isBeforeInTranslationUnit(QualLoc
, Loc
))
2911 Diag(Loc
.isInvalid() ? FallbackLoc
: Loc
, DiagID
)
2912 << QualStr
<< NumQuals
<< FixIts
[0] << FixIts
[1] << FixIts
[2] << FixIts
[3];
2915 // Diagnose pointless type qualifiers on the return type of a function.
2916 static void diagnoseRedundantReturnTypeQualifiers(Sema
&S
, QualType RetTy
,
2918 unsigned FunctionChunkIndex
) {
2919 const DeclaratorChunk::FunctionTypeInfo
&FTI
=
2920 D
.getTypeObject(FunctionChunkIndex
).Fun
;
2921 if (FTI
.hasTrailingReturnType()) {
2922 S
.diagnoseIgnoredQualifiers(diag::warn_qual_return_type
,
2923 RetTy
.getLocalCVRQualifiers(),
2924 FTI
.getTrailingReturnTypeLoc());
2928 for (unsigned OuterChunkIndex
= FunctionChunkIndex
+ 1,
2929 End
= D
.getNumTypeObjects();
2930 OuterChunkIndex
!= End
; ++OuterChunkIndex
) {
2931 DeclaratorChunk
&OuterChunk
= D
.getTypeObject(OuterChunkIndex
);
2932 switch (OuterChunk
.Kind
) {
2933 case DeclaratorChunk::Paren
:
2936 case DeclaratorChunk::Pointer
: {
2937 DeclaratorChunk::PointerTypeInfo
&PTI
= OuterChunk
.Ptr
;
2938 S
.diagnoseIgnoredQualifiers(
2939 diag::warn_qual_return_type
,
2943 PTI
.VolatileQualLoc
,
2944 PTI
.RestrictQualLoc
,
2946 PTI
.UnalignedQualLoc
);
2950 case DeclaratorChunk::Function
:
2951 case DeclaratorChunk::BlockPointer
:
2952 case DeclaratorChunk::Reference
:
2953 case DeclaratorChunk::Array
:
2954 case DeclaratorChunk::MemberPointer
:
2955 case DeclaratorChunk::Pipe
:
2956 // FIXME: We can't currently provide an accurate source location and a
2957 // fix-it hint for these.
2958 unsigned AtomicQual
= RetTy
->isAtomicType() ? DeclSpec::TQ_atomic
: 0;
2959 S
.diagnoseIgnoredQualifiers(diag::warn_qual_return_type
,
2960 RetTy
.getCVRQualifiers() | AtomicQual
,
2961 D
.getIdentifierLoc());
2965 llvm_unreachable("unknown declarator chunk kind");
2968 // If the qualifiers come from a conversion function type, don't diagnose
2969 // them -- they're not necessarily redundant, since such a conversion
2970 // operator can be explicitly called as "x.operator const int()".
2971 if (D
.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId
)
2974 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2975 // which are present there.
2976 S
.diagnoseIgnoredQualifiers(diag::warn_qual_return_type
,
2977 D
.getDeclSpec().getTypeQualifiers(),
2978 D
.getIdentifierLoc(),
2979 D
.getDeclSpec().getConstSpecLoc(),
2980 D
.getDeclSpec().getVolatileSpecLoc(),
2981 D
.getDeclSpec().getRestrictSpecLoc(),
2982 D
.getDeclSpec().getAtomicSpecLoc(),
2983 D
.getDeclSpec().getUnalignedSpecLoc());
2986 static std::pair
<QualType
, TypeSourceInfo
*>
2987 InventTemplateParameter(TypeProcessingState
&state
, QualType T
,
2988 TypeSourceInfo
*TrailingTSI
, AutoType
*Auto
,
2989 InventedTemplateParameterInfo
&Info
) {
2990 Sema
&S
= state
.getSema();
2991 Declarator
&D
= state
.getDeclarator();
2993 const unsigned TemplateParameterDepth
= Info
.AutoTemplateParameterDepth
;
2994 const unsigned AutoParameterPosition
= Info
.TemplateParams
.size();
2995 const bool IsParameterPack
= D
.hasEllipsis();
2997 // If auto is mentioned in a lambda parameter or abbreviated function
2998 // template context, convert it to a template parameter type.
3000 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3001 // template parameter type. Template parameters are temporarily added
3002 // to the TU until the associated TemplateDecl is created.
3003 TemplateTypeParmDecl
*InventedTemplateParam
=
3004 TemplateTypeParmDecl::Create(
3005 S
.Context
, S
.Context
.getTranslationUnitDecl(),
3006 /*KeyLoc=*/D
.getDeclSpec().getTypeSpecTypeLoc(),
3007 /*NameLoc=*/D
.getIdentifierLoc(),
3008 TemplateParameterDepth
, AutoParameterPosition
,
3009 S
.InventAbbreviatedTemplateParameterTypeName(
3010 D
.getIdentifier(), AutoParameterPosition
), false,
3011 IsParameterPack
, /*HasTypeConstraint=*/Auto
->isConstrained());
3012 InventedTemplateParam
->setImplicit();
3013 Info
.TemplateParams
.push_back(InventedTemplateParam
);
3015 // Attach type constraints to the new parameter.
3016 if (Auto
->isConstrained()) {
3018 // The 'auto' appears in a trailing return type we've already built;
3019 // extract its type constraints to attach to the template parameter.
3020 AutoTypeLoc AutoLoc
= TrailingTSI
->getTypeLoc().getContainedAutoTypeLoc();
3021 TemplateArgumentListInfo
TAL(AutoLoc
.getLAngleLoc(), AutoLoc
.getRAngleLoc());
3022 bool Invalid
= false;
3023 for (unsigned Idx
= 0; Idx
< AutoLoc
.getNumArgs(); ++Idx
) {
3024 if (D
.getEllipsisLoc().isInvalid() && !Invalid
&&
3025 S
.DiagnoseUnexpandedParameterPack(AutoLoc
.getArgLoc(Idx
),
3026 Sema::UPPC_TypeConstraint
))
3028 TAL
.addArgument(AutoLoc
.getArgLoc(Idx
));
3032 S
.AttachTypeConstraint(
3033 AutoLoc
.getNestedNameSpecifierLoc(), AutoLoc
.getConceptNameInfo(),
3034 AutoLoc
.getNamedConcept(), /*FoundDecl=*/AutoLoc
.getFoundDecl(),
3035 AutoLoc
.hasExplicitTemplateArgs() ? &TAL
: nullptr,
3036 InventedTemplateParam
,
3037 S
.Context
.getTypeDeclType(InventedTemplateParam
),
3038 D
.getEllipsisLoc());
3041 // The 'auto' appears in the decl-specifiers; we've not finished forming
3042 // TypeSourceInfo for it yet.
3043 TemplateIdAnnotation
*TemplateId
= D
.getDeclSpec().getRepAsTemplateId();
3044 TemplateArgumentListInfo
TemplateArgsInfo(TemplateId
->LAngleLoc
,
3045 TemplateId
->RAngleLoc
);
3046 bool Invalid
= false;
3047 if (TemplateId
->LAngleLoc
.isValid()) {
3048 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateId
->getTemplateArgs(),
3049 TemplateId
->NumArgs
);
3050 S
.translateTemplateArguments(TemplateArgsPtr
, TemplateArgsInfo
);
3052 if (D
.getEllipsisLoc().isInvalid()) {
3053 for (TemplateArgumentLoc Arg
: TemplateArgsInfo
.arguments()) {
3054 if (S
.DiagnoseUnexpandedParameterPack(Arg
,
3055 Sema::UPPC_TypeConstraint
)) {
3063 UsingShadowDecl
*USD
=
3064 TemplateId
->Template
.get().getAsUsingShadowDecl();
3066 cast
<ConceptDecl
>(TemplateId
->Template
.get().getAsTemplateDecl());
3067 S
.AttachTypeConstraint(
3068 D
.getDeclSpec().getTypeSpecScope().getWithLocInContext(S
.Context
),
3069 DeclarationNameInfo(DeclarationName(TemplateId
->Name
),
3070 TemplateId
->TemplateNameLoc
),
3073 USD
? cast
<NamedDecl
>(USD
) : CD
,
3074 TemplateId
->LAngleLoc
.isValid() ? &TemplateArgsInfo
: nullptr,
3075 InventedTemplateParam
,
3076 S
.Context
.getTypeDeclType(InventedTemplateParam
),
3077 D
.getEllipsisLoc());
3082 // Replace the 'auto' in the function parameter with this invented
3083 // template type parameter.
3084 // FIXME: Retain some type sugar to indicate that this was written
3086 QualType
Replacement(InventedTemplateParam
->getTypeForDecl(), 0);
3087 QualType NewT
= state
.ReplaceAutoType(T
, Replacement
);
3088 TypeSourceInfo
*NewTSI
=
3089 TrailingTSI
? S
.ReplaceAutoTypeSourceInfo(TrailingTSI
, Replacement
)
3091 return {NewT
, NewTSI
};
3094 static TypeSourceInfo
*
3095 GetTypeSourceInfoForDeclarator(TypeProcessingState
&State
,
3096 QualType T
, TypeSourceInfo
*ReturnTypeInfo
);
3098 static QualType
GetDeclSpecTypeForDeclarator(TypeProcessingState
&state
,
3099 TypeSourceInfo
*&ReturnTypeInfo
) {
3100 Sema
&SemaRef
= state
.getSema();
3101 Declarator
&D
= state
.getDeclarator();
3103 ReturnTypeInfo
= nullptr;
3105 // The TagDecl owned by the DeclSpec.
3106 TagDecl
*OwnedTagDecl
= nullptr;
3108 switch (D
.getName().getKind()) {
3109 case UnqualifiedIdKind::IK_ImplicitSelfParam
:
3110 case UnqualifiedIdKind::IK_OperatorFunctionId
:
3111 case UnqualifiedIdKind::IK_Identifier
:
3112 case UnqualifiedIdKind::IK_LiteralOperatorId
:
3113 case UnqualifiedIdKind::IK_TemplateId
:
3114 T
= ConvertDeclSpecToType(state
);
3116 if (!D
.isInvalidType() && D
.getDeclSpec().isTypeSpecOwned()) {
3117 OwnedTagDecl
= cast
<TagDecl
>(D
.getDeclSpec().getRepAsDecl());
3118 // Owned declaration is embedded in declarator.
3119 OwnedTagDecl
->setEmbeddedInDeclarator(true);
3123 case UnqualifiedIdKind::IK_ConstructorName
:
3124 case UnqualifiedIdKind::IK_ConstructorTemplateId
:
3125 case UnqualifiedIdKind::IK_DestructorName
:
3126 // Constructors and destructors don't have return types. Use
3128 T
= SemaRef
.Context
.VoidTy
;
3129 processTypeAttrs(state
, T
, TAL_DeclSpec
,
3130 D
.getMutableDeclSpec().getAttributes());
3133 case UnqualifiedIdKind::IK_DeductionGuideName
:
3134 // Deduction guides have a trailing return type and no type in their
3135 // decl-specifier sequence. Use a placeholder return type for now.
3136 T
= SemaRef
.Context
.DependentTy
;
3139 case UnqualifiedIdKind::IK_ConversionFunctionId
:
3140 // The result type of a conversion function is the type that it
3142 T
= SemaRef
.GetTypeFromParser(D
.getName().ConversionFunctionId
,
3147 // Note: We don't need to distribute declaration attributes (i.e.
3148 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3149 // and those don't get distributed.
3150 distributeTypeAttrsFromDeclarator(
3151 state
, T
, SemaRef
.CUDA().IdentifyTarget(D
.getAttributes()));
3153 // Find the deduced type in this type. Look in the trailing return type if we
3154 // have one, otherwise in the DeclSpec type.
3155 // FIXME: The standard wording doesn't currently describe this.
3156 DeducedType
*Deduced
= T
->getContainedDeducedType();
3157 bool DeducedIsTrailingReturnType
= false;
3158 if (Deduced
&& isa
<AutoType
>(Deduced
) && D
.hasTrailingReturnType()) {
3159 QualType T
= SemaRef
.GetTypeFromParser(D
.getTrailingReturnType());
3160 Deduced
= T
.isNull() ? nullptr : T
->getContainedDeducedType();
3161 DeducedIsTrailingReturnType
= true;
3164 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3166 AutoType
*Auto
= dyn_cast
<AutoType
>(Deduced
);
3169 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3170 // class template argument deduction)?
3171 bool IsCXXAutoType
=
3172 (Auto
&& Auto
->getKeyword() != AutoTypeKeyword::GNUAutoType
);
3173 bool IsDeducedReturnType
= false;
3175 switch (D
.getContext()) {
3176 case DeclaratorContext::LambdaExpr
:
3177 // Declared return type of a lambda-declarator is implicit and is always
3180 case DeclaratorContext::ObjCParameter
:
3181 case DeclaratorContext::ObjCResult
:
3184 case DeclaratorContext::RequiresExpr
:
3187 case DeclaratorContext::Prototype
:
3188 case DeclaratorContext::LambdaExprParameter
: {
3189 InventedTemplateParameterInfo
*Info
= nullptr;
3190 if (D
.getContext() == DeclaratorContext::Prototype
) {
3191 // With concepts we allow 'auto' in function parameters.
3192 if (!SemaRef
.getLangOpts().CPlusPlus20
|| !Auto
||
3193 Auto
->getKeyword() != AutoTypeKeyword::Auto
) {
3196 } else if (!SemaRef
.getCurScope()->isFunctionDeclarationScope()) {
3201 Info
= &SemaRef
.InventedParameterInfos
.back();
3203 // In C++14, generic lambdas allow 'auto' in their parameters.
3204 if (!SemaRef
.getLangOpts().CPlusPlus14
&& Auto
&&
3205 Auto
->getKeyword() == AutoTypeKeyword::Auto
) {
3206 Error
= 25; // auto not allowed in lambda parameter (before C++14)
3208 } else if (!Auto
|| Auto
->getKeyword() != AutoTypeKeyword::Auto
) {
3209 Error
= 16; // __auto_type or decltype(auto) not allowed in lambda
3213 Info
= SemaRef
.getCurLambda();
3214 assert(Info
&& "No LambdaScopeInfo on the stack!");
3217 // We'll deal with inventing template parameters for 'auto' in trailing
3218 // return types when we pick up the trailing return type when processing
3219 // the function chunk.
3220 if (!DeducedIsTrailingReturnType
)
3221 T
= InventTemplateParameter(state
, T
, nullptr, Auto
, *Info
).first
;
3224 case DeclaratorContext::Member
: {
3225 if (D
.isStaticMember() || D
.isFunctionDeclarator())
3227 bool Cxx
= SemaRef
.getLangOpts().CPlusPlus
;
3228 if (isa
<ObjCContainerDecl
>(SemaRef
.CurContext
)) {
3229 Error
= 6; // Interface member.
3231 switch (cast
<TagDecl
>(SemaRef
.CurContext
)->getTagKind()) {
3232 case TagTypeKind::Enum
:
3233 llvm_unreachable("unhandled tag kind");
3234 case TagTypeKind::Struct
:
3235 Error
= Cxx
? 1 : 2; /* Struct member */
3237 case TagTypeKind::Union
:
3238 Error
= Cxx
? 3 : 4; /* Union member */
3240 case TagTypeKind::Class
:
3241 Error
= 5; /* Class member */
3243 case TagTypeKind::Interface
:
3244 Error
= 6; /* Interface member */
3248 if (D
.getDeclSpec().isFriendSpecified())
3249 Error
= 20; // Friend type
3252 case DeclaratorContext::CXXCatch
:
3253 case DeclaratorContext::ObjCCatch
:
3254 Error
= 7; // Exception declaration
3256 case DeclaratorContext::TemplateParam
:
3257 if (isa
<DeducedTemplateSpecializationType
>(Deduced
) &&
3258 !SemaRef
.getLangOpts().CPlusPlus20
)
3259 Error
= 19; // Template parameter (until C++20)
3260 else if (!SemaRef
.getLangOpts().CPlusPlus17
)
3261 Error
= 8; // Template parameter (until C++17)
3263 case DeclaratorContext::BlockLiteral
:
3264 Error
= 9; // Block literal
3266 case DeclaratorContext::TemplateArg
:
3267 // Within a template argument list, a deduced template specialization
3268 // type will be reinterpreted as a template template argument.
3269 if (isa
<DeducedTemplateSpecializationType
>(Deduced
) &&
3270 !D
.getNumTypeObjects() &&
3271 D
.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier
)
3274 case DeclaratorContext::TemplateTypeArg
:
3275 Error
= 10; // Template type argument
3277 case DeclaratorContext::AliasDecl
:
3278 case DeclaratorContext::AliasTemplate
:
3279 Error
= 12; // Type alias
3281 case DeclaratorContext::TrailingReturn
:
3282 case DeclaratorContext::TrailingReturnVar
:
3283 if (!SemaRef
.getLangOpts().CPlusPlus14
|| !IsCXXAutoType
)
3284 Error
= 13; // Function return type
3285 IsDeducedReturnType
= true;
3287 case DeclaratorContext::ConversionId
:
3288 if (!SemaRef
.getLangOpts().CPlusPlus14
|| !IsCXXAutoType
)
3289 Error
= 14; // conversion-type-id
3290 IsDeducedReturnType
= true;
3292 case DeclaratorContext::FunctionalCast
:
3293 if (isa
<DeducedTemplateSpecializationType
>(Deduced
))
3295 if (SemaRef
.getLangOpts().CPlusPlus23
&& IsCXXAutoType
&&
3296 !Auto
->isDecltypeAuto())
3299 case DeclaratorContext::TypeName
:
3300 case DeclaratorContext::Association
:
3301 Error
= 15; // Generic
3303 case DeclaratorContext::File
:
3304 case DeclaratorContext::Block
:
3305 case DeclaratorContext::ForInit
:
3306 case DeclaratorContext::SelectionInit
:
3307 case DeclaratorContext::Condition
:
3308 // FIXME: P0091R3 (erroneously) does not permit class template argument
3309 // deduction in conditions, for-init-statements, and other declarations
3310 // that are not simple-declarations.
3312 case DeclaratorContext::CXXNew
:
3313 // FIXME: P0091R3 does not permit class template argument deduction here,
3314 // but we follow GCC and allow it anyway.
3315 if (!IsCXXAutoType
&& !isa
<DeducedTemplateSpecializationType
>(Deduced
))
3316 Error
= 17; // 'new' type
3318 case DeclaratorContext::KNRTypeList
:
3319 Error
= 18; // K&R function parameter
3323 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef
)
3326 // In Objective-C it is an error to use 'auto' on a function declarator
3327 // (and everywhere for '__auto_type').
3328 if (D
.isFunctionDeclarator() &&
3329 (!SemaRef
.getLangOpts().CPlusPlus11
|| !IsCXXAutoType
))
3332 SourceRange AutoRange
= D
.getDeclSpec().getTypeSpecTypeLoc();
3333 if (D
.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId
)
3334 AutoRange
= D
.getName().getSourceRange();
3339 switch (Auto
->getKeyword()) {
3340 case AutoTypeKeyword::Auto
: Kind
= 0; break;
3341 case AutoTypeKeyword::DecltypeAuto
: Kind
= 1; break;
3342 case AutoTypeKeyword::GNUAutoType
: Kind
= 2; break;
3345 assert(isa
<DeducedTemplateSpecializationType
>(Deduced
) &&
3346 "unknown auto type");
3350 auto *DTST
= dyn_cast
<DeducedTemplateSpecializationType
>(Deduced
);
3351 TemplateName TN
= DTST
? DTST
->getTemplateName() : TemplateName();
3353 SemaRef
.Diag(AutoRange
.getBegin(), diag::err_auto_not_allowed
)
3354 << Kind
<< Error
<< (int)SemaRef
.getTemplateNameKindForDiagnostics(TN
)
3355 << QualType(Deduced
, 0) << AutoRange
;
3356 if (auto *TD
= TN
.getAsTemplateDecl())
3357 SemaRef
.NoteTemplateLocation(*TD
);
3359 T
= SemaRef
.Context
.IntTy
;
3360 D
.setInvalidType(true);
3361 } else if (Auto
&& D
.getContext() != DeclaratorContext::LambdaExpr
) {
3362 // If there was a trailing return type, we already got
3363 // warn_cxx98_compat_trailing_return_type in the parser.
3364 SemaRef
.Diag(AutoRange
.getBegin(),
3365 D
.getContext() == DeclaratorContext::LambdaExprParameter
3366 ? diag::warn_cxx11_compat_generic_lambda
3367 : IsDeducedReturnType
3368 ? diag::warn_cxx11_compat_deduced_return_type
3369 : diag::warn_cxx98_compat_auto_type_specifier
)
3374 if (SemaRef
.getLangOpts().CPlusPlus
&&
3375 OwnedTagDecl
&& OwnedTagDecl
->isCompleteDefinition()) {
3376 // Check the contexts where C++ forbids the declaration of a new class
3377 // or enumeration in a type-specifier-seq.
3378 unsigned DiagID
= 0;
3379 switch (D
.getContext()) {
3380 case DeclaratorContext::TrailingReturn
:
3381 case DeclaratorContext::TrailingReturnVar
:
3382 // Class and enumeration definitions are syntactically not allowed in
3383 // trailing return types.
3384 llvm_unreachable("parser should not have allowed this");
3386 case DeclaratorContext::File
:
3387 case DeclaratorContext::Member
:
3388 case DeclaratorContext::Block
:
3389 case DeclaratorContext::ForInit
:
3390 case DeclaratorContext::SelectionInit
:
3391 case DeclaratorContext::BlockLiteral
:
3392 case DeclaratorContext::LambdaExpr
:
3393 // C++11 [dcl.type]p3:
3394 // A type-specifier-seq shall not define a class or enumeration unless
3395 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3396 // the declaration of a template-declaration.
3397 case DeclaratorContext::AliasDecl
:
3399 case DeclaratorContext::AliasTemplate
:
3400 DiagID
= diag::err_type_defined_in_alias_template
;
3402 case DeclaratorContext::TypeName
:
3403 case DeclaratorContext::FunctionalCast
:
3404 case DeclaratorContext::ConversionId
:
3405 case DeclaratorContext::TemplateParam
:
3406 case DeclaratorContext::CXXNew
:
3407 case DeclaratorContext::CXXCatch
:
3408 case DeclaratorContext::ObjCCatch
:
3409 case DeclaratorContext::TemplateArg
:
3410 case DeclaratorContext::TemplateTypeArg
:
3411 case DeclaratorContext::Association
:
3412 DiagID
= diag::err_type_defined_in_type_specifier
;
3414 case DeclaratorContext::Prototype
:
3415 case DeclaratorContext::LambdaExprParameter
:
3416 case DeclaratorContext::ObjCParameter
:
3417 case DeclaratorContext::ObjCResult
:
3418 case DeclaratorContext::KNRTypeList
:
3419 case DeclaratorContext::RequiresExpr
:
3421 // Types shall not be defined in return or parameter types.
3422 DiagID
= diag::err_type_defined_in_param_type
;
3424 case DeclaratorContext::Condition
:
3426 // The type-specifier-seq shall not contain typedef and shall not declare
3427 // a new class or enumeration.
3428 DiagID
= diag::err_type_defined_in_condition
;
3433 SemaRef
.Diag(OwnedTagDecl
->getLocation(), DiagID
)
3434 << SemaRef
.Context
.getTypeDeclType(OwnedTagDecl
);
3435 D
.setInvalidType(true);
3439 assert(!T
.isNull() && "This function should not return a null type");
3443 /// Produce an appropriate diagnostic for an ambiguity between a function
3444 /// declarator and a C++ direct-initializer.
3445 static void warnAboutAmbiguousFunction(Sema
&S
, Declarator
&D
,
3446 DeclaratorChunk
&DeclType
, QualType RT
) {
3447 const DeclaratorChunk::FunctionTypeInfo
&FTI
= DeclType
.Fun
;
3448 assert(FTI
.isAmbiguous
&& "no direct-initializer / function ambiguity");
3450 // If the return type is void there is no ambiguity.
3451 if (RT
->isVoidType())
3454 // An initializer for a non-class type can have at most one argument.
3455 if (!RT
->isRecordType() && FTI
.NumParams
> 1)
3458 // An initializer for a reference must have exactly one argument.
3459 if (RT
->isReferenceType() && FTI
.NumParams
!= 1)
3462 // Only warn if this declarator is declaring a function at block scope, and
3463 // doesn't have a storage class (such as 'extern') specified.
3464 if (!D
.isFunctionDeclarator() ||
3465 D
.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration
||
3466 !S
.CurContext
->isFunctionOrMethod() ||
3467 D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified
)
3470 // Inside a condition, a direct initializer is not permitted. We allow one to
3471 // be parsed in order to give better diagnostics in condition parsing.
3472 if (D
.getContext() == DeclaratorContext::Condition
)
3475 SourceRange
ParenRange(DeclType
.Loc
, DeclType
.EndLoc
);
3477 S
.Diag(DeclType
.Loc
,
3478 FTI
.NumParams
? diag::warn_parens_disambiguated_as_function_declaration
3479 : diag::warn_empty_parens_are_function_decl
)
3482 // If the declaration looks like:
3485 // and name lookup finds a function named 'f', then the ',' was
3486 // probably intended to be a ';'.
3487 if (!D
.isFirstDeclarator() && D
.getIdentifier()) {
3488 FullSourceLoc
Comma(D
.getCommaLoc(), S
.SourceMgr
);
3489 FullSourceLoc
Name(D
.getIdentifierLoc(), S
.SourceMgr
);
3490 if (Comma
.getFileID() != Name
.getFileID() ||
3491 Comma
.getSpellingLineNumber() != Name
.getSpellingLineNumber()) {
3492 LookupResult
Result(S
, D
.getIdentifier(), SourceLocation(),
3493 Sema::LookupOrdinaryName
);
3494 if (S
.LookupName(Result
, S
.getCurScope()))
3495 S
.Diag(D
.getCommaLoc(), diag::note_empty_parens_function_call
)
3496 << FixItHint::CreateReplacement(D
.getCommaLoc(), ";")
3497 << D
.getIdentifier();
3498 Result
.suppressDiagnostics();
3502 if (FTI
.NumParams
> 0) {
3503 // For a declaration with parameters, eg. "T var(T());", suggest adding
3504 // parens around the first parameter to turn the declaration into a
3505 // variable declaration.
3506 SourceRange Range
= FTI
.Params
[0].Param
->getSourceRange();
3507 SourceLocation B
= Range
.getBegin();
3508 SourceLocation E
= S
.getLocForEndOfToken(Range
.getEnd());
3509 // FIXME: Maybe we should suggest adding braces instead of parens
3510 // in C++11 for classes that don't have an initializer_list constructor.
3511 S
.Diag(B
, diag::note_additional_parens_for_variable_declaration
)
3512 << FixItHint::CreateInsertion(B
, "(")
3513 << FixItHint::CreateInsertion(E
, ")");
3515 // For a declaration without parameters, eg. "T var();", suggest replacing
3516 // the parens with an initializer to turn the declaration into a variable
3518 const CXXRecordDecl
*RD
= RT
->getAsCXXRecordDecl();
3520 // Empty parens mean value-initialization, and no parens mean
3521 // default initialization. These are equivalent if the default
3522 // constructor is user-provided or if zero-initialization is a
3524 if (RD
&& RD
->hasDefinition() &&
3525 (RD
->isEmpty() || RD
->hasUserProvidedDefaultConstructor()))
3526 S
.Diag(DeclType
.Loc
, diag::note_empty_parens_default_ctor
)
3527 << FixItHint::CreateRemoval(ParenRange
);
3530 S
.getFixItZeroInitializerForType(RT
, ParenRange
.getBegin());
3531 if (Init
.empty() && S
.LangOpts
.CPlusPlus11
)
3534 S
.Diag(DeclType
.Loc
, diag::note_empty_parens_zero_initialize
)
3535 << FixItHint::CreateReplacement(ParenRange
, Init
);
3540 /// Produce an appropriate diagnostic for a declarator with top-level
3542 static void warnAboutRedundantParens(Sema
&S
, Declarator
&D
, QualType T
) {
3543 DeclaratorChunk
&Paren
= D
.getTypeObject(D
.getNumTypeObjects() - 1);
3544 assert(Paren
.Kind
== DeclaratorChunk::Paren
&&
3545 "do not have redundant top-level parentheses");
3547 // This is a syntactic check; we're not interested in cases that arise
3548 // during template instantiation.
3549 if (S
.inTemplateInstantiation())
3552 // Check whether this could be intended to be a construction of a temporary
3553 // object in C++ via a function-style cast.
3554 bool CouldBeTemporaryObject
=
3555 S
.getLangOpts().CPlusPlus
&& D
.isExpressionContext() &&
3556 !D
.isInvalidType() && D
.getIdentifier() &&
3557 D
.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier
&&
3558 (T
->isRecordType() || T
->isDependentType()) &&
3559 D
.getDeclSpec().getTypeQualifiers() == 0 && D
.isFirstDeclarator();
3561 bool StartsWithDeclaratorId
= true;
3562 for (auto &C
: D
.type_objects()) {
3564 case DeclaratorChunk::Paren
:
3568 case DeclaratorChunk::Pointer
:
3569 StartsWithDeclaratorId
= false;
3572 case DeclaratorChunk::Array
:
3574 CouldBeTemporaryObject
= false;
3577 case DeclaratorChunk::Reference
:
3578 // FIXME: Suppress the warning here if there is no initializer; we're
3579 // going to give an error anyway.
3580 // We assume that something like 'T (&x) = y;' is highly likely to not
3581 // be intended to be a temporary object.
3582 CouldBeTemporaryObject
= false;
3583 StartsWithDeclaratorId
= false;
3586 case DeclaratorChunk::Function
:
3587 // In a new-type-id, function chunks require parentheses.
3588 if (D
.getContext() == DeclaratorContext::CXXNew
)
3590 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3591 // redundant-parens warning, but we don't know whether the function
3592 // chunk was syntactically valid as an expression here.
3593 CouldBeTemporaryObject
= false;
3596 case DeclaratorChunk::BlockPointer
:
3597 case DeclaratorChunk::MemberPointer
:
3598 case DeclaratorChunk::Pipe
:
3599 // These cannot appear in expressions.
3600 CouldBeTemporaryObject
= false;
3601 StartsWithDeclaratorId
= false;
3606 // FIXME: If there is an initializer, assume that this is not intended to be
3607 // a construction of a temporary object.
3609 // Check whether the name has already been declared; if not, this is not a
3610 // function-style cast.
3611 if (CouldBeTemporaryObject
) {
3612 LookupResult
Result(S
, D
.getIdentifier(), SourceLocation(),
3613 Sema::LookupOrdinaryName
);
3614 if (!S
.LookupName(Result
, S
.getCurScope()))
3615 CouldBeTemporaryObject
= false;
3616 Result
.suppressDiagnostics();
3619 SourceRange
ParenRange(Paren
.Loc
, Paren
.EndLoc
);
3621 if (!CouldBeTemporaryObject
) {
3622 // If we have A (::B), the parentheses affect the meaning of the program.
3623 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3624 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3625 // formally unambiguous.
3626 if (StartsWithDeclaratorId
&& D
.getCXXScopeSpec().isValid()) {
3627 for (NestedNameSpecifier
*NNS
= D
.getCXXScopeSpec().getScopeRep(); NNS
;
3628 NNS
= NNS
->getPrefix()) {
3629 if (NNS
->getKind() == NestedNameSpecifier::Global
)
3634 S
.Diag(Paren
.Loc
, diag::warn_redundant_parens_around_declarator
)
3635 << ParenRange
<< FixItHint::CreateRemoval(Paren
.Loc
)
3636 << FixItHint::CreateRemoval(Paren
.EndLoc
);
3640 S
.Diag(Paren
.Loc
, diag::warn_parens_disambiguated_as_variable_declaration
)
3641 << ParenRange
<< D
.getIdentifier();
3642 auto *RD
= T
->getAsCXXRecordDecl();
3643 if (!RD
|| !RD
->hasDefinition() || RD
->hasNonTrivialDestructor())
3644 S
.Diag(Paren
.Loc
, diag::note_raii_guard_add_name
)
3645 << FixItHint::CreateInsertion(Paren
.Loc
, " varname") << T
3646 << D
.getIdentifier();
3647 // FIXME: A cast to void is probably a better suggestion in cases where it's
3648 // valid (when there is no initializer and we're not in a condition).
3649 S
.Diag(D
.getBeginLoc(), diag::note_function_style_cast_add_parentheses
)
3650 << FixItHint::CreateInsertion(D
.getBeginLoc(), "(")
3651 << FixItHint::CreateInsertion(S
.getLocForEndOfToken(D
.getEndLoc()), ")");
3652 S
.Diag(Paren
.Loc
, diag::note_remove_parens_for_variable_declaration
)
3653 << FixItHint::CreateRemoval(Paren
.Loc
)
3654 << FixItHint::CreateRemoval(Paren
.EndLoc
);
3657 /// Helper for figuring out the default CC for a function declarator type. If
3658 /// this is the outermost chunk, then we can determine the CC from the
3659 /// declarator context. If not, then this could be either a member function
3660 /// type or normal function type.
3661 static CallingConv
getCCForDeclaratorChunk(
3662 Sema
&S
, Declarator
&D
, const ParsedAttributesView
&AttrList
,
3663 const DeclaratorChunk::FunctionTypeInfo
&FTI
, unsigned ChunkIndex
) {
3664 assert(D
.getTypeObject(ChunkIndex
).Kind
== DeclaratorChunk::Function
);
3666 // Check for an explicit CC attribute.
3667 for (const ParsedAttr
&AL
: AttrList
) {
3668 switch (AL
.getKind()) {
3669 CALLING_CONV_ATTRS_CASELIST
: {
3670 // Ignore attributes that don't validate or can't apply to the
3671 // function type. We'll diagnose the failure to apply them in
3672 // handleFunctionTypeAttr.
3674 if (!S
.CheckCallingConvAttr(AL
, CC
, /*FunctionDecl=*/nullptr,
3675 S
.CUDA().IdentifyTarget(D
.getAttributes())) &&
3676 (!FTI
.isVariadic
|| supportsVariadicCall(CC
))) {
3687 bool IsCXXInstanceMethod
= false;
3689 if (S
.getLangOpts().CPlusPlus
) {
3690 // Look inwards through parentheses to see if this chunk will form a
3691 // member pointer type or if we're the declarator. Any type attributes
3692 // between here and there will override the CC we choose here.
3693 unsigned I
= ChunkIndex
;
3694 bool FoundNonParen
= false;
3695 while (I
&& !FoundNonParen
) {
3697 if (D
.getTypeObject(I
).Kind
!= DeclaratorChunk::Paren
)
3698 FoundNonParen
= true;
3701 if (FoundNonParen
) {
3702 // If we're not the declarator, we're a regular function type unless we're
3703 // in a member pointer.
3704 IsCXXInstanceMethod
=
3705 D
.getTypeObject(I
).Kind
== DeclaratorChunk::MemberPointer
;
3706 } else if (D
.getContext() == DeclaratorContext::LambdaExpr
) {
3707 // This can only be a call operator for a lambda, which is an instance
3708 // method, unless explicitly specified as 'static'.
3709 IsCXXInstanceMethod
=
3710 D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static
;
3712 // We're the innermost decl chunk, so must be a function declarator.
3713 assert(D
.isFunctionDeclarator());
3715 // If we're inside a record, we're declaring a method, but it could be
3716 // explicitly or implicitly static.
3717 IsCXXInstanceMethod
=
3718 D
.isFirstDeclarationOfMember() &&
3719 D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&&
3720 !D
.isStaticMember();
3724 CallingConv CC
= S
.Context
.getDefaultCallingConvention(FTI
.isVariadic
,
3725 IsCXXInstanceMethod
);
3727 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3728 // and AMDGPU targets, hence it cannot be treated as a calling
3729 // convention attribute. This is the simplest place to infer
3730 // calling convention for OpenCL kernels.
3731 if (S
.getLangOpts().OpenCL
) {
3732 for (const ParsedAttr
&AL
: D
.getDeclSpec().getAttributes()) {
3733 if (AL
.getKind() == ParsedAttr::AT_OpenCLKernel
) {
3734 CC
= CC_OpenCLKernel
;
3738 } else if (S
.getLangOpts().CUDA
) {
3739 // If we're compiling CUDA/HIP code and targeting HIPSPV we need to make
3740 // sure the kernels will be marked with the right calling convention so that
3741 // they will be visible by the APIs that ingest SPIR-V. We do not do this
3742 // when targeting AMDGCNSPIRV, as it does not rely on OpenCL.
3743 llvm::Triple Triple
= S
.Context
.getTargetInfo().getTriple();
3744 if (Triple
.isSPIRV() && Triple
.getVendor() != llvm::Triple::AMD
) {
3745 for (const ParsedAttr
&AL
: D
.getDeclSpec().getAttributes()) {
3746 if (AL
.getKind() == ParsedAttr::AT_CUDAGlobal
) {
3747 CC
= CC_OpenCLKernel
;
3758 /// A simple notion of pointer kinds, which matches up with the various
3759 /// pointer declarators.
3760 enum class SimplePointerKind
{
3766 } // end anonymous namespace
3768 IdentifierInfo
*Sema::getNullabilityKeyword(NullabilityKind nullability
) {
3769 switch (nullability
) {
3770 case NullabilityKind::NonNull
:
3771 if (!Ident__Nonnull
)
3772 Ident__Nonnull
= PP
.getIdentifierInfo("_Nonnull");
3773 return Ident__Nonnull
;
3775 case NullabilityKind::Nullable
:
3776 if (!Ident__Nullable
)
3777 Ident__Nullable
= PP
.getIdentifierInfo("_Nullable");
3778 return Ident__Nullable
;
3780 case NullabilityKind::NullableResult
:
3781 if (!Ident__Nullable_result
)
3782 Ident__Nullable_result
= PP
.getIdentifierInfo("_Nullable_result");
3783 return Ident__Nullable_result
;
3785 case NullabilityKind::Unspecified
:
3786 if (!Ident__Null_unspecified
)
3787 Ident__Null_unspecified
= PP
.getIdentifierInfo("_Null_unspecified");
3788 return Ident__Null_unspecified
;
3790 llvm_unreachable("Unknown nullability kind.");
3793 /// Check whether there is a nullability attribute of any kind in the given
3795 static bool hasNullabilityAttr(const ParsedAttributesView
&attrs
) {
3796 for (const ParsedAttr
&AL
: attrs
) {
3797 if (AL
.getKind() == ParsedAttr::AT_TypeNonNull
||
3798 AL
.getKind() == ParsedAttr::AT_TypeNullable
||
3799 AL
.getKind() == ParsedAttr::AT_TypeNullableResult
||
3800 AL
.getKind() == ParsedAttr::AT_TypeNullUnspecified
)
3808 /// Describes the kind of a pointer a declarator describes.
3809 enum class PointerDeclaratorKind
{
3812 // Single-level pointer.
3814 // Multi-level pointer (of any pointer kind).
3817 MaybePointerToCFRef
,
3821 NSErrorPointerPointer
,
3824 /// Describes a declarator chunk wrapping a pointer that marks inference as
3826 // These values must be kept in sync with diagnostics.
3827 enum class PointerWrappingDeclaratorKind
{
3828 /// Pointer is top-level.
3830 /// Pointer is an array element.
3832 /// Pointer is the referent type of a C++ reference.
3835 } // end anonymous namespace
3837 /// Classify the given declarator, whose type-specified is \c type, based on
3838 /// what kind of pointer it refers to.
3840 /// This is used to determine the default nullability.
3841 static PointerDeclaratorKind
3842 classifyPointerDeclarator(Sema
&S
, QualType type
, Declarator
&declarator
,
3843 PointerWrappingDeclaratorKind
&wrappingKind
) {
3844 unsigned numNormalPointers
= 0;
3846 // For any dependent type, we consider it a non-pointer.
3847 if (type
->isDependentType())
3848 return PointerDeclaratorKind::NonPointer
;
3850 // Look through the declarator chunks to identify pointers.
3851 for (unsigned i
= 0, n
= declarator
.getNumTypeObjects(); i
!= n
; ++i
) {
3852 DeclaratorChunk
&chunk
= declarator
.getTypeObject(i
);
3853 switch (chunk
.Kind
) {
3854 case DeclaratorChunk::Array
:
3855 if (numNormalPointers
== 0)
3856 wrappingKind
= PointerWrappingDeclaratorKind::Array
;
3859 case DeclaratorChunk::Function
:
3860 case DeclaratorChunk::Pipe
:
3863 case DeclaratorChunk::BlockPointer
:
3864 case DeclaratorChunk::MemberPointer
:
3865 return numNormalPointers
> 0 ? PointerDeclaratorKind::MultiLevelPointer
3866 : PointerDeclaratorKind::SingleLevelPointer
;
3868 case DeclaratorChunk::Paren
:
3871 case DeclaratorChunk::Reference
:
3872 if (numNormalPointers
== 0)
3873 wrappingKind
= PointerWrappingDeclaratorKind::Reference
;
3876 case DeclaratorChunk::Pointer
:
3877 ++numNormalPointers
;
3878 if (numNormalPointers
> 2)
3879 return PointerDeclaratorKind::MultiLevelPointer
;
3884 // Then, dig into the type specifier itself.
3885 unsigned numTypeSpecifierPointers
= 0;
3887 // Decompose normal pointers.
3888 if (auto ptrType
= type
->getAs
<PointerType
>()) {
3889 ++numNormalPointers
;
3891 if (numNormalPointers
> 2)
3892 return PointerDeclaratorKind::MultiLevelPointer
;
3894 type
= ptrType
->getPointeeType();
3895 ++numTypeSpecifierPointers
;
3899 // Decompose block pointers.
3900 if (type
->getAs
<BlockPointerType
>()) {
3901 return numNormalPointers
> 0 ? PointerDeclaratorKind::MultiLevelPointer
3902 : PointerDeclaratorKind::SingleLevelPointer
;
3905 // Decompose member pointers.
3906 if (type
->getAs
<MemberPointerType
>()) {
3907 return numNormalPointers
> 0 ? PointerDeclaratorKind::MultiLevelPointer
3908 : PointerDeclaratorKind::SingleLevelPointer
;
3911 // Look at Objective-C object pointers.
3912 if (auto objcObjectPtr
= type
->getAs
<ObjCObjectPointerType
>()) {
3913 ++numNormalPointers
;
3914 ++numTypeSpecifierPointers
;
3916 // If this is NSError**, report that.
3917 if (auto objcClassDecl
= objcObjectPtr
->getInterfaceDecl()) {
3918 if (objcClassDecl
->getIdentifier() == S
.ObjC().getNSErrorIdent() &&
3919 numNormalPointers
== 2 && numTypeSpecifierPointers
< 2) {
3920 return PointerDeclaratorKind::NSErrorPointerPointer
;
3927 // Look at Objective-C class types.
3928 if (auto objcClass
= type
->getAs
<ObjCInterfaceType
>()) {
3929 if (objcClass
->getInterface()->getIdentifier() ==
3930 S
.ObjC().getNSErrorIdent()) {
3931 if (numNormalPointers
== 2 && numTypeSpecifierPointers
< 2)
3932 return PointerDeclaratorKind::NSErrorPointerPointer
;
3938 // If at this point we haven't seen a pointer, we won't see one.
3939 if (numNormalPointers
== 0)
3940 return PointerDeclaratorKind::NonPointer
;
3942 if (auto recordType
= type
->getAs
<RecordType
>()) {
3943 RecordDecl
*recordDecl
= recordType
->getDecl();
3945 // If this is CFErrorRef*, report it as such.
3946 if (numNormalPointers
== 2 && numTypeSpecifierPointers
< 2 &&
3947 S
.ObjC().isCFError(recordDecl
)) {
3948 return PointerDeclaratorKind::CFErrorRefPointer
;
3956 switch (numNormalPointers
) {
3958 return PointerDeclaratorKind::NonPointer
;
3961 return PointerDeclaratorKind::SingleLevelPointer
;
3964 return PointerDeclaratorKind::MaybePointerToCFRef
;
3967 return PointerDeclaratorKind::MultiLevelPointer
;
3971 static FileID
getNullabilityCompletenessCheckFileID(Sema
&S
,
3972 SourceLocation loc
) {
3973 // If we're anywhere in a function, method, or closure context, don't perform
3974 // completeness checks.
3975 for (DeclContext
*ctx
= S
.CurContext
; ctx
; ctx
= ctx
->getParent()) {
3976 if (ctx
->isFunctionOrMethod())
3979 if (ctx
->isFileContext())
3983 // We only care about the expansion location.
3984 loc
= S
.SourceMgr
.getExpansionLoc(loc
);
3985 FileID file
= S
.SourceMgr
.getFileID(loc
);
3986 if (file
.isInvalid())
3989 // Retrieve file information.
3990 bool invalid
= false;
3991 const SrcMgr::SLocEntry
&sloc
= S
.SourceMgr
.getSLocEntry(file
, &invalid
);
3992 if (invalid
|| !sloc
.isFile())
3995 // We don't want to perform completeness checks on the main file or in
3997 const SrcMgr::FileInfo
&fileInfo
= sloc
.getFile();
3998 if (fileInfo
.getIncludeLoc().isInvalid())
4000 if (fileInfo
.getFileCharacteristic() != SrcMgr::C_User
&&
4001 S
.Diags
.getSuppressSystemWarnings()) {
4008 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4009 /// taking into account whitespace before and after.
4010 template <typename DiagBuilderT
>
4011 static void fixItNullability(Sema
&S
, DiagBuilderT
&Diag
,
4012 SourceLocation PointerLoc
,
4013 NullabilityKind Nullability
) {
4014 assert(PointerLoc
.isValid());
4015 if (PointerLoc
.isMacroID())
4018 SourceLocation FixItLoc
= S
.getLocForEndOfToken(PointerLoc
);
4019 if (!FixItLoc
.isValid() || FixItLoc
== PointerLoc
)
4022 const char *NextChar
= S
.SourceMgr
.getCharacterData(FixItLoc
);
4026 SmallString
<32> InsertionTextBuf
{" "};
4027 InsertionTextBuf
+= getNullabilitySpelling(Nullability
);
4028 InsertionTextBuf
+= " ";
4029 StringRef InsertionText
= InsertionTextBuf
.str();
4031 if (isWhitespace(*NextChar
)) {
4032 InsertionText
= InsertionText
.drop_back();
4033 } else if (NextChar
[-1] == '[') {
4034 if (NextChar
[0] == ']')
4035 InsertionText
= InsertionText
.drop_back().drop_front();
4037 InsertionText
= InsertionText
.drop_front();
4038 } else if (!isAsciiIdentifierContinue(NextChar
[0], /*allow dollar*/ true) &&
4039 !isAsciiIdentifierContinue(NextChar
[-1], /*allow dollar*/ true)) {
4040 InsertionText
= InsertionText
.drop_back().drop_front();
4043 Diag
<< FixItHint::CreateInsertion(FixItLoc
, InsertionText
);
4046 static void emitNullabilityConsistencyWarning(Sema
&S
,
4047 SimplePointerKind PointerKind
,
4048 SourceLocation PointerLoc
,
4049 SourceLocation PointerEndLoc
) {
4050 assert(PointerLoc
.isValid());
4052 if (PointerKind
== SimplePointerKind::Array
) {
4053 S
.Diag(PointerLoc
, diag::warn_nullability_missing_array
);
4055 S
.Diag(PointerLoc
, diag::warn_nullability_missing
)
4056 << static_cast<unsigned>(PointerKind
);
4059 auto FixItLoc
= PointerEndLoc
.isValid() ? PointerEndLoc
: PointerLoc
;
4060 if (FixItLoc
.isMacroID())
4063 auto addFixIt
= [&](NullabilityKind Nullability
) {
4064 auto Diag
= S
.Diag(FixItLoc
, diag::note_nullability_fix_it
);
4065 Diag
<< static_cast<unsigned>(Nullability
);
4066 Diag
<< static_cast<unsigned>(PointerKind
);
4067 fixItNullability(S
, Diag
, FixItLoc
, Nullability
);
4069 addFixIt(NullabilityKind::Nullable
);
4070 addFixIt(NullabilityKind::NonNull
);
4073 /// Complains about missing nullability if the file containing \p pointerLoc
4074 /// has other uses of nullability (either the keywords or the \c assume_nonnull
4077 /// If the file has \e not seen other uses of nullability, this particular
4078 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4080 checkNullabilityConsistency(Sema
&S
, SimplePointerKind pointerKind
,
4081 SourceLocation pointerLoc
,
4082 SourceLocation pointerEndLoc
= SourceLocation()) {
4083 // Determine which file we're performing consistency checking for.
4084 FileID file
= getNullabilityCompletenessCheckFileID(S
, pointerLoc
);
4085 if (file
.isInvalid())
4088 // If we haven't seen any type nullability in this file, we won't warn now
4090 FileNullability
&fileNullability
= S
.NullabilityMap
[file
];
4091 if (!fileNullability
.SawTypeNullability
) {
4092 // If this is the first pointer declarator in the file, and the appropriate
4093 // warning is on, record it in case we need to diagnose it retroactively.
4094 diag::kind diagKind
;
4095 if (pointerKind
== SimplePointerKind::Array
)
4096 diagKind
= diag::warn_nullability_missing_array
;
4098 diagKind
= diag::warn_nullability_missing
;
4100 if (fileNullability
.PointerLoc
.isInvalid() &&
4101 !S
.Context
.getDiagnostics().isIgnored(diagKind
, pointerLoc
)) {
4102 fileNullability
.PointerLoc
= pointerLoc
;
4103 fileNullability
.PointerEndLoc
= pointerEndLoc
;
4104 fileNullability
.PointerKind
= static_cast<unsigned>(pointerKind
);
4110 // Complain about missing nullability.
4111 emitNullabilityConsistencyWarning(S
, pointerKind
, pointerLoc
, pointerEndLoc
);
4114 /// Marks that a nullability feature has been used in the file containing
4117 /// If this file already had pointer types in it that were missing nullability,
4118 /// the first such instance is retroactively diagnosed.
4120 /// \sa checkNullabilityConsistency
4121 static void recordNullabilitySeen(Sema
&S
, SourceLocation loc
) {
4122 FileID file
= getNullabilityCompletenessCheckFileID(S
, loc
);
4123 if (file
.isInvalid())
4126 FileNullability
&fileNullability
= S
.NullabilityMap
[file
];
4127 if (fileNullability
.SawTypeNullability
)
4129 fileNullability
.SawTypeNullability
= true;
4131 // If we haven't seen any type nullability before, now we have. Retroactively
4132 // diagnose the first unannotated pointer, if there was one.
4133 if (fileNullability
.PointerLoc
.isInvalid())
4136 auto kind
= static_cast<SimplePointerKind
>(fileNullability
.PointerKind
);
4137 emitNullabilityConsistencyWarning(S
, kind
, fileNullability
.PointerLoc
,
4138 fileNullability
.PointerEndLoc
);
4141 /// Returns true if any of the declarator chunks before \p endIndex include a
4142 /// level of indirection: array, pointer, reference, or pointer-to-member.
4144 /// Because declarator chunks are stored in outer-to-inner order, testing
4145 /// every chunk before \p endIndex is testing all chunks that embed the current
4146 /// chunk as part of their type.
4148 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4149 /// end index, in which case all chunks are tested.
4150 static bool hasOuterPointerLikeChunk(const Declarator
&D
, unsigned endIndex
) {
4151 unsigned i
= endIndex
;
4153 // Walk outwards along the declarator chunks.
4155 const DeclaratorChunk
&DC
= D
.getTypeObject(i
);
4157 case DeclaratorChunk::Paren
:
4159 case DeclaratorChunk::Array
:
4160 case DeclaratorChunk::Pointer
:
4161 case DeclaratorChunk::Reference
:
4162 case DeclaratorChunk::MemberPointer
:
4164 case DeclaratorChunk::Function
:
4165 case DeclaratorChunk::BlockPointer
:
4166 case DeclaratorChunk::Pipe
:
4167 // These are invalid anyway, so just ignore.
4174 static bool IsNoDerefableChunk(const DeclaratorChunk
&Chunk
) {
4175 return (Chunk
.Kind
== DeclaratorChunk::Pointer
||
4176 Chunk
.Kind
== DeclaratorChunk::Array
);
4179 template<typename AttrT
>
4180 static AttrT
*createSimpleAttr(ASTContext
&Ctx
, ParsedAttr
&AL
) {
4181 AL
.setUsedAsTypeAttr();
4182 return ::new (Ctx
) AttrT(Ctx
, AL
);
4185 static Attr
*createNullabilityAttr(ASTContext
&Ctx
, ParsedAttr
&Attr
,
4186 NullabilityKind NK
) {
4188 case NullabilityKind::NonNull
:
4189 return createSimpleAttr
<TypeNonNullAttr
>(Ctx
, Attr
);
4191 case NullabilityKind::Nullable
:
4192 return createSimpleAttr
<TypeNullableAttr
>(Ctx
, Attr
);
4194 case NullabilityKind::NullableResult
:
4195 return createSimpleAttr
<TypeNullableResultAttr
>(Ctx
, Attr
);
4197 case NullabilityKind::Unspecified
:
4198 return createSimpleAttr
<TypeNullUnspecifiedAttr
>(Ctx
, Attr
);
4200 llvm_unreachable("unknown NullabilityKind");
4203 // Diagnose whether this is a case with the multiple addr spaces.
4204 // Returns true if this is an invalid case.
4205 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4206 // by qualifiers for two or more different address spaces."
4207 static bool DiagnoseMultipleAddrSpaceAttributes(Sema
&S
, LangAS ASOld
,
4209 SourceLocation AttrLoc
) {
4210 if (ASOld
!= LangAS::Default
) {
4211 if (ASOld
!= ASNew
) {
4212 S
.Diag(AttrLoc
, diag::err_attribute_address_multiple_qualifiers
);
4215 // Emit a warning if they are identical; it's likely unintended.
4217 diag::warn_attribute_address_multiple_identical_qualifiers
);
4222 // Whether this is a type broadly expected to have nullability attached.
4223 // These types are affected by `#pragma assume_nonnull`, and missing nullability
4224 // will be diagnosed with -Wnullability-completeness.
4225 static bool shouldHaveNullability(QualType T
) {
4226 return T
->canHaveNullability(/*ResultIfUnknown=*/false) &&
4227 // For now, do not infer/require nullability on C++ smart pointers.
4228 // It's unclear whether the pragma's behavior is useful for C++.
4229 // e.g. treating type-aliases and template-type-parameters differently
4230 // from types of declarations can be surprising.
4231 !isa
<RecordType
, TemplateSpecializationType
>(
4232 T
->getCanonicalTypeInternal());
4235 static TypeSourceInfo
*GetFullTypeForDeclarator(TypeProcessingState
&state
,
4236 QualType declSpecType
,
4237 TypeSourceInfo
*TInfo
) {
4238 // The TypeSourceInfo that this function returns will not be a null type.
4239 // If there is an error, this function will fill in a dummy type as fallback.
4240 QualType T
= declSpecType
;
4241 Declarator
&D
= state
.getDeclarator();
4242 Sema
&S
= state
.getSema();
4243 ASTContext
&Context
= S
.Context
;
4244 const LangOptions
&LangOpts
= S
.getLangOpts();
4246 // The name we're declaring, if any.
4247 DeclarationName Name
;
4248 if (D
.getIdentifier())
4249 Name
= D
.getIdentifier();
4251 // Does this declaration declare a typedef-name?
4252 bool IsTypedefName
=
4253 D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef
||
4254 D
.getContext() == DeclaratorContext::AliasDecl
||
4255 D
.getContext() == DeclaratorContext::AliasTemplate
;
4257 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4258 bool IsQualifiedFunction
= T
->isFunctionProtoType() &&
4259 (!T
->castAs
<FunctionProtoType
>()->getMethodQuals().empty() ||
4260 T
->castAs
<FunctionProtoType
>()->getRefQualifier() != RQ_None
);
4262 // If T is 'decltype(auto)', the only declarators we can have are parens
4263 // and at most one function declarator if this is a function declaration.
4264 // If T is a deduced class template specialization type, we can have no
4265 // declarator chunks at all.
4266 if (auto *DT
= T
->getAs
<DeducedType
>()) {
4267 const AutoType
*AT
= T
->getAs
<AutoType
>();
4268 bool IsClassTemplateDeduction
= isa
<DeducedTemplateSpecializationType
>(DT
);
4269 if ((AT
&& AT
->isDecltypeAuto()) || IsClassTemplateDeduction
) {
4270 for (unsigned I
= 0, E
= D
.getNumTypeObjects(); I
!= E
; ++I
) {
4271 unsigned Index
= E
- I
- 1;
4272 DeclaratorChunk
&DeclChunk
= D
.getTypeObject(Index
);
4273 unsigned DiagId
= IsClassTemplateDeduction
4274 ? diag::err_deduced_class_template_compound_type
4275 : diag::err_decltype_auto_compound_type
;
4276 unsigned DiagKind
= 0;
4277 switch (DeclChunk
.Kind
) {
4278 case DeclaratorChunk::Paren
:
4279 // FIXME: Rejecting this is a little silly.
4280 if (IsClassTemplateDeduction
) {
4285 case DeclaratorChunk::Function
: {
4286 if (IsClassTemplateDeduction
) {
4291 if (D
.isFunctionDeclarationContext() &&
4292 D
.isFunctionDeclarator(FnIndex
) && FnIndex
== Index
)
4294 DiagId
= diag::err_decltype_auto_function_declarator_not_declaration
;
4297 case DeclaratorChunk::Pointer
:
4298 case DeclaratorChunk::BlockPointer
:
4299 case DeclaratorChunk::MemberPointer
:
4302 case DeclaratorChunk::Reference
:
4305 case DeclaratorChunk::Array
:
4308 case DeclaratorChunk::Pipe
:
4312 S
.Diag(DeclChunk
.Loc
, DiagId
) << DiagKind
;
4313 D
.setInvalidType(true);
4319 // Determine whether we should infer _Nonnull on pointer types.
4320 std::optional
<NullabilityKind
> inferNullability
;
4321 bool inferNullabilityCS
= false;
4322 bool inferNullabilityInnerOnly
= false;
4323 bool inferNullabilityInnerOnlyComplete
= false;
4325 // Are we in an assume-nonnull region?
4326 bool inAssumeNonNullRegion
= false;
4327 SourceLocation assumeNonNullLoc
= S
.PP
.getPragmaAssumeNonNullLoc();
4328 if (assumeNonNullLoc
.isValid()) {
4329 inAssumeNonNullRegion
= true;
4330 recordNullabilitySeen(S
, assumeNonNullLoc
);
4333 // Whether to complain about missing nullability specifiers or not.
4337 /// Complain on the inner pointers (but not the outermost
4340 /// Complain about any pointers that don't have nullability
4341 /// specified or inferred.
4343 } complainAboutMissingNullability
= CAMN_No
;
4344 unsigned NumPointersRemaining
= 0;
4345 auto complainAboutInferringWithinChunk
= PointerWrappingDeclaratorKind::None
;
4347 if (IsTypedefName
) {
4348 // For typedefs, we do not infer any nullability (the default),
4349 // and we only complain about missing nullability specifiers on
4351 complainAboutMissingNullability
= CAMN_InnerPointers
;
4353 if (shouldHaveNullability(T
) && !T
->getNullability()) {
4354 // Note that we allow but don't require nullability on dependent types.
4355 ++NumPointersRemaining
;
4358 for (unsigned i
= 0, n
= D
.getNumTypeObjects(); i
!= n
; ++i
) {
4359 DeclaratorChunk
&chunk
= D
.getTypeObject(i
);
4360 switch (chunk
.Kind
) {
4361 case DeclaratorChunk::Array
:
4362 case DeclaratorChunk::Function
:
4363 case DeclaratorChunk::Pipe
:
4366 case DeclaratorChunk::BlockPointer
:
4367 case DeclaratorChunk::MemberPointer
:
4368 ++NumPointersRemaining
;
4371 case DeclaratorChunk::Paren
:
4372 case DeclaratorChunk::Reference
:
4375 case DeclaratorChunk::Pointer
:
4376 ++NumPointersRemaining
;
4381 bool isFunctionOrMethod
= false;
4382 switch (auto context
= state
.getDeclarator().getContext()) {
4383 case DeclaratorContext::ObjCParameter
:
4384 case DeclaratorContext::ObjCResult
:
4385 case DeclaratorContext::Prototype
:
4386 case DeclaratorContext::TrailingReturn
:
4387 case DeclaratorContext::TrailingReturnVar
:
4388 isFunctionOrMethod
= true;
4391 case DeclaratorContext::Member
:
4392 if (state
.getDeclarator().isObjCIvar() && !isFunctionOrMethod
) {
4393 complainAboutMissingNullability
= CAMN_No
;
4397 // Weak properties are inferred to be nullable.
4398 if (state
.getDeclarator().isObjCWeakProperty()) {
4399 // Weak properties cannot be nonnull, and should not complain about
4400 // missing nullable attributes during completeness checks.
4401 complainAboutMissingNullability
= CAMN_No
;
4402 if (inAssumeNonNullRegion
) {
4403 inferNullability
= NullabilityKind::Nullable
;
4410 case DeclaratorContext::File
:
4411 case DeclaratorContext::KNRTypeList
: {
4412 complainAboutMissingNullability
= CAMN_Yes
;
4414 // Nullability inference depends on the type and declarator.
4415 auto wrappingKind
= PointerWrappingDeclaratorKind::None
;
4416 switch (classifyPointerDeclarator(S
, T
, D
, wrappingKind
)) {
4417 case PointerDeclaratorKind::NonPointer
:
4418 case PointerDeclaratorKind::MultiLevelPointer
:
4419 // Cannot infer nullability.
4422 case PointerDeclaratorKind::SingleLevelPointer
:
4423 // Infer _Nonnull if we are in an assumes-nonnull region.
4424 if (inAssumeNonNullRegion
) {
4425 complainAboutInferringWithinChunk
= wrappingKind
;
4426 inferNullability
= NullabilityKind::NonNull
;
4427 inferNullabilityCS
= (context
== DeclaratorContext::ObjCParameter
||
4428 context
== DeclaratorContext::ObjCResult
);
4432 case PointerDeclaratorKind::CFErrorRefPointer
:
4433 case PointerDeclaratorKind::NSErrorPointerPointer
:
4434 // Within a function or method signature, infer _Nullable at both
4436 if (isFunctionOrMethod
&& inAssumeNonNullRegion
)
4437 inferNullability
= NullabilityKind::Nullable
;
4440 case PointerDeclaratorKind::MaybePointerToCFRef
:
4441 if (isFunctionOrMethod
) {
4442 // On pointer-to-pointer parameters marked cf_returns_retained or
4443 // cf_returns_not_retained, if the outer pointer is explicit then
4444 // infer the inner pointer as _Nullable.
4445 auto hasCFReturnsAttr
=
4446 [](const ParsedAttributesView
&AttrList
) -> bool {
4447 return AttrList
.hasAttribute(ParsedAttr::AT_CFReturnsRetained
) ||
4448 AttrList
.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained
);
4450 if (const auto *InnermostChunk
= D
.getInnermostNonParenChunk()) {
4451 if (hasCFReturnsAttr(D
.getDeclarationAttributes()) ||
4452 hasCFReturnsAttr(D
.getAttributes()) ||
4453 hasCFReturnsAttr(InnermostChunk
->getAttrs()) ||
4454 hasCFReturnsAttr(D
.getDeclSpec().getAttributes())) {
4455 inferNullability
= NullabilityKind::Nullable
;
4456 inferNullabilityInnerOnly
= true;
4465 case DeclaratorContext::ConversionId
:
4466 complainAboutMissingNullability
= CAMN_Yes
;
4469 case DeclaratorContext::AliasDecl
:
4470 case DeclaratorContext::AliasTemplate
:
4471 case DeclaratorContext::Block
:
4472 case DeclaratorContext::BlockLiteral
:
4473 case DeclaratorContext::Condition
:
4474 case DeclaratorContext::CXXCatch
:
4475 case DeclaratorContext::CXXNew
:
4476 case DeclaratorContext::ForInit
:
4477 case DeclaratorContext::SelectionInit
:
4478 case DeclaratorContext::LambdaExpr
:
4479 case DeclaratorContext::LambdaExprParameter
:
4480 case DeclaratorContext::ObjCCatch
:
4481 case DeclaratorContext::TemplateParam
:
4482 case DeclaratorContext::TemplateArg
:
4483 case DeclaratorContext::TemplateTypeArg
:
4484 case DeclaratorContext::TypeName
:
4485 case DeclaratorContext::FunctionalCast
:
4486 case DeclaratorContext::RequiresExpr
:
4487 case DeclaratorContext::Association
:
4488 // Don't infer in these contexts.
4493 // Local function that returns true if its argument looks like a va_list.
4494 auto isVaList
= [&S
](QualType T
) -> bool {
4495 auto *typedefTy
= T
->getAs
<TypedefType
>();
4498 TypedefDecl
*vaListTypedef
= S
.Context
.getBuiltinVaListDecl();
4500 if (typedefTy
->getDecl() == vaListTypedef
)
4502 if (auto *name
= typedefTy
->getDecl()->getIdentifier())
4503 if (name
->isStr("va_list"))
4505 typedefTy
= typedefTy
->desugar()->getAs
<TypedefType
>();
4506 } while (typedefTy
);
4510 // Local function that checks the nullability for a given pointer declarator.
4511 // Returns true if _Nonnull was inferred.
4512 auto inferPointerNullability
=
4513 [&](SimplePointerKind pointerKind
, SourceLocation pointerLoc
,
4514 SourceLocation pointerEndLoc
,
4515 ParsedAttributesView
&attrs
, AttributePool
&Pool
) -> ParsedAttr
* {
4516 // We've seen a pointer.
4517 if (NumPointersRemaining
> 0)
4518 --NumPointersRemaining
;
4520 // If a nullability attribute is present, there's nothing to do.
4521 if (hasNullabilityAttr(attrs
))
4524 // If we're supposed to infer nullability, do so now.
4525 if (inferNullability
&& !inferNullabilityInnerOnlyComplete
) {
4526 ParsedAttr::Form form
=
4528 ? ParsedAttr::Form::ContextSensitiveKeyword()
4529 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4530 false /*IsRegularKeywordAttribute*/);
4531 ParsedAttr
*nullabilityAttr
= Pool
.create(
4532 S
.getNullabilityKeyword(*inferNullability
), SourceRange(pointerLoc
),
4533 nullptr, SourceLocation(), nullptr, 0, form
);
4535 attrs
.addAtEnd(nullabilityAttr
);
4537 if (inferNullabilityCS
) {
4538 state
.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4539 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability
);
4542 if (pointerLoc
.isValid() &&
4543 complainAboutInferringWithinChunk
!=
4544 PointerWrappingDeclaratorKind::None
) {
4546 S
.Diag(pointerLoc
, diag::warn_nullability_inferred_on_nested_type
);
4547 Diag
<< static_cast<int>(complainAboutInferringWithinChunk
);
4548 fixItNullability(S
, Diag
, pointerLoc
, NullabilityKind::NonNull
);
4551 if (inferNullabilityInnerOnly
)
4552 inferNullabilityInnerOnlyComplete
= true;
4553 return nullabilityAttr
;
4556 // If we're supposed to complain about missing nullability, do so
4557 // now if it's truly missing.
4558 switch (complainAboutMissingNullability
) {
4562 case CAMN_InnerPointers
:
4563 if (NumPointersRemaining
== 0)
4568 checkNullabilityConsistency(S
, pointerKind
, pointerLoc
, pointerEndLoc
);
4573 // If the type itself could have nullability but does not, infer pointer
4574 // nullability and perform consistency checking.
4575 if (S
.CodeSynthesisContexts
.empty()) {
4576 if (shouldHaveNullability(T
) && !T
->getNullability()) {
4578 // Record that we've seen a pointer, but do nothing else.
4579 if (NumPointersRemaining
> 0)
4580 --NumPointersRemaining
;
4582 SimplePointerKind pointerKind
= SimplePointerKind::Pointer
;
4583 if (T
->isBlockPointerType())
4584 pointerKind
= SimplePointerKind::BlockPointer
;
4585 else if (T
->isMemberPointerType())
4586 pointerKind
= SimplePointerKind::MemberPointer
;
4588 if (auto *attr
= inferPointerNullability(
4589 pointerKind
, D
.getDeclSpec().getTypeSpecTypeLoc(),
4590 D
.getDeclSpec().getEndLoc(),
4591 D
.getMutableDeclSpec().getAttributes(),
4592 D
.getMutableDeclSpec().getAttributePool())) {
4593 T
= state
.getAttributedType(
4594 createNullabilityAttr(Context
, *attr
, *inferNullability
), T
, T
);
4599 if (complainAboutMissingNullability
== CAMN_Yes
&& T
->isArrayType() &&
4600 !T
->getNullability() && !isVaList(T
) && D
.isPrototypeContext() &&
4601 !hasOuterPointerLikeChunk(D
, D
.getNumTypeObjects())) {
4602 checkNullabilityConsistency(S
, SimplePointerKind::Array
,
4603 D
.getDeclSpec().getTypeSpecTypeLoc());
4607 bool ExpectNoDerefChunk
=
4608 state
.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref
);
4610 // Walk the DeclTypeInfo, building the recursive type as we go.
4611 // DeclTypeInfos are ordered from the identifier out, which is
4612 // opposite of what we want :).
4614 // Track if the produced type matches the structure of the declarator.
4615 // This is used later to decide if we can fill `TypeLoc` from
4616 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
4617 // an error by replacing the type with `int`.
4618 bool AreDeclaratorChunksValid
= true;
4619 for (unsigned i
= 0, e
= D
.getNumTypeObjects(); i
!= e
; ++i
) {
4620 unsigned chunkIndex
= e
- i
- 1;
4621 state
.setCurrentChunkIndex(chunkIndex
);
4622 DeclaratorChunk
&DeclType
= D
.getTypeObject(chunkIndex
);
4623 IsQualifiedFunction
&= DeclType
.Kind
== DeclaratorChunk::Paren
;
4624 switch (DeclType
.Kind
) {
4625 case DeclaratorChunk::Paren
:
4627 warnAboutRedundantParens(S
, D
, T
);
4628 T
= S
.BuildParenType(T
);
4630 case DeclaratorChunk::BlockPointer
:
4631 // If blocks are disabled, emit an error.
4632 if (!LangOpts
.Blocks
)
4633 S
.Diag(DeclType
.Loc
, diag::err_blocks_disable
) << LangOpts
.OpenCL
;
4635 // Handle pointer nullability.
4636 inferPointerNullability(SimplePointerKind::BlockPointer
, DeclType
.Loc
,
4637 DeclType
.EndLoc
, DeclType
.getAttrs(),
4638 state
.getDeclarator().getAttributePool());
4640 T
= S
.BuildBlockPointerType(T
, D
.getIdentifierLoc(), Name
);
4641 if (DeclType
.Cls
.TypeQuals
|| LangOpts
.OpenCL
) {
4642 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4643 // qualified with const.
4644 if (LangOpts
.OpenCL
)
4645 DeclType
.Cls
.TypeQuals
|= DeclSpec::TQ_const
;
4646 T
= S
.BuildQualifiedType(T
, DeclType
.Loc
, DeclType
.Cls
.TypeQuals
);
4649 case DeclaratorChunk::Pointer
:
4650 // Verify that we're not building a pointer to pointer to function with
4651 // exception specification.
4652 if (LangOpts
.CPlusPlus
&& S
.CheckDistantExceptionSpec(T
)) {
4653 S
.Diag(D
.getIdentifierLoc(), diag::err_distant_exception_spec
);
4654 D
.setInvalidType(true);
4655 // Build the type anyway.
4658 // Handle pointer nullability
4659 inferPointerNullability(SimplePointerKind::Pointer
, DeclType
.Loc
,
4660 DeclType
.EndLoc
, DeclType
.getAttrs(),
4661 state
.getDeclarator().getAttributePool());
4663 if (LangOpts
.ObjC
&& T
->getAs
<ObjCObjectType
>()) {
4664 T
= Context
.getObjCObjectPointerType(T
);
4665 if (DeclType
.Ptr
.TypeQuals
)
4666 T
= S
.BuildQualifiedType(T
, DeclType
.Loc
, DeclType
.Ptr
.TypeQuals
);
4670 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4671 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4672 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4673 if (LangOpts
.OpenCL
) {
4674 if (T
->isImageType() || T
->isSamplerT() || T
->isPipeType() ||
4675 T
->isBlockPointerType()) {
4676 S
.Diag(D
.getIdentifierLoc(), diag::err_opencl_pointer_to_type
) << T
;
4677 D
.setInvalidType(true);
4681 T
= S
.BuildPointerType(T
, DeclType
.Loc
, Name
);
4682 if (DeclType
.Ptr
.TypeQuals
)
4683 T
= S
.BuildQualifiedType(T
, DeclType
.Loc
, DeclType
.Ptr
.TypeQuals
);
4685 case DeclaratorChunk::Reference
: {
4686 // Verify that we're not building a reference to pointer to function with
4687 // exception specification.
4688 if (LangOpts
.CPlusPlus
&& S
.CheckDistantExceptionSpec(T
)) {
4689 S
.Diag(D
.getIdentifierLoc(), diag::err_distant_exception_spec
);
4690 D
.setInvalidType(true);
4691 // Build the type anyway.
4693 T
= S
.BuildReferenceType(T
, DeclType
.Ref
.LValueRef
, DeclType
.Loc
, Name
);
4695 if (DeclType
.Ref
.HasRestrict
)
4696 T
= S
.BuildQualifiedType(T
, DeclType
.Loc
, Qualifiers::Restrict
);
4699 case DeclaratorChunk::Array
: {
4700 // Verify that we're not building an array of pointers to function with
4701 // exception specification.
4702 if (LangOpts
.CPlusPlus
&& S
.CheckDistantExceptionSpec(T
)) {
4703 S
.Diag(D
.getIdentifierLoc(), diag::err_distant_exception_spec
);
4704 D
.setInvalidType(true);
4705 // Build the type anyway.
4707 DeclaratorChunk::ArrayTypeInfo
&ATI
= DeclType
.Arr
;
4708 Expr
*ArraySize
= static_cast<Expr
*>(ATI
.NumElts
);
4709 ArraySizeModifier ASM
;
4711 // Microsoft property fields can have multiple sizeless array chunks
4712 // (i.e. int x[][][]). Skip all of these except one to avoid creating
4713 // bad incomplete array types.
4714 if (chunkIndex
!= 0 && !ArraySize
&&
4715 D
.getDeclSpec().getAttributes().hasMSPropertyAttr()) {
4716 // This is a sizeless chunk. If the next is also, skip this one.
4717 DeclaratorChunk
&NextDeclType
= D
.getTypeObject(chunkIndex
- 1);
4718 if (NextDeclType
.Kind
== DeclaratorChunk::Array
&&
4719 !NextDeclType
.Arr
.NumElts
)
4724 ASM
= ArraySizeModifier::Star
;
4725 else if (ATI
.hasStatic
)
4726 ASM
= ArraySizeModifier::Static
;
4728 ASM
= ArraySizeModifier::Normal
;
4729 if (ASM
== ArraySizeModifier::Star
&& !D
.isPrototypeContext()) {
4730 // FIXME: This check isn't quite right: it allows star in prototypes
4731 // for function definitions, and disallows some edge cases detailed
4732 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4733 S
.Diag(DeclType
.Loc
, diag::err_array_star_outside_prototype
);
4734 ASM
= ArraySizeModifier::Normal
;
4735 D
.setInvalidType(true);
4738 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4739 // shall appear only in a declaration of a function parameter with an
4741 if (ASM
== ArraySizeModifier::Static
|| ATI
.TypeQuals
) {
4742 if (!(D
.isPrototypeContext() ||
4743 D
.getContext() == DeclaratorContext::KNRTypeList
)) {
4744 S
.Diag(DeclType
.Loc
, diag::err_array_static_outside_prototype
)
4745 << (ASM
== ArraySizeModifier::Static
? "'static'"
4746 : "type qualifier");
4747 // Remove the 'static' and the type qualifiers.
4748 if (ASM
== ArraySizeModifier::Static
)
4749 ASM
= ArraySizeModifier::Normal
;
4751 D
.setInvalidType(true);
4754 // C99 6.7.5.2p1: ... and then only in the outermost array type
4756 if (hasOuterPointerLikeChunk(D
, chunkIndex
)) {
4757 S
.Diag(DeclType
.Loc
, diag::err_array_static_not_outermost
)
4758 << (ASM
== ArraySizeModifier::Static
? "'static'"
4759 : "type qualifier");
4760 if (ASM
== ArraySizeModifier::Static
)
4761 ASM
= ArraySizeModifier::Normal
;
4763 D
.setInvalidType(true);
4767 // Array parameters can be marked nullable as well, although it's not
4768 // necessary if they're marked 'static'.
4769 if (complainAboutMissingNullability
== CAMN_Yes
&&
4770 !hasNullabilityAttr(DeclType
.getAttrs()) &&
4771 ASM
!= ArraySizeModifier::Static
&& D
.isPrototypeContext() &&
4772 !hasOuterPointerLikeChunk(D
, chunkIndex
)) {
4773 checkNullabilityConsistency(S
, SimplePointerKind::Array
, DeclType
.Loc
);
4776 T
= S
.BuildArrayType(T
, ASM
, ArraySize
, ATI
.TypeQuals
,
4777 SourceRange(DeclType
.Loc
, DeclType
.EndLoc
), Name
);
4780 case DeclaratorChunk::Function
: {
4781 // If the function declarator has a prototype (i.e. it is not () and
4782 // does not have a K&R-style identifier list), then the arguments are part
4783 // of the type, otherwise the argument list is ().
4784 DeclaratorChunk::FunctionTypeInfo
&FTI
= DeclType
.Fun
;
4785 IsQualifiedFunction
=
4786 FTI
.hasMethodTypeQualifiers() || FTI
.hasRefQualifier();
4788 // Check for auto functions and trailing return type and adjust the
4789 // return type accordingly.
4790 if (!D
.isInvalidType()) {
4791 auto IsClassType
= [&](CXXScopeSpec
&SS
) {
4792 // If there already was an problem with the scope, don’t issue another
4793 // error about the explicit object parameter.
4794 return SS
.isInvalid() ||
4795 isa_and_present
<CXXRecordDecl
>(S
.computeDeclContext(SS
));
4798 // C++23 [dcl.fct]p6:
4800 // An explicit-object-parameter-declaration is a parameter-declaration
4801 // with a this specifier. An explicit-object-parameter-declaration shall
4802 // appear only as the first parameter-declaration of a
4803 // parameter-declaration-list of one of:
4805 // - a declaration of a member function or member function template
4806 // ([class.mem]), or
4808 // - an explicit instantiation ([temp.explicit]) or explicit
4809 // specialization ([temp.expl.spec]) of a templated member function,
4812 // - a lambda-declarator [expr.prim.lambda].
4813 DeclaratorContext C
= D
.getContext();
4814 ParmVarDecl
*First
=
4816 ? dyn_cast_if_present
<ParmVarDecl
>(FTI
.Params
[0].Param
)
4819 bool IsFunctionDecl
= D
.getInnermostNonParenChunk() == &DeclType
;
4820 if (First
&& First
->isExplicitObjectParameter() &&
4821 C
!= DeclaratorContext::LambdaExpr
&&
4823 // Either not a member or nested declarator in a member.
4825 // Note that e.g. 'static' or 'friend' declarations are accepted
4826 // here; we diagnose them later when we build the member function
4827 // because it's easier that way.
4828 (C
!= DeclaratorContext::Member
|| !IsFunctionDecl
) &&
4830 // Allow out-of-line definitions of member functions.
4831 !IsClassType(D
.getCXXScopeSpec())) {
4833 S
.Diag(First
->getBeginLoc(),
4834 diag::err_explicit_object_parameter_nonmember
)
4835 << /*non-member*/ 2 << /*function*/ 0
4836 << First
->getSourceRange();
4838 S
.Diag(First
->getBeginLoc(),
4839 diag::err_explicit_object_parameter_invalid
)
4840 << First
->getSourceRange();
4843 AreDeclaratorChunksValid
= false;
4846 // trailing-return-type is only required if we're declaring a function,
4847 // and not, for instance, a pointer to a function.
4848 if (D
.getDeclSpec().hasAutoTypeSpec() &&
4849 !FTI
.hasTrailingReturnType() && chunkIndex
== 0) {
4850 if (!S
.getLangOpts().CPlusPlus14
) {
4851 S
.Diag(D
.getDeclSpec().getTypeSpecTypeLoc(),
4852 D
.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4853 ? diag::err_auto_missing_trailing_return
4854 : diag::err_deduced_return_type
);
4856 D
.setInvalidType(true);
4857 AreDeclaratorChunksValid
= false;
4859 S
.Diag(D
.getDeclSpec().getTypeSpecTypeLoc(),
4860 diag::warn_cxx11_compat_deduced_return_type
);
4862 } else if (FTI
.hasTrailingReturnType()) {
4863 // T must be exactly 'auto' at this point. See CWG issue 681.
4864 if (isa
<ParenType
>(T
)) {
4865 S
.Diag(D
.getBeginLoc(), diag::err_trailing_return_in_parens
)
4866 << T
<< D
.getSourceRange();
4867 D
.setInvalidType(true);
4868 // FIXME: recover and fill decls in `TypeLoc`s.
4869 AreDeclaratorChunksValid
= false;
4870 } else if (D
.getName().getKind() ==
4871 UnqualifiedIdKind::IK_DeductionGuideName
) {
4872 if (T
!= Context
.DependentTy
) {
4873 S
.Diag(D
.getDeclSpec().getBeginLoc(),
4874 diag::err_deduction_guide_with_complex_decl
)
4875 << D
.getSourceRange();
4876 D
.setInvalidType(true);
4877 // FIXME: recover and fill decls in `TypeLoc`s.
4878 AreDeclaratorChunksValid
= false;
4880 } else if (D
.getContext() != DeclaratorContext::LambdaExpr
&&
4881 (T
.hasQualifiers() || !isa
<AutoType
>(T
) ||
4882 cast
<AutoType
>(T
)->getKeyword() !=
4883 AutoTypeKeyword::Auto
||
4884 cast
<AutoType
>(T
)->isConstrained())) {
4885 // Attach a valid source location for diagnostics on functions with
4886 // trailing return types missing 'auto'. Attempt to get the location
4887 // from the declared type; if invalid, fall back to the trailing
4888 // return type's location.
4889 SourceLocation Loc
= D
.getDeclSpec().getTypeSpecTypeLoc();
4890 SourceRange SR
= D
.getDeclSpec().getSourceRange();
4891 if (Loc
.isInvalid()) {
4892 Loc
= FTI
.getTrailingReturnTypeLoc();
4893 SR
= D
.getSourceRange();
4895 S
.Diag(Loc
, diag::err_trailing_return_without_auto
) << T
<< SR
;
4896 D
.setInvalidType(true);
4897 // FIXME: recover and fill decls in `TypeLoc`s.
4898 AreDeclaratorChunksValid
= false;
4900 T
= S
.GetTypeFromParser(FTI
.getTrailingReturnType(), &TInfo
);
4902 // An error occurred parsing the trailing return type.
4904 D
.setInvalidType(true);
4905 } else if (AutoType
*Auto
= T
->getContainedAutoType()) {
4906 // If the trailing return type contains an `auto`, we may need to
4907 // invent a template parameter for it, for cases like
4908 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
4909 InventedTemplateParameterInfo
*InventedParamInfo
= nullptr;
4910 if (D
.getContext() == DeclaratorContext::Prototype
)
4911 InventedParamInfo
= &S
.InventedParameterInfos
.back();
4912 else if (D
.getContext() == DeclaratorContext::LambdaExprParameter
)
4913 InventedParamInfo
= S
.getCurLambda();
4914 if (InventedParamInfo
) {
4915 std::tie(T
, TInfo
) = InventTemplateParameter(
4916 state
, T
, TInfo
, Auto
, *InventedParamInfo
);
4920 // This function type is not the type of the entity being declared,
4921 // so checking the 'auto' is not the responsibility of this chunk.
4925 // C99 6.7.5.3p1: The return type may not be a function or array type.
4926 // For conversion functions, we'll diagnose this particular error later.
4927 if (!D
.isInvalidType() && (T
->isArrayType() || T
->isFunctionType()) &&
4928 (D
.getName().getKind() !=
4929 UnqualifiedIdKind::IK_ConversionFunctionId
)) {
4930 unsigned diagID
= diag::err_func_returning_array_function
;
4931 // Last processing chunk in block context means this function chunk
4932 // represents the block.
4933 if (chunkIndex
== 0 &&
4934 D
.getContext() == DeclaratorContext::BlockLiteral
)
4935 diagID
= diag::err_block_returning_array_function
;
4936 S
.Diag(DeclType
.Loc
, diagID
) << T
->isFunctionType() << T
;
4938 D
.setInvalidType(true);
4939 AreDeclaratorChunksValid
= false;
4942 // Do not allow returning half FP value.
4943 // FIXME: This really should be in BuildFunctionType.
4944 if (T
->isHalfType()) {
4945 if (S
.getLangOpts().OpenCL
) {
4946 if (!S
.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
4948 S
.Diag(D
.getIdentifierLoc(), diag::err_opencl_invalid_return
)
4949 << T
<< 0 /*pointer hint*/;
4950 D
.setInvalidType(true);
4952 } else if (!S
.getLangOpts().NativeHalfArgsAndReturns
&&
4953 !S
.Context
.getTargetInfo().allowHalfArgsAndReturns()) {
4954 S
.Diag(D
.getIdentifierLoc(),
4955 diag::err_parameters_retval_cannot_have_fp16_type
) << 1;
4956 D
.setInvalidType(true);
4960 if (LangOpts
.OpenCL
) {
4961 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4963 if (T
->isBlockPointerType() || T
->isImageType() || T
->isSamplerT() ||
4965 S
.Diag(D
.getIdentifierLoc(), diag::err_opencl_invalid_return
)
4966 << T
<< 1 /*hint off*/;
4967 D
.setInvalidType(true);
4969 // OpenCL doesn't support variadic functions and blocks
4970 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4971 // We also allow here any toolchain reserved identifiers.
4972 if (FTI
.isVariadic
&&
4973 !S
.getOpenCLOptions().isAvailableOption(
4974 "__cl_clang_variadic_functions", S
.getLangOpts()) &&
4975 !(D
.getIdentifier() &&
4976 ((D
.getIdentifier()->getName() == "printf" &&
4977 LangOpts
.getOpenCLCompatibleVersion() >= 120) ||
4978 D
.getIdentifier()->getName().starts_with("__")))) {
4979 S
.Diag(D
.getIdentifierLoc(), diag::err_opencl_variadic_function
);
4980 D
.setInvalidType(true);
4984 // Methods cannot return interface types. All ObjC objects are
4985 // passed by reference.
4986 if (T
->isObjCObjectType()) {
4987 SourceLocation DiagLoc
, FixitLoc
;
4989 DiagLoc
= TInfo
->getTypeLoc().getBeginLoc();
4990 FixitLoc
= S
.getLocForEndOfToken(TInfo
->getTypeLoc().getEndLoc());
4992 DiagLoc
= D
.getDeclSpec().getTypeSpecTypeLoc();
4993 FixitLoc
= S
.getLocForEndOfToken(D
.getDeclSpec().getEndLoc());
4995 S
.Diag(DiagLoc
, diag::err_object_cannot_be_passed_returned_by_value
)
4997 << FixItHint::CreateInsertion(FixitLoc
, "*");
4999 T
= Context
.getObjCObjectPointerType(T
);
5002 TLB
.pushFullCopy(TInfo
->getTypeLoc());
5003 ObjCObjectPointerTypeLoc TLoc
= TLB
.push
<ObjCObjectPointerTypeLoc
>(T
);
5004 TLoc
.setStarLoc(FixitLoc
);
5005 TInfo
= TLB
.getTypeSourceInfo(Context
, T
);
5007 AreDeclaratorChunksValid
= false;
5010 D
.setInvalidType(true);
5013 // cv-qualifiers on return types are pointless except when the type is a
5014 // class type in C++.
5015 if ((T
.getCVRQualifiers() || T
->isAtomicType()) &&
5016 !(S
.getLangOpts().CPlusPlus
&&
5017 (T
->isDependentType() || T
->isRecordType()))) {
5018 if (T
->isVoidType() && !S
.getLangOpts().CPlusPlus
&&
5019 D
.getFunctionDefinitionKind() ==
5020 FunctionDefinitionKind::Definition
) {
5021 // [6.9.1/3] qualified void return is invalid on a C
5022 // function definition. Apparently ok on declarations and
5023 // in C++ though (!)
5024 S
.Diag(DeclType
.Loc
, diag::err_func_returning_qualified_void
) << T
;
5026 diagnoseRedundantReturnTypeQualifiers(S
, T
, D
, chunkIndex
);
5028 // C++2a [dcl.fct]p12:
5029 // A volatile-qualified return type is deprecated
5030 if (T
.isVolatileQualified() && S
.getLangOpts().CPlusPlus20
)
5031 S
.Diag(DeclType
.Loc
, diag::warn_deprecated_volatile_return
) << T
;
5034 // Objective-C ARC ownership qualifiers are ignored on the function
5035 // return type (by type canonicalization). Complain if this attribute
5036 // was written here.
5037 if (T
.getQualifiers().hasObjCLifetime()) {
5038 SourceLocation AttrLoc
;
5039 if (chunkIndex
+ 1 < D
.getNumTypeObjects()) {
5040 DeclaratorChunk ReturnTypeChunk
= D
.getTypeObject(chunkIndex
+ 1);
5041 for (const ParsedAttr
&AL
: ReturnTypeChunk
.getAttrs()) {
5042 if (AL
.getKind() == ParsedAttr::AT_ObjCOwnership
) {
5043 AttrLoc
= AL
.getLoc();
5048 if (AttrLoc
.isInvalid()) {
5049 for (const ParsedAttr
&AL
: D
.getDeclSpec().getAttributes()) {
5050 if (AL
.getKind() == ParsedAttr::AT_ObjCOwnership
) {
5051 AttrLoc
= AL
.getLoc();
5057 if (AttrLoc
.isValid()) {
5058 // The ownership attributes are almost always written via
5060 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5061 if (AttrLoc
.isMacroID())
5063 S
.SourceMgr
.getImmediateExpansionRange(AttrLoc
).getBegin();
5065 S
.Diag(AttrLoc
, diag::warn_arc_lifetime_result_type
)
5066 << T
.getQualifiers().getObjCLifetime();
5070 if (LangOpts
.CPlusPlus
&& D
.getDeclSpec().hasTagDefinition()) {
5072 // Types shall not be defined in return or parameter types.
5073 TagDecl
*Tag
= cast
<TagDecl
>(D
.getDeclSpec().getRepAsDecl());
5074 S
.Diag(Tag
->getLocation(), diag::err_type_defined_in_result_type
)
5075 << Context
.getTypeDeclType(Tag
);
5078 // Exception specs are not allowed in typedefs. Complain, but add it
5080 if (IsTypedefName
&& FTI
.getExceptionSpecType() && !LangOpts
.CPlusPlus17
)
5081 S
.Diag(FTI
.getExceptionSpecLocBeg(),
5082 diag::err_exception_spec_in_typedef
)
5083 << (D
.getContext() == DeclaratorContext::AliasDecl
||
5084 D
.getContext() == DeclaratorContext::AliasTemplate
);
5086 // If we see "T var();" or "T var(T());" at block scope, it is probably
5087 // an attempt to initialize a variable, not a function declaration.
5088 if (FTI
.isAmbiguous
)
5089 warnAboutAmbiguousFunction(S
, D
, DeclType
, T
);
5091 FunctionType::ExtInfo
EI(
5092 getCCForDeclaratorChunk(S
, D
, DeclType
.getAttrs(), FTI
, chunkIndex
));
5094 // OpenCL disallows functions without a prototype, but it doesn't enforce
5095 // strict prototypes as in C23 because it allows a function definition to
5096 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5097 if (!FTI
.NumParams
&& !FTI
.isVariadic
&&
5098 !LangOpts
.requiresStrictPrototypes() && !LangOpts
.OpenCL
) {
5099 // Simple void foo(), where the incoming T is the result type.
5100 T
= Context
.getFunctionNoProtoType(T
, EI
);
5102 // We allow a zero-parameter variadic function in C if the
5103 // function is marked with the "overloadable" attribute. Scan
5104 // for this attribute now. We also allow it in C23 per WG14 N2975.
5105 if (!FTI
.NumParams
&& FTI
.isVariadic
&& !LangOpts
.CPlusPlus
) {
5107 S
.Diag(FTI
.getEllipsisLoc(),
5108 diag::warn_c17_compat_ellipsis_only_parameter
);
5109 else if (!D
.getDeclarationAttributes().hasAttribute(
5110 ParsedAttr::AT_Overloadable
) &&
5111 !D
.getAttributes().hasAttribute(
5112 ParsedAttr::AT_Overloadable
) &&
5113 !D
.getDeclSpec().getAttributes().hasAttribute(
5114 ParsedAttr::AT_Overloadable
))
5115 S
.Diag(FTI
.getEllipsisLoc(), diag::err_ellipsis_first_param
);
5118 if (FTI
.NumParams
&& FTI
.Params
[0].Param
== nullptr) {
5119 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5121 S
.Diag(FTI
.Params
[0].IdentLoc
,
5122 diag::err_ident_list_in_fn_declaration
);
5123 D
.setInvalidType(true);
5124 // Recover by creating a K&R-style function type, if possible.
5125 T
= (!LangOpts
.requiresStrictPrototypes() && !LangOpts
.OpenCL
)
5126 ? Context
.getFunctionNoProtoType(T
, EI
)
5128 AreDeclaratorChunksValid
= false;
5132 FunctionProtoType::ExtProtoInfo EPI
;
5134 EPI
.Variadic
= FTI
.isVariadic
;
5135 EPI
.EllipsisLoc
= FTI
.getEllipsisLoc();
5136 EPI
.HasTrailingReturn
= FTI
.hasTrailingReturnType();
5137 EPI
.TypeQuals
.addCVRUQualifiers(
5138 FTI
.MethodQualifiers
? FTI
.MethodQualifiers
->getTypeQualifiers()
5140 EPI
.RefQualifier
= !FTI
.hasRefQualifier()? RQ_None
5141 : FTI
.RefQualifierIsLValueRef
? RQ_LValue
5144 // Otherwise, we have a function with a parameter list that is
5145 // potentially variadic.
5146 SmallVector
<QualType
, 16> ParamTys
;
5147 ParamTys
.reserve(FTI
.NumParams
);
5149 SmallVector
<FunctionProtoType::ExtParameterInfo
, 16>
5150 ExtParameterInfos(FTI
.NumParams
);
5151 bool HasAnyInterestingExtParameterInfos
= false;
5153 for (unsigned i
= 0, e
= FTI
.NumParams
; i
!= e
; ++i
) {
5154 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(FTI
.Params
[i
].Param
);
5155 QualType ParamTy
= Param
->getType();
5156 assert(!ParamTy
.isNull() && "Couldn't parse type?");
5158 // Look for 'void'. void is allowed only as a single parameter to a
5159 // function with no other parameters (C99 6.7.5.3p10). We record
5160 // int(void) as a FunctionProtoType with an empty parameter list.
5161 if (ParamTy
->isVoidType()) {
5162 // If this is something like 'float(int, void)', reject it. 'void'
5163 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5164 // have parameters of incomplete type.
5165 if (FTI
.NumParams
!= 1 || FTI
.isVariadic
) {
5166 S
.Diag(FTI
.Params
[i
].IdentLoc
, diag::err_void_only_param
);
5167 ParamTy
= Context
.IntTy
;
5168 Param
->setType(ParamTy
);
5169 } else if (FTI
.Params
[i
].Ident
) {
5170 // Reject, but continue to parse 'int(void abc)'.
5171 S
.Diag(FTI
.Params
[i
].IdentLoc
, diag::err_param_with_void_type
);
5172 ParamTy
= Context
.IntTy
;
5173 Param
->setType(ParamTy
);
5175 // Reject, but continue to parse 'float(const void)'.
5176 if (ParamTy
.hasQualifiers())
5177 S
.Diag(DeclType
.Loc
, diag::err_void_param_qualified
);
5179 // Reject, but continue to parse 'float(this void)' as
5181 if (Param
->isExplicitObjectParameter()) {
5182 S
.Diag(Param
->getLocation(),
5183 diag::err_void_explicit_object_param
);
5184 Param
->setExplicitObjectParameterLoc(SourceLocation());
5187 // Do not add 'void' to the list.
5190 } else if (ParamTy
->isHalfType()) {
5191 // Disallow half FP parameters.
5192 // FIXME: This really should be in BuildFunctionType.
5193 if (S
.getLangOpts().OpenCL
) {
5194 if (!S
.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5196 S
.Diag(Param
->getLocation(), diag::err_opencl_invalid_param
)
5199 Param
->setInvalidDecl();
5201 } else if (!S
.getLangOpts().NativeHalfArgsAndReturns
&&
5202 !S
.Context
.getTargetInfo().allowHalfArgsAndReturns()) {
5203 S
.Diag(Param
->getLocation(),
5204 diag::err_parameters_retval_cannot_have_fp16_type
) << 0;
5207 } else if (!FTI
.hasPrototype
) {
5208 if (Context
.isPromotableIntegerType(ParamTy
)) {
5209 ParamTy
= Context
.getPromotedIntegerType(ParamTy
);
5210 Param
->setKNRPromoted(true);
5211 } else if (const BuiltinType
*BTy
= ParamTy
->getAs
<BuiltinType
>()) {
5212 if (BTy
->getKind() == BuiltinType::Float
) {
5213 ParamTy
= Context
.DoubleTy
;
5214 Param
->setKNRPromoted(true);
5217 } else if (S
.getLangOpts().OpenCL
&& ParamTy
->isBlockPointerType()) {
5218 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5219 S
.Diag(Param
->getLocation(), diag::err_opencl_invalid_param
)
5220 << ParamTy
<< 1 /*hint off*/;
5224 if (LangOpts
.ObjCAutoRefCount
&& Param
->hasAttr
<NSConsumedAttr
>()) {
5225 ExtParameterInfos
[i
] = ExtParameterInfos
[i
].withIsConsumed(true);
5226 HasAnyInterestingExtParameterInfos
= true;
5229 if (auto attr
= Param
->getAttr
<ParameterABIAttr
>()) {
5230 ExtParameterInfos
[i
] =
5231 ExtParameterInfos
[i
].withABI(attr
->getABI());
5232 HasAnyInterestingExtParameterInfos
= true;
5235 if (Param
->hasAttr
<PassObjectSizeAttr
>()) {
5236 ExtParameterInfos
[i
] = ExtParameterInfos
[i
].withHasPassObjectSize();
5237 HasAnyInterestingExtParameterInfos
= true;
5240 if (Param
->hasAttr
<NoEscapeAttr
>()) {
5241 ExtParameterInfos
[i
] = ExtParameterInfos
[i
].withIsNoEscape(true);
5242 HasAnyInterestingExtParameterInfos
= true;
5245 ParamTys
.push_back(ParamTy
);
5248 if (HasAnyInterestingExtParameterInfos
) {
5249 EPI
.ExtParameterInfos
= ExtParameterInfos
.data();
5250 checkExtParameterInfos(S
, ParamTys
, EPI
,
5251 [&](unsigned i
) { return FTI
.Params
[i
].Param
->getLocation(); });
5254 SmallVector
<QualType
, 4> Exceptions
;
5255 SmallVector
<ParsedType
, 2> DynamicExceptions
;
5256 SmallVector
<SourceRange
, 2> DynamicExceptionRanges
;
5257 Expr
*NoexceptExpr
= nullptr;
5259 if (FTI
.getExceptionSpecType() == EST_Dynamic
) {
5260 // FIXME: It's rather inefficient to have to split into two vectors
5262 unsigned N
= FTI
.getNumExceptions();
5263 DynamicExceptions
.reserve(N
);
5264 DynamicExceptionRanges
.reserve(N
);
5265 for (unsigned I
= 0; I
!= N
; ++I
) {
5266 DynamicExceptions
.push_back(FTI
.Exceptions
[I
].Ty
);
5267 DynamicExceptionRanges
.push_back(FTI
.Exceptions
[I
].Range
);
5269 } else if (isComputedNoexcept(FTI
.getExceptionSpecType())) {
5270 NoexceptExpr
= FTI
.NoexceptExpr
;
5273 S
.checkExceptionSpecification(D
.isFunctionDeclarationContext(),
5274 FTI
.getExceptionSpecType(),
5276 DynamicExceptionRanges
,
5281 // FIXME: Set address space from attrs for C++ mode here.
5282 // OpenCLCPlusPlus: A class member function has an address space.
5283 auto IsClassMember
= [&]() {
5284 return (!state
.getDeclarator().getCXXScopeSpec().isEmpty() &&
5285 state
.getDeclarator()
5288 ->getKind() == NestedNameSpecifier::TypeSpec
) ||
5289 state
.getDeclarator().getContext() ==
5290 DeclaratorContext::Member
||
5291 state
.getDeclarator().getContext() ==
5292 DeclaratorContext::LambdaExpr
;
5295 if (state
.getSema().getLangOpts().OpenCLCPlusPlus
&& IsClassMember()) {
5296 LangAS ASIdx
= LangAS::Default
;
5297 // Take address space attr if any and mark as invalid to avoid adding
5298 // them later while creating QualType.
5299 if (FTI
.MethodQualifiers
)
5300 for (ParsedAttr
&attr
: FTI
.MethodQualifiers
->getAttributes()) {
5301 LangAS ASIdxNew
= attr
.asOpenCLLangAS();
5302 if (DiagnoseMultipleAddrSpaceAttributes(S
, ASIdx
, ASIdxNew
,
5304 D
.setInvalidType(true);
5308 // If a class member function's address space is not set, set it to
5311 (ASIdx
== LangAS::Default
? S
.getDefaultCXXMethodAddrSpace()
5313 EPI
.TypeQuals
.addAddressSpace(AS
);
5315 T
= Context
.getFunctionType(T
, ParamTys
, EPI
);
5319 case DeclaratorChunk::MemberPointer
: {
5320 // The scope spec must refer to a class, or be dependent.
5321 CXXScopeSpec
&SS
= DeclType
.Mem
.Scope();
5324 // Handle pointer nullability.
5325 inferPointerNullability(SimplePointerKind::MemberPointer
, DeclType
.Loc
,
5326 DeclType
.EndLoc
, DeclType
.getAttrs(),
5327 state
.getDeclarator().getAttributePool());
5329 if (SS
.isInvalid()) {
5330 // Avoid emitting extra errors if we already errored on the scope.
5331 D
.setInvalidType(true);
5332 } else if (S
.isDependentScopeSpecifier(SS
) ||
5333 isa_and_nonnull
<CXXRecordDecl
>(S
.computeDeclContext(SS
))) {
5334 NestedNameSpecifier
*NNS
= SS
.getScopeRep();
5335 NestedNameSpecifier
*NNSPrefix
= NNS
->getPrefix();
5336 switch (NNS
->getKind()) {
5337 case NestedNameSpecifier::Identifier
:
5338 ClsType
= Context
.getDependentNameType(
5339 ElaboratedTypeKeyword::None
, NNSPrefix
, NNS
->getAsIdentifier());
5342 case NestedNameSpecifier::Namespace
:
5343 case NestedNameSpecifier::NamespaceAlias
:
5344 case NestedNameSpecifier::Global
:
5345 case NestedNameSpecifier::Super
:
5346 llvm_unreachable("Nested-name-specifier must name a type");
5348 case NestedNameSpecifier::TypeSpec
:
5349 case NestedNameSpecifier::TypeSpecWithTemplate
:
5350 ClsType
= QualType(NNS
->getAsType(), 0);
5351 // Note: if the NNS has a prefix and ClsType is a nondependent
5352 // TemplateSpecializationType, then the NNS prefix is NOT included
5353 // in ClsType; hence we wrap ClsType into an ElaboratedType.
5354 // NOTE: in particular, no wrap occurs if ClsType already is an
5355 // Elaborated, DependentName, or DependentTemplateSpecialization.
5356 if (isa
<TemplateSpecializationType
>(NNS
->getAsType()))
5357 ClsType
= Context
.getElaboratedType(ElaboratedTypeKeyword::None
,
5358 NNSPrefix
, ClsType
);
5362 S
.Diag(DeclType
.Mem
.Scope().getBeginLoc(),
5363 diag::err_illegal_decl_mempointer_in_nonclass
)
5364 << (D
.getIdentifier() ? D
.getIdentifier()->getName() : "type name")
5365 << DeclType
.Mem
.Scope().getRange();
5366 D
.setInvalidType(true);
5369 if (!ClsType
.isNull())
5370 T
= S
.BuildMemberPointerType(T
, ClsType
, DeclType
.Loc
,
5373 AreDeclaratorChunksValid
= false;
5377 D
.setInvalidType(true);
5378 AreDeclaratorChunksValid
= false;
5379 } else if (DeclType
.Mem
.TypeQuals
) {
5380 T
= S
.BuildQualifiedType(T
, DeclType
.Loc
, DeclType
.Mem
.TypeQuals
);
5385 case DeclaratorChunk::Pipe
: {
5386 T
= S
.BuildReadPipeType(T
, DeclType
.Loc
);
5387 processTypeAttrs(state
, T
, TAL_DeclSpec
,
5388 D
.getMutableDeclSpec().getAttributes());
5394 D
.setInvalidType(true);
5396 AreDeclaratorChunksValid
= false;
5399 // See if there are any attributes on this declarator chunk.
5400 processTypeAttrs(state
, T
, TAL_DeclChunk
, DeclType
.getAttrs(),
5401 S
.CUDA().IdentifyTarget(D
.getAttributes()));
5403 if (DeclType
.Kind
!= DeclaratorChunk::Paren
) {
5404 if (ExpectNoDerefChunk
&& !IsNoDerefableChunk(DeclType
))
5405 S
.Diag(DeclType
.Loc
, diag::warn_noderef_on_non_pointer_or_array
);
5407 ExpectNoDerefChunk
= state
.didParseNoDeref();
5411 if (ExpectNoDerefChunk
)
5412 S
.Diag(state
.getDeclarator().getBeginLoc(),
5413 diag::warn_noderef_on_non_pointer_or_array
);
5415 // GNU warning -Wstrict-prototypes
5416 // Warn if a function declaration or definition is without a prototype.
5417 // This warning is issued for all kinds of unprototyped function
5418 // declarations (i.e. function type typedef, function pointer etc.)
5420 // The empty list in a function declarator that is not part of a definition
5421 // of that function specifies that no information about the number or types
5422 // of the parameters is supplied.
5423 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5424 // function declarations whose behavior changes in C23.
5425 if (!LangOpts
.requiresStrictPrototypes()) {
5426 bool IsBlock
= false;
5427 for (const DeclaratorChunk
&DeclType
: D
.type_objects()) {
5428 switch (DeclType
.Kind
) {
5429 case DeclaratorChunk::BlockPointer
:
5432 case DeclaratorChunk::Function
: {
5433 const DeclaratorChunk::FunctionTypeInfo
&FTI
= DeclType
.Fun
;
5434 // We suppress the warning when there's no LParen location, as this
5435 // indicates the declaration was an implicit declaration, which gets
5436 // warned about separately via -Wimplicit-function-declaration. We also
5437 // suppress the warning when we know the function has a prototype.
5438 if (!FTI
.hasPrototype
&& FTI
.NumParams
== 0 && !FTI
.isVariadic
&&
5439 FTI
.getLParenLoc().isValid())
5440 S
.Diag(DeclType
.Loc
, diag::warn_strict_prototypes
)
5442 << FixItHint::CreateInsertion(FTI
.getRParenLoc(), "void");
5452 assert(!T
.isNull() && "T must not be null after this point");
5454 if (LangOpts
.CPlusPlus
&& T
->isFunctionType()) {
5455 const FunctionProtoType
*FnTy
= T
->getAs
<FunctionProtoType
>();
5456 assert(FnTy
&& "Why oh why is there not a FunctionProtoType here?");
5459 // A cv-qualifier-seq shall only be part of the function type
5460 // for a nonstatic member function, the function type to which a pointer
5461 // to member refers, or the top-level function type of a function typedef
5464 // Core issue 547 also allows cv-qualifiers on function types that are
5465 // top-level template type arguments.
5469 ExplicitObjectMember
,
5472 if (D
.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName
)
5473 Kind
= DeductionGuide
;
5474 else if (!D
.getCXXScopeSpec().isSet()) {
5475 if ((D
.getContext() == DeclaratorContext::Member
||
5476 D
.getContext() == DeclaratorContext::LambdaExpr
) &&
5477 !D
.getDeclSpec().isFriendSpecified())
5480 DeclContext
*DC
= S
.computeDeclContext(D
.getCXXScopeSpec());
5481 if (!DC
|| DC
->isRecord())
5485 if (Kind
== Member
) {
5487 if (D
.isFunctionDeclarator(I
)) {
5488 const DeclaratorChunk
&Chunk
= D
.getTypeObject(I
);
5489 if (Chunk
.Fun
.NumParams
) {
5490 auto *P
= dyn_cast_or_null
<ParmVarDecl
>(Chunk
.Fun
.Params
->Param
);
5491 if (P
&& P
->isExplicitObjectParameter())
5492 Kind
= ExplicitObjectMember
;
5497 // C++11 [dcl.fct]p6 (w/DR1417):
5498 // An attempt to specify a function type with a cv-qualifier-seq or a
5499 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5500 // - the function type for a non-static member function,
5501 // - the function type to which a pointer to member refers,
5502 // - the top-level function type of a function typedef declaration or
5503 // alias-declaration,
5504 // - the type-id in the default argument of a type-parameter, or
5505 // - the type-id of a template-argument for a type-parameter
5507 // C++23 [dcl.fct]p6 (P0847R7)
5508 // ... A member-declarator with an explicit-object-parameter-declaration
5509 // shall not include a ref-qualifier or a cv-qualifier-seq and shall not be
5510 // declared static or virtual ...
5512 // FIXME: Checking this here is insufficient. We accept-invalid on:
5514 // template<typename T> struct S { void f(T); };
5515 // S<int() const> s;
5517 // ... for instance.
5518 if (IsQualifiedFunction
&&
5519 // Check for non-static member function and not and
5520 // explicit-object-parameter-declaration
5521 (Kind
!= Member
|| D
.isExplicitObjectMemberFunction() ||
5522 D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static
||
5523 (D
.getContext() == clang::DeclaratorContext::Member
&&
5524 D
.isStaticMember())) &&
5525 !IsTypedefName
&& D
.getContext() != DeclaratorContext::TemplateArg
&&
5526 D
.getContext() != DeclaratorContext::TemplateTypeArg
) {
5527 SourceLocation Loc
= D
.getBeginLoc();
5528 SourceRange RemovalRange
;
5530 if (D
.isFunctionDeclarator(I
)) {
5531 SmallVector
<SourceLocation
, 4> RemovalLocs
;
5532 const DeclaratorChunk
&Chunk
= D
.getTypeObject(I
);
5533 assert(Chunk
.Kind
== DeclaratorChunk::Function
);
5535 if (Chunk
.Fun
.hasRefQualifier())
5536 RemovalLocs
.push_back(Chunk
.Fun
.getRefQualifierLoc());
5538 if (Chunk
.Fun
.hasMethodTypeQualifiers())
5539 Chunk
.Fun
.MethodQualifiers
->forEachQualifier(
5540 [&](DeclSpec::TQ TypeQual
, StringRef QualName
,
5541 SourceLocation SL
) { RemovalLocs
.push_back(SL
); });
5543 if (!RemovalLocs
.empty()) {
5544 llvm::sort(RemovalLocs
,
5545 BeforeThanCompare
<SourceLocation
>(S
.getSourceManager()));
5546 RemovalRange
= SourceRange(RemovalLocs
.front(), RemovalLocs
.back());
5547 Loc
= RemovalLocs
.front();
5551 S
.Diag(Loc
, diag::err_invalid_qualified_function_type
)
5552 << Kind
<< D
.isFunctionDeclarator() << T
5553 << getFunctionQualifiersAsString(FnTy
)
5554 << FixItHint::CreateRemoval(RemovalRange
);
5556 // Strip the cv-qualifiers and ref-qualifiers from the type.
5557 FunctionProtoType::ExtProtoInfo EPI
= FnTy
->getExtProtoInfo();
5558 EPI
.TypeQuals
.removeCVRQualifiers();
5559 EPI
.RefQualifier
= RQ_None
;
5561 T
= Context
.getFunctionType(FnTy
->getReturnType(), FnTy
->getParamTypes(),
5563 // Rebuild any parens around the identifier in the function type.
5564 for (unsigned i
= 0, e
= D
.getNumTypeObjects(); i
!= e
; ++i
) {
5565 if (D
.getTypeObject(i
).Kind
!= DeclaratorChunk::Paren
)
5567 T
= S
.BuildParenType(T
);
5572 // Apply any undistributed attributes from the declaration or declarator.
5573 ParsedAttributesView NonSlidingAttrs
;
5574 for (ParsedAttr
&AL
: D
.getDeclarationAttributes()) {
5575 if (!AL
.slidesFromDeclToDeclSpecLegacyBehavior()) {
5576 NonSlidingAttrs
.addAtEnd(&AL
);
5579 processTypeAttrs(state
, T
, TAL_DeclName
, NonSlidingAttrs
);
5580 processTypeAttrs(state
, T
, TAL_DeclName
, D
.getAttributes());
5582 // Diagnose any ignored type attributes.
5583 state
.diagnoseIgnoredTypeAttrs(T
);
5585 // C++0x [dcl.constexpr]p9:
5586 // A constexpr specifier used in an object declaration declares the object
5588 if (D
.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr
&&
5592 // C++2a [dcl.fct]p4:
5593 // A parameter with volatile-qualified type is deprecated
5594 if (T
.isVolatileQualified() && S
.getLangOpts().CPlusPlus20
&&
5595 (D
.getContext() == DeclaratorContext::Prototype
||
5596 D
.getContext() == DeclaratorContext::LambdaExprParameter
))
5597 S
.Diag(D
.getIdentifierLoc(), diag::warn_deprecated_volatile_param
) << T
;
5599 // If there was an ellipsis in the declarator, the declaration declares a
5600 // parameter pack whose type may be a pack expansion type.
5601 if (D
.hasEllipsis()) {
5602 // C++0x [dcl.fct]p13:
5603 // A declarator-id or abstract-declarator containing an ellipsis shall
5604 // only be used in a parameter-declaration. Such a parameter-declaration
5605 // is a parameter pack (14.5.3). [...]
5606 switch (D
.getContext()) {
5607 case DeclaratorContext::Prototype
:
5608 case DeclaratorContext::LambdaExprParameter
:
5609 case DeclaratorContext::RequiresExpr
:
5610 // C++0x [dcl.fct]p13:
5611 // [...] When it is part of a parameter-declaration-clause, the
5612 // parameter pack is a function parameter pack (14.5.3). The type T
5613 // of the declarator-id of the function parameter pack shall contain
5614 // a template parameter pack; each template parameter pack in T is
5615 // expanded by the function parameter pack.
5617 // We represent function parameter packs as function parameters whose
5618 // type is a pack expansion.
5619 if (!T
->containsUnexpandedParameterPack() &&
5620 (!LangOpts
.CPlusPlus20
|| !T
->getContainedAutoType())) {
5621 S
.Diag(D
.getEllipsisLoc(),
5622 diag::err_function_parameter_pack_without_parameter_packs
)
5623 << T
<< D
.getSourceRange();
5624 D
.setEllipsisLoc(SourceLocation());
5626 T
= Context
.getPackExpansionType(T
, std::nullopt
,
5627 /*ExpectPackInType=*/false);
5630 case DeclaratorContext::TemplateParam
:
5631 // C++0x [temp.param]p15:
5632 // If a template-parameter is a [...] is a parameter-declaration that
5633 // declares a parameter pack (8.3.5), then the template-parameter is a
5634 // template parameter pack (14.5.3).
5636 // Note: core issue 778 clarifies that, if there are any unexpanded
5637 // parameter packs in the type of the non-type template parameter, then
5638 // it expands those parameter packs.
5639 if (T
->containsUnexpandedParameterPack())
5640 T
= Context
.getPackExpansionType(T
, std::nullopt
);
5642 S
.Diag(D
.getEllipsisLoc(),
5643 LangOpts
.CPlusPlus11
5644 ? diag::warn_cxx98_compat_variadic_templates
5645 : diag::ext_variadic_templates
);
5648 case DeclaratorContext::File
:
5649 case DeclaratorContext::KNRTypeList
:
5650 case DeclaratorContext::ObjCParameter
: // FIXME: special diagnostic here?
5651 case DeclaratorContext::ObjCResult
: // FIXME: special diagnostic here?
5652 case DeclaratorContext::TypeName
:
5653 case DeclaratorContext::FunctionalCast
:
5654 case DeclaratorContext::CXXNew
:
5655 case DeclaratorContext::AliasDecl
:
5656 case DeclaratorContext::AliasTemplate
:
5657 case DeclaratorContext::Member
:
5658 case DeclaratorContext::Block
:
5659 case DeclaratorContext::ForInit
:
5660 case DeclaratorContext::SelectionInit
:
5661 case DeclaratorContext::Condition
:
5662 case DeclaratorContext::CXXCatch
:
5663 case DeclaratorContext::ObjCCatch
:
5664 case DeclaratorContext::BlockLiteral
:
5665 case DeclaratorContext::LambdaExpr
:
5666 case DeclaratorContext::ConversionId
:
5667 case DeclaratorContext::TrailingReturn
:
5668 case DeclaratorContext::TrailingReturnVar
:
5669 case DeclaratorContext::TemplateArg
:
5670 case DeclaratorContext::TemplateTypeArg
:
5671 case DeclaratorContext::Association
:
5672 // FIXME: We may want to allow parameter packs in block-literal contexts
5674 S
.Diag(D
.getEllipsisLoc(),
5675 diag::err_ellipsis_in_declarator_not_parameter
);
5676 D
.setEllipsisLoc(SourceLocation());
5681 assert(!T
.isNull() && "T must not be null at the end of this function");
5682 if (!AreDeclaratorChunksValid
)
5683 return Context
.getTrivialTypeSourceInfo(T
);
5684 return GetTypeSourceInfoForDeclarator(state
, T
, TInfo
);
5687 TypeSourceInfo
*Sema::GetTypeForDeclarator(Declarator
&D
) {
5688 // Determine the type of the declarator. Not all forms of declarator
5691 TypeProcessingState
state(*this, D
);
5693 TypeSourceInfo
*ReturnTypeInfo
= nullptr;
5694 QualType T
= GetDeclSpecTypeForDeclarator(state
, ReturnTypeInfo
);
5695 if (D
.isPrototypeContext() && getLangOpts().ObjCAutoRefCount
)
5696 inferARCWriteback(state
, T
);
5698 return GetFullTypeForDeclarator(state
, T
, ReturnTypeInfo
);
5701 static void transferARCOwnershipToDeclSpec(Sema
&S
,
5702 QualType
&declSpecTy
,
5703 Qualifiers::ObjCLifetime ownership
) {
5704 if (declSpecTy
->isObjCRetainableType() &&
5705 declSpecTy
.getObjCLifetime() == Qualifiers::OCL_None
) {
5707 qs
.addObjCLifetime(ownership
);
5708 declSpecTy
= S
.Context
.getQualifiedType(declSpecTy
, qs
);
5712 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState
&state
,
5713 Qualifiers::ObjCLifetime ownership
,
5714 unsigned chunkIndex
) {
5715 Sema
&S
= state
.getSema();
5716 Declarator
&D
= state
.getDeclarator();
5718 // Look for an explicit lifetime attribute.
5719 DeclaratorChunk
&chunk
= D
.getTypeObject(chunkIndex
);
5720 if (chunk
.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership
))
5723 const char *attrStr
= nullptr;
5724 switch (ownership
) {
5725 case Qualifiers::OCL_None
: llvm_unreachable("no ownership!");
5726 case Qualifiers::OCL_ExplicitNone
: attrStr
= "none"; break;
5727 case Qualifiers::OCL_Strong
: attrStr
= "strong"; break;
5728 case Qualifiers::OCL_Weak
: attrStr
= "weak"; break;
5729 case Qualifiers::OCL_Autoreleasing
: attrStr
= "autoreleasing"; break;
5732 IdentifierLoc
*Arg
= new (S
.Context
) IdentifierLoc
;
5733 Arg
->Ident
= &S
.Context
.Idents
.get(attrStr
);
5734 Arg
->Loc
= SourceLocation();
5736 ArgsUnion
Args(Arg
);
5738 // If there wasn't one, add one (with an invalid source location
5739 // so that we don't make an AttributedType for it).
5740 ParsedAttr
*attr
= D
.getAttributePool().create(
5741 &S
.Context
.Idents
.get("objc_ownership"), SourceLocation(),
5742 /*scope*/ nullptr, SourceLocation(),
5743 /*args*/ &Args
, 1, ParsedAttr::Form::GNU());
5744 chunk
.getAttrs().addAtEnd(attr
);
5745 // TODO: mark whether we did this inference?
5748 /// Used for transferring ownership in casts resulting in l-values.
5749 static void transferARCOwnership(TypeProcessingState
&state
,
5750 QualType
&declSpecTy
,
5751 Qualifiers::ObjCLifetime ownership
) {
5752 Sema
&S
= state
.getSema();
5753 Declarator
&D
= state
.getDeclarator();
5756 bool hasIndirection
= false;
5757 for (unsigned i
= 0, e
= D
.getNumTypeObjects(); i
!= e
; ++i
) {
5758 DeclaratorChunk
&chunk
= D
.getTypeObject(i
);
5759 switch (chunk
.Kind
) {
5760 case DeclaratorChunk::Paren
:
5764 case DeclaratorChunk::Array
:
5765 case DeclaratorChunk::Reference
:
5766 case DeclaratorChunk::Pointer
:
5768 hasIndirection
= true;
5772 case DeclaratorChunk::BlockPointer
:
5774 transferARCOwnershipToDeclaratorChunk(state
, ownership
, i
);
5777 case DeclaratorChunk::Function
:
5778 case DeclaratorChunk::MemberPointer
:
5779 case DeclaratorChunk::Pipe
:
5787 DeclaratorChunk
&chunk
= D
.getTypeObject(inner
);
5788 if (chunk
.Kind
== DeclaratorChunk::Pointer
) {
5789 if (declSpecTy
->isObjCRetainableType())
5790 return transferARCOwnershipToDeclSpec(S
, declSpecTy
, ownership
);
5791 if (declSpecTy
->isObjCObjectType() && hasIndirection
)
5792 return transferARCOwnershipToDeclaratorChunk(state
, ownership
, inner
);
5794 assert(chunk
.Kind
== DeclaratorChunk::Array
||
5795 chunk
.Kind
== DeclaratorChunk::Reference
);
5796 return transferARCOwnershipToDeclSpec(S
, declSpecTy
, ownership
);
5800 TypeSourceInfo
*Sema::GetTypeForDeclaratorCast(Declarator
&D
, QualType FromTy
) {
5801 TypeProcessingState
state(*this, D
);
5803 TypeSourceInfo
*ReturnTypeInfo
= nullptr;
5804 QualType declSpecTy
= GetDeclSpecTypeForDeclarator(state
, ReturnTypeInfo
);
5806 if (getLangOpts().ObjC
) {
5807 Qualifiers::ObjCLifetime ownership
= Context
.getInnerObjCOwnership(FromTy
);
5808 if (ownership
!= Qualifiers::OCL_None
)
5809 transferARCOwnership(state
, declSpecTy
, ownership
);
5812 return GetFullTypeForDeclarator(state
, declSpecTy
, ReturnTypeInfo
);
5815 static void fillAttributedTypeLoc(AttributedTypeLoc TL
,
5816 TypeProcessingState
&State
) {
5817 TL
.setAttr(State
.takeAttrForAttributedType(TL
.getTypePtr()));
5820 static void fillHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL
,
5821 TypeProcessingState
&State
) {
5822 HLSLAttributedResourceLocInfo LocInfo
=
5823 State
.getSema().HLSL().TakeLocForHLSLAttribute(TL
.getTypePtr());
5824 TL
.setSourceRange(LocInfo
.Range
);
5825 TL
.setContainedTypeSourceInfo(LocInfo
.ContainedTyInfo
);
5828 static void fillMatrixTypeLoc(MatrixTypeLoc MTL
,
5829 const ParsedAttributesView
&Attrs
) {
5830 for (const ParsedAttr
&AL
: Attrs
) {
5831 if (AL
.getKind() == ParsedAttr::AT_MatrixType
) {
5832 MTL
.setAttrNameLoc(AL
.getLoc());
5833 MTL
.setAttrRowOperand(AL
.getArgAsExpr(0));
5834 MTL
.setAttrColumnOperand(AL
.getArgAsExpr(1));
5835 MTL
.setAttrOperandParensRange(SourceRange());
5840 llvm_unreachable("no matrix_type attribute found at the expected location!");
5843 static void fillAtomicQualLoc(AtomicTypeLoc ATL
, const DeclaratorChunk
&Chunk
) {
5845 switch (Chunk
.Kind
) {
5846 case DeclaratorChunk::Function
:
5847 case DeclaratorChunk::Array
:
5848 case DeclaratorChunk::Paren
:
5849 case DeclaratorChunk::Pipe
:
5850 llvm_unreachable("cannot be _Atomic qualified");
5852 case DeclaratorChunk::Pointer
:
5853 Loc
= Chunk
.Ptr
.AtomicQualLoc
;
5856 case DeclaratorChunk::BlockPointer
:
5857 case DeclaratorChunk::Reference
:
5858 case DeclaratorChunk::MemberPointer
:
5859 // FIXME: Provide a source location for the _Atomic keyword.
5864 ATL
.setParensRange(SourceRange());
5868 class TypeSpecLocFiller
: public TypeLocVisitor
<TypeSpecLocFiller
> {
5870 ASTContext
&Context
;
5871 TypeProcessingState
&State
;
5875 TypeSpecLocFiller(Sema
&S
, ASTContext
&Context
, TypeProcessingState
&State
,
5877 : SemaRef(S
), Context(Context
), State(State
), DS(DS
) {}
5879 void VisitAttributedTypeLoc(AttributedTypeLoc TL
) {
5880 Visit(TL
.getModifiedLoc());
5881 fillAttributedTypeLoc(TL
, State
);
5883 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL
) {
5884 Visit(TL
.getWrappedLoc());
5886 void VisitHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL
) {
5887 Visit(TL
.getWrappedLoc());
5888 fillHLSLAttributedResourceTypeLoc(TL
, State
);
5890 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL
) {
5891 Visit(TL
.getInnerLoc());
5893 State
.getExpansionLocForMacroQualifiedType(TL
.getTypePtr()));
5895 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL
) {
5896 Visit(TL
.getUnqualifiedLoc());
5898 // Allow to fill pointee's type locations, e.g.,
5899 // int __attr * __attr * __attr *p;
5900 void VisitPointerTypeLoc(PointerTypeLoc TL
) { Visit(TL
.getNextTypeLoc()); }
5901 void VisitTypedefTypeLoc(TypedefTypeLoc TL
) {
5902 TL
.setNameLoc(DS
.getTypeSpecTypeLoc());
5904 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL
) {
5905 TL
.setNameLoc(DS
.getTypeSpecTypeLoc());
5906 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5907 // addition field. What we have is good enough for display of location
5908 // of 'fixit' on interface name.
5909 TL
.setNameEndLoc(DS
.getEndLoc());
5911 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL
) {
5912 TypeSourceInfo
*RepTInfo
= nullptr;
5913 Sema::GetTypeFromParser(DS
.getRepAsType(), &RepTInfo
);
5914 TL
.copy(RepTInfo
->getTypeLoc());
5916 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL
) {
5917 TypeSourceInfo
*RepTInfo
= nullptr;
5918 Sema::GetTypeFromParser(DS
.getRepAsType(), &RepTInfo
);
5919 TL
.copy(RepTInfo
->getTypeLoc());
5921 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL
) {
5922 TypeSourceInfo
*TInfo
= nullptr;
5923 Sema::GetTypeFromParser(DS
.getRepAsType(), &TInfo
);
5925 // If we got no declarator info from previous Sema routines,
5926 // just fill with the typespec loc.
5928 TL
.initialize(Context
, DS
.getTypeSpecTypeNameLoc());
5932 TypeLoc OldTL
= TInfo
->getTypeLoc();
5933 if (TInfo
->getType()->getAs
<ElaboratedType
>()) {
5934 ElaboratedTypeLoc ElabTL
= OldTL
.castAs
<ElaboratedTypeLoc
>();
5935 TemplateSpecializationTypeLoc NamedTL
= ElabTL
.getNamedTypeLoc()
5936 .castAs
<TemplateSpecializationTypeLoc
>();
5939 TL
.copy(OldTL
.castAs
<TemplateSpecializationTypeLoc
>());
5940 assert(TL
.getRAngleLoc() == OldTL
.castAs
<TemplateSpecializationTypeLoc
>().getRAngleLoc());
5944 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL
) {
5945 assert(DS
.getTypeSpecType() == DeclSpec::TST_typeofExpr
||
5946 DS
.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr
);
5947 TL
.setTypeofLoc(DS
.getTypeSpecTypeLoc());
5948 TL
.setParensRange(DS
.getTypeofParensRange());
5950 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL
) {
5951 assert(DS
.getTypeSpecType() == DeclSpec::TST_typeofType
||
5952 DS
.getTypeSpecType() == DeclSpec::TST_typeof_unqualType
);
5953 TL
.setTypeofLoc(DS
.getTypeSpecTypeLoc());
5954 TL
.setParensRange(DS
.getTypeofParensRange());
5955 assert(DS
.getRepAsType());
5956 TypeSourceInfo
*TInfo
= nullptr;
5957 Sema::GetTypeFromParser(DS
.getRepAsType(), &TInfo
);
5958 TL
.setUnmodifiedTInfo(TInfo
);
5960 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL
) {
5961 assert(DS
.getTypeSpecType() == DeclSpec::TST_decltype
);
5962 TL
.setDecltypeLoc(DS
.getTypeSpecTypeLoc());
5963 TL
.setRParenLoc(DS
.getTypeofParensRange().getEnd());
5965 void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL
) {
5966 assert(DS
.getTypeSpecType() == DeclSpec::TST_typename_pack_indexing
);
5967 TL
.setEllipsisLoc(DS
.getEllipsisLoc());
5969 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL
) {
5970 assert(DS
.isTransformTypeTrait(DS
.getTypeSpecType()));
5971 TL
.setKWLoc(DS
.getTypeSpecTypeLoc());
5972 TL
.setParensRange(DS
.getTypeofParensRange());
5973 assert(DS
.getRepAsType());
5974 TypeSourceInfo
*TInfo
= nullptr;
5975 Sema::GetTypeFromParser(DS
.getRepAsType(), &TInfo
);
5976 TL
.setUnderlyingTInfo(TInfo
);
5978 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL
) {
5979 // By default, use the source location of the type specifier.
5980 TL
.setBuiltinLoc(DS
.getTypeSpecTypeLoc());
5981 if (TL
.needsExtraLocalData()) {
5982 // Set info for the written builtin specifiers.
5983 TL
.getWrittenBuiltinSpecs() = DS
.getWrittenBuiltinSpecs();
5984 // Try to have a meaningful source location.
5985 if (TL
.getWrittenSignSpec() != TypeSpecifierSign::Unspecified
)
5986 TL
.expandBuiltinRange(DS
.getTypeSpecSignLoc());
5987 if (TL
.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified
)
5988 TL
.expandBuiltinRange(DS
.getTypeSpecWidthRange());
5991 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL
) {
5992 if (DS
.getTypeSpecType() == TST_typename
) {
5993 TypeSourceInfo
*TInfo
= nullptr;
5994 Sema::GetTypeFromParser(DS
.getRepAsType(), &TInfo
);
5996 if (auto ETL
= TInfo
->getTypeLoc().getAs
<ElaboratedTypeLoc
>()) {
6001 const ElaboratedType
*T
= TL
.getTypePtr();
6002 TL
.setElaboratedKeywordLoc(T
->getKeyword() != ElaboratedTypeKeyword::None
6003 ? DS
.getTypeSpecTypeLoc()
6004 : SourceLocation());
6005 const CXXScopeSpec
& SS
= DS
.getTypeSpecScope();
6006 TL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
6007 Visit(TL
.getNextTypeLoc().getUnqualifiedLoc());
6009 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL
) {
6010 assert(DS
.getTypeSpecType() == TST_typename
);
6011 TypeSourceInfo
*TInfo
= nullptr;
6012 Sema::GetTypeFromParser(DS
.getRepAsType(), &TInfo
);
6014 TL
.copy(TInfo
->getTypeLoc().castAs
<DependentNameTypeLoc
>());
6016 void VisitDependentTemplateSpecializationTypeLoc(
6017 DependentTemplateSpecializationTypeLoc TL
) {
6018 assert(DS
.getTypeSpecType() == TST_typename
);
6019 TypeSourceInfo
*TInfo
= nullptr;
6020 Sema::GetTypeFromParser(DS
.getRepAsType(), &TInfo
);
6023 TInfo
->getTypeLoc().castAs
<DependentTemplateSpecializationTypeLoc
>());
6025 void VisitAutoTypeLoc(AutoTypeLoc TL
) {
6026 assert(DS
.getTypeSpecType() == TST_auto
||
6027 DS
.getTypeSpecType() == TST_decltype_auto
||
6028 DS
.getTypeSpecType() == TST_auto_type
||
6029 DS
.getTypeSpecType() == TST_unspecified
);
6030 TL
.setNameLoc(DS
.getTypeSpecTypeLoc());
6031 if (DS
.getTypeSpecType() == TST_decltype_auto
)
6032 TL
.setRParenLoc(DS
.getTypeofParensRange().getEnd());
6033 if (!DS
.isConstrainedAuto())
6035 TemplateIdAnnotation
*TemplateId
= DS
.getRepAsTemplateId();
6039 NestedNameSpecifierLoc NNS
=
6040 (DS
.getTypeSpecScope().isNotEmpty()
6041 ? DS
.getTypeSpecScope().getWithLocInContext(Context
)
6042 : NestedNameSpecifierLoc());
6043 TemplateArgumentListInfo
TemplateArgsInfo(TemplateId
->LAngleLoc
,
6044 TemplateId
->RAngleLoc
);
6045 if (TemplateId
->NumArgs
> 0) {
6046 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateId
->getTemplateArgs(),
6047 TemplateId
->NumArgs
);
6048 SemaRef
.translateTemplateArguments(TemplateArgsPtr
, TemplateArgsInfo
);
6050 DeclarationNameInfo DNI
= DeclarationNameInfo(
6051 TL
.getTypePtr()->getTypeConstraintConcept()->getDeclName(),
6052 TemplateId
->TemplateNameLoc
);
6054 NamedDecl
*FoundDecl
;
6055 if (auto TN
= TemplateId
->Template
.get();
6056 UsingShadowDecl
*USD
= TN
.getAsUsingShadowDecl())
6057 FoundDecl
= cast
<NamedDecl
>(USD
);
6059 FoundDecl
= cast_if_present
<NamedDecl
>(TN
.getAsTemplateDecl());
6061 auto *CR
= ConceptReference::Create(
6062 Context
, NNS
, TemplateId
->TemplateKWLoc
, DNI
, FoundDecl
,
6063 /*NamedDecl=*/TL
.getTypePtr()->getTypeConstraintConcept(),
6064 ASTTemplateArgumentListInfo::Create(Context
, TemplateArgsInfo
));
6065 TL
.setConceptReference(CR
);
6067 void VisitTagTypeLoc(TagTypeLoc TL
) {
6068 TL
.setNameLoc(DS
.getTypeSpecTypeNameLoc());
6070 void VisitAtomicTypeLoc(AtomicTypeLoc TL
) {
6071 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6072 // or an _Atomic qualifier.
6073 if (DS
.getTypeSpecType() == DeclSpec::TST_atomic
) {
6074 TL
.setKWLoc(DS
.getTypeSpecTypeLoc());
6075 TL
.setParensRange(DS
.getTypeofParensRange());
6077 TypeSourceInfo
*TInfo
= nullptr;
6078 Sema::GetTypeFromParser(DS
.getRepAsType(), &TInfo
);
6080 TL
.getValueLoc().initializeFullCopy(TInfo
->getTypeLoc());
6082 TL
.setKWLoc(DS
.getAtomicSpecLoc());
6083 // No parens, to indicate this was spelled as an _Atomic qualifier.
6084 TL
.setParensRange(SourceRange());
6085 Visit(TL
.getValueLoc());
6089 void VisitPipeTypeLoc(PipeTypeLoc TL
) {
6090 TL
.setKWLoc(DS
.getTypeSpecTypeLoc());
6092 TypeSourceInfo
*TInfo
= nullptr;
6093 Sema::GetTypeFromParser(DS
.getRepAsType(), &TInfo
);
6094 TL
.getValueLoc().initializeFullCopy(TInfo
->getTypeLoc());
6097 void VisitExtIntTypeLoc(BitIntTypeLoc TL
) {
6098 TL
.setNameLoc(DS
.getTypeSpecTypeLoc());
6101 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL
) {
6102 TL
.setNameLoc(DS
.getTypeSpecTypeLoc());
6105 void VisitTypeLoc(TypeLoc TL
) {
6106 // FIXME: add other typespec types and change this to an assert.
6107 TL
.initialize(Context
, DS
.getTypeSpecTypeLoc());
6111 class DeclaratorLocFiller
: public TypeLocVisitor
<DeclaratorLocFiller
> {
6112 ASTContext
&Context
;
6113 TypeProcessingState
&State
;
6114 const DeclaratorChunk
&Chunk
;
6117 DeclaratorLocFiller(ASTContext
&Context
, TypeProcessingState
&State
,
6118 const DeclaratorChunk
&Chunk
)
6119 : Context(Context
), State(State
), Chunk(Chunk
) {}
6121 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL
) {
6122 llvm_unreachable("qualified type locs not expected here!");
6124 void VisitDecayedTypeLoc(DecayedTypeLoc TL
) {
6125 llvm_unreachable("decayed type locs not expected here!");
6127 void VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL
) {
6128 llvm_unreachable("array parameter type locs not expected here!");
6131 void VisitAttributedTypeLoc(AttributedTypeLoc TL
) {
6132 fillAttributedTypeLoc(TL
, State
);
6134 void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL
) {
6137 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL
) {
6140 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL
) {
6143 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL
) {
6144 assert(Chunk
.Kind
== DeclaratorChunk::BlockPointer
);
6145 TL
.setCaretLoc(Chunk
.Loc
);
6147 void VisitPointerTypeLoc(PointerTypeLoc TL
) {
6148 assert(Chunk
.Kind
== DeclaratorChunk::Pointer
);
6149 TL
.setStarLoc(Chunk
.Loc
);
6151 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL
) {
6152 assert(Chunk
.Kind
== DeclaratorChunk::Pointer
);
6153 TL
.setStarLoc(Chunk
.Loc
);
6155 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL
) {
6156 assert(Chunk
.Kind
== DeclaratorChunk::MemberPointer
);
6157 const CXXScopeSpec
& SS
= Chunk
.Mem
.Scope();
6158 NestedNameSpecifierLoc NNSLoc
= SS
.getWithLocInContext(Context
);
6160 const Type
* ClsTy
= TL
.getClass();
6161 QualType ClsQT
= QualType(ClsTy
, 0);
6162 TypeSourceInfo
*ClsTInfo
= Context
.CreateTypeSourceInfo(ClsQT
, 0);
6163 // Now copy source location info into the type loc component.
6164 TypeLoc ClsTL
= ClsTInfo
->getTypeLoc();
6165 switch (NNSLoc
.getNestedNameSpecifier()->getKind()) {
6166 case NestedNameSpecifier::Identifier
:
6167 assert(isa
<DependentNameType
>(ClsTy
) && "Unexpected TypeLoc");
6169 DependentNameTypeLoc DNTLoc
= ClsTL
.castAs
<DependentNameTypeLoc
>();
6170 DNTLoc
.setElaboratedKeywordLoc(SourceLocation());
6171 DNTLoc
.setQualifierLoc(NNSLoc
.getPrefix());
6172 DNTLoc
.setNameLoc(NNSLoc
.getLocalBeginLoc());
6176 case NestedNameSpecifier::TypeSpec
:
6177 case NestedNameSpecifier::TypeSpecWithTemplate
:
6178 if (isa
<ElaboratedType
>(ClsTy
)) {
6179 ElaboratedTypeLoc ETLoc
= ClsTL
.castAs
<ElaboratedTypeLoc
>();
6180 ETLoc
.setElaboratedKeywordLoc(SourceLocation());
6181 ETLoc
.setQualifierLoc(NNSLoc
.getPrefix());
6182 TypeLoc NamedTL
= ETLoc
.getNamedTypeLoc();
6183 NamedTL
.initializeFullCopy(NNSLoc
.getTypeLoc());
6185 ClsTL
.initializeFullCopy(NNSLoc
.getTypeLoc());
6189 case NestedNameSpecifier::Namespace
:
6190 case NestedNameSpecifier::NamespaceAlias
:
6191 case NestedNameSpecifier::Global
:
6192 case NestedNameSpecifier::Super
:
6193 llvm_unreachable("Nested-name-specifier must name a type");
6196 // Finally fill in MemberPointerLocInfo fields.
6197 TL
.setStarLoc(Chunk
.Mem
.StarLoc
);
6198 TL
.setClassTInfo(ClsTInfo
);
6200 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL
) {
6201 assert(Chunk
.Kind
== DeclaratorChunk::Reference
);
6202 // 'Amp' is misleading: this might have been originally
6203 /// spelled with AmpAmp.
6204 TL
.setAmpLoc(Chunk
.Loc
);
6206 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL
) {
6207 assert(Chunk
.Kind
== DeclaratorChunk::Reference
);
6208 assert(!Chunk
.Ref
.LValueRef
);
6209 TL
.setAmpAmpLoc(Chunk
.Loc
);
6211 void VisitArrayTypeLoc(ArrayTypeLoc TL
) {
6212 assert(Chunk
.Kind
== DeclaratorChunk::Array
);
6213 TL
.setLBracketLoc(Chunk
.Loc
);
6214 TL
.setRBracketLoc(Chunk
.EndLoc
);
6215 TL
.setSizeExpr(static_cast<Expr
*>(Chunk
.Arr
.NumElts
));
6217 void VisitFunctionTypeLoc(FunctionTypeLoc TL
) {
6218 assert(Chunk
.Kind
== DeclaratorChunk::Function
);
6219 TL
.setLocalRangeBegin(Chunk
.Loc
);
6220 TL
.setLocalRangeEnd(Chunk
.EndLoc
);
6222 const DeclaratorChunk::FunctionTypeInfo
&FTI
= Chunk
.Fun
;
6223 TL
.setLParenLoc(FTI
.getLParenLoc());
6224 TL
.setRParenLoc(FTI
.getRParenLoc());
6225 for (unsigned i
= 0, e
= TL
.getNumParams(), tpi
= 0; i
!= e
; ++i
) {
6226 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(FTI
.Params
[i
].Param
);
6227 TL
.setParam(tpi
++, Param
);
6229 TL
.setExceptionSpecRange(FTI
.getExceptionSpecRange());
6231 void VisitParenTypeLoc(ParenTypeLoc TL
) {
6232 assert(Chunk
.Kind
== DeclaratorChunk::Paren
);
6233 TL
.setLParenLoc(Chunk
.Loc
);
6234 TL
.setRParenLoc(Chunk
.EndLoc
);
6236 void VisitPipeTypeLoc(PipeTypeLoc TL
) {
6237 assert(Chunk
.Kind
== DeclaratorChunk::Pipe
);
6238 TL
.setKWLoc(Chunk
.Loc
);
6240 void VisitBitIntTypeLoc(BitIntTypeLoc TL
) {
6241 TL
.setNameLoc(Chunk
.Loc
);
6243 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL
) {
6244 TL
.setExpansionLoc(Chunk
.Loc
);
6246 void VisitVectorTypeLoc(VectorTypeLoc TL
) { TL
.setNameLoc(Chunk
.Loc
); }
6247 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL
) {
6248 TL
.setNameLoc(Chunk
.Loc
);
6250 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL
) {
6251 TL
.setNameLoc(Chunk
.Loc
);
6253 void VisitAtomicTypeLoc(AtomicTypeLoc TL
) {
6254 fillAtomicQualLoc(TL
, Chunk
);
6257 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL
) {
6258 TL
.setNameLoc(Chunk
.Loc
);
6260 void VisitMatrixTypeLoc(MatrixTypeLoc TL
) {
6261 fillMatrixTypeLoc(TL
, Chunk
.getAttrs());
6264 void VisitTypeLoc(TypeLoc TL
) {
6265 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6268 } // end anonymous namespace
6271 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL
,
6272 const ParsedAttributesView
&Attrs
) {
6273 for (const ParsedAttr
&AL
: Attrs
) {
6274 if (AL
.getKind() == ParsedAttr::AT_AddressSpace
) {
6275 DASTL
.setAttrNameLoc(AL
.getLoc());
6276 DASTL
.setAttrExprOperand(AL
.getArgAsExpr(0));
6277 DASTL
.setAttrOperandParensRange(SourceRange());
6283 "no address_space attribute found at the expected location!");
6286 /// Create and instantiate a TypeSourceInfo with type source information.
6288 /// \param T QualType referring to the type as written in source code.
6290 /// \param ReturnTypeInfo For declarators whose return type does not show
6291 /// up in the normal place in the declaration specifiers (such as a C++
6292 /// conversion function), this pointer will refer to a type source information
6293 /// for that return type.
6294 static TypeSourceInfo
*
6295 GetTypeSourceInfoForDeclarator(TypeProcessingState
&State
,
6296 QualType T
, TypeSourceInfo
*ReturnTypeInfo
) {
6297 Sema
&S
= State
.getSema();
6298 Declarator
&D
= State
.getDeclarator();
6300 TypeSourceInfo
*TInfo
= S
.Context
.CreateTypeSourceInfo(T
);
6301 UnqualTypeLoc CurrTL
= TInfo
->getTypeLoc().getUnqualifiedLoc();
6303 // Handle parameter packs whose type is a pack expansion.
6304 if (isa
<PackExpansionType
>(T
)) {
6305 CurrTL
.castAs
<PackExpansionTypeLoc
>().setEllipsisLoc(D
.getEllipsisLoc());
6306 CurrTL
= CurrTL
.getNextTypeLoc().getUnqualifiedLoc();
6309 for (unsigned i
= 0, e
= D
.getNumTypeObjects(); i
!= e
; ++i
) {
6310 // Microsoft property fields can have multiple sizeless array chunks
6311 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6312 if (CurrTL
.getTypeLocClass() == TypeLoc::IncompleteArray
&& e
!= 1 &&
6313 D
.getDeclSpec().getAttributes().hasMSPropertyAttr())
6316 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6317 // declarator chunk.
6318 if (AtomicTypeLoc ATL
= CurrTL
.getAs
<AtomicTypeLoc
>()) {
6319 fillAtomicQualLoc(ATL
, D
.getTypeObject(i
));
6320 CurrTL
= ATL
.getValueLoc().getUnqualifiedLoc();
6323 bool HasDesugaredTypeLoc
= true;
6324 while (HasDesugaredTypeLoc
) {
6325 switch (CurrTL
.getTypeLocClass()) {
6326 case TypeLoc::MacroQualified
: {
6327 auto TL
= CurrTL
.castAs
<MacroQualifiedTypeLoc
>();
6329 State
.getExpansionLocForMacroQualifiedType(TL
.getTypePtr()));
6330 CurrTL
= TL
.getNextTypeLoc().getUnqualifiedLoc();
6334 case TypeLoc::Attributed
: {
6335 auto TL
= CurrTL
.castAs
<AttributedTypeLoc
>();
6336 fillAttributedTypeLoc(TL
, State
);
6337 CurrTL
= TL
.getNextTypeLoc().getUnqualifiedLoc();
6341 case TypeLoc::Adjusted
:
6342 case TypeLoc::BTFTagAttributed
: {
6343 CurrTL
= CurrTL
.getNextTypeLoc().getUnqualifiedLoc();
6347 case TypeLoc::DependentAddressSpace
: {
6348 auto TL
= CurrTL
.castAs
<DependentAddressSpaceTypeLoc
>();
6349 fillDependentAddressSpaceTypeLoc(TL
, D
.getTypeObject(i
).getAttrs());
6350 CurrTL
= TL
.getPointeeTypeLoc().getUnqualifiedLoc();
6355 HasDesugaredTypeLoc
= false;
6360 DeclaratorLocFiller(S
.Context
, State
, D
.getTypeObject(i
)).Visit(CurrTL
);
6361 CurrTL
= CurrTL
.getNextTypeLoc().getUnqualifiedLoc();
6364 // If we have different source information for the return type, use
6365 // that. This really only applies to C++ conversion functions.
6366 if (ReturnTypeInfo
) {
6367 TypeLoc TL
= ReturnTypeInfo
->getTypeLoc();
6368 assert(TL
.getFullDataSize() == CurrTL
.getFullDataSize());
6369 memcpy(CurrTL
.getOpaqueData(), TL
.getOpaqueData(), TL
.getFullDataSize());
6371 TypeSpecLocFiller(S
, S
.Context
, State
, D
.getDeclSpec()).Visit(CurrTL
);
6377 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6378 ParsedType
Sema::CreateParsedType(QualType T
, TypeSourceInfo
*TInfo
) {
6379 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6380 // and Sema during declaration parsing. Try deallocating/caching them when
6381 // it's appropriate, instead of allocating them and keeping them around.
6382 LocInfoType
*LocT
= (LocInfoType
*)BumpAlloc
.Allocate(sizeof(LocInfoType
),
6383 alignof(LocInfoType
));
6384 new (LocT
) LocInfoType(T
, TInfo
);
6385 assert(LocT
->getTypeClass() != T
->getTypeClass() &&
6386 "LocInfoType's TypeClass conflicts with an existing Type class");
6387 return ParsedType::make(QualType(LocT
, 0));
6390 void LocInfoType::getAsStringInternal(std::string
&Str
,
6391 const PrintingPolicy
&Policy
) const {
6392 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6393 " was used directly instead of getting the QualType through"
6394 " GetTypeFromParser");
6397 TypeResult
Sema::ActOnTypeName(Declarator
&D
) {
6398 // C99 6.7.6: Type names have no identifier. This is already validated by
6400 assert(D
.getIdentifier() == nullptr &&
6401 "Type name should have no identifier!");
6403 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
);
6404 QualType T
= TInfo
->getType();
6405 if (D
.isInvalidType())
6408 // Make sure there are no unused decl attributes on the declarator.
6409 // We don't want to do this for ObjC parameters because we're going
6410 // to apply them to the actual parameter declaration.
6411 // Likewise, we don't want to do this for alias declarations, because
6412 // we are actually going to build a declaration from this eventually.
6413 if (D
.getContext() != DeclaratorContext::ObjCParameter
&&
6414 D
.getContext() != DeclaratorContext::AliasDecl
&&
6415 D
.getContext() != DeclaratorContext::AliasTemplate
)
6416 checkUnusedDeclAttributes(D
);
6418 if (getLangOpts().CPlusPlus
) {
6419 // Check that there are no default arguments (C++ only).
6420 CheckExtraCXXDefaultArguments(D
);
6423 if (AutoTypeLoc TL
= TInfo
->getTypeLoc().getContainedAutoTypeLoc()) {
6424 const AutoType
*AT
= TL
.getTypePtr();
6425 CheckConstrainedAuto(AT
, TL
.getConceptNameLoc());
6427 return CreateParsedType(T
, TInfo
);
6430 //===----------------------------------------------------------------------===//
6431 // Type Attribute Processing
6432 //===----------------------------------------------------------------------===//
6434 /// Build an AddressSpace index from a constant expression and diagnose any
6435 /// errors related to invalid address_spaces. Returns true on successfully
6436 /// building an AddressSpace index.
6437 static bool BuildAddressSpaceIndex(Sema
&S
, LangAS
&ASIdx
,
6438 const Expr
*AddrSpace
,
6439 SourceLocation AttrLoc
) {
6440 if (!AddrSpace
->isValueDependent()) {
6441 std::optional
<llvm::APSInt
> OptAddrSpace
=
6442 AddrSpace
->getIntegerConstantExpr(S
.Context
);
6443 if (!OptAddrSpace
) {
6444 S
.Diag(AttrLoc
, diag::err_attribute_argument_type
)
6445 << "'address_space'" << AANT_ArgumentIntegerConstant
6446 << AddrSpace
->getSourceRange();
6449 llvm::APSInt
&addrSpace
= *OptAddrSpace
;
6452 if (addrSpace
.isSigned()) {
6453 if (addrSpace
.isNegative()) {
6454 S
.Diag(AttrLoc
, diag::err_attribute_address_space_negative
)
6455 << AddrSpace
->getSourceRange();
6458 addrSpace
.setIsSigned(false);
6461 llvm::APSInt
max(addrSpace
.getBitWidth());
6463 Qualifiers::MaxAddressSpace
- (unsigned)LangAS::FirstTargetAddressSpace
;
6465 if (addrSpace
> max
) {
6466 S
.Diag(AttrLoc
, diag::err_attribute_address_space_too_high
)
6467 << (unsigned)max
.getZExtValue() << AddrSpace
->getSourceRange();
6472 getLangASFromTargetAS(static_cast<unsigned>(addrSpace
.getZExtValue()));
6476 // Default value for DependentAddressSpaceTypes
6477 ASIdx
= LangAS::Default
;
6481 QualType
Sema::BuildAddressSpaceAttr(QualType
&T
, LangAS ASIdx
, Expr
*AddrSpace
,
6482 SourceLocation AttrLoc
) {
6483 if (!AddrSpace
->isValueDependent()) {
6484 if (DiagnoseMultipleAddrSpaceAttributes(*this, T
.getAddressSpace(), ASIdx
,
6488 return Context
.getAddrSpaceQualType(T
, ASIdx
);
6491 // A check with similar intentions as checking if a type already has an
6492 // address space except for on a dependent types, basically if the
6493 // current type is already a DependentAddressSpaceType then its already
6494 // lined up to have another address space on it and we can't have
6495 // multiple address spaces on the one pointer indirection
6496 if (T
->getAs
<DependentAddressSpaceType
>()) {
6497 Diag(AttrLoc
, diag::err_attribute_address_multiple_qualifiers
);
6501 return Context
.getDependentAddressSpaceType(T
, AddrSpace
, AttrLoc
);
6504 QualType
Sema::BuildAddressSpaceAttr(QualType
&T
, Expr
*AddrSpace
,
6505 SourceLocation AttrLoc
) {
6507 if (!BuildAddressSpaceIndex(*this, ASIdx
, AddrSpace
, AttrLoc
))
6509 return BuildAddressSpaceAttr(T
, ASIdx
, AddrSpace
, AttrLoc
);
6512 static void HandleBTFTypeTagAttribute(QualType
&Type
, const ParsedAttr
&Attr
,
6513 TypeProcessingState
&State
) {
6514 Sema
&S
= State
.getSema();
6516 // This attribute is only supported in C.
6517 // FIXME: we should implement checkCommonAttributeFeatures() in SemaAttr.cpp
6518 // such that it handles type attributes, and then call that from
6519 // processTypeAttrs() instead of one-off checks like this.
6520 if (!Attr
.diagnoseLangOpts(S
)) {
6525 // Check the number of attribute arguments.
6526 if (Attr
.getNumArgs() != 1) {
6527 S
.Diag(Attr
.getLoc(), diag::err_attribute_wrong_number_arguments
)
6533 // Ensure the argument is a string.
6534 auto *StrLiteral
= dyn_cast
<StringLiteral
>(Attr
.getArgAsExpr(0));
6536 S
.Diag(Attr
.getLoc(), diag::err_attribute_argument_type
)
6537 << Attr
<< AANT_ArgumentString
;
6542 ASTContext
&Ctx
= S
.Context
;
6543 StringRef BTFTypeTag
= StrLiteral
->getString();
6544 Type
= State
.getBTFTagAttributedType(
6545 ::new (Ctx
) BTFTypeTagAttr(Ctx
, Attr
, BTFTypeTag
), Type
);
6548 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6549 /// specified type. The attribute contains 1 argument, the id of the address
6550 /// space for the type.
6551 static void HandleAddressSpaceTypeAttribute(QualType
&Type
,
6552 const ParsedAttr
&Attr
,
6553 TypeProcessingState
&State
) {
6554 Sema
&S
= State
.getSema();
6556 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6557 // qualified by an address-space qualifier."
6558 if (Type
->isFunctionType()) {
6559 S
.Diag(Attr
.getLoc(), diag::err_attribute_address_function_type
);
6565 if (Attr
.getKind() == ParsedAttr::AT_AddressSpace
) {
6567 // Check the attribute arguments.
6568 if (Attr
.getNumArgs() != 1) {
6569 S
.Diag(Attr
.getLoc(), diag::err_attribute_wrong_number_arguments
) << Attr
6575 Expr
*ASArgExpr
= static_cast<Expr
*>(Attr
.getArgAsExpr(0));
6577 if (!BuildAddressSpaceIndex(S
, ASIdx
, ASArgExpr
, Attr
.getLoc())) {
6582 ASTContext
&Ctx
= S
.Context
;
6584 ::new (Ctx
) AddressSpaceAttr(Ctx
, Attr
, static_cast<unsigned>(ASIdx
));
6586 // If the expression is not value dependent (not templated), then we can
6587 // apply the address space qualifiers just to the equivalent type.
6588 // Otherwise, we make an AttributedType with the modified and equivalent
6589 // type the same, and wrap it in a DependentAddressSpaceType. When this
6590 // dependent type is resolved, the qualifier is added to the equivalent type
6593 if (!ASArgExpr
->isValueDependent()) {
6594 QualType EquivType
=
6595 S
.BuildAddressSpaceAttr(Type
, ASIdx
, ASArgExpr
, Attr
.getLoc());
6596 if (EquivType
.isNull()) {
6600 T
= State
.getAttributedType(ASAttr
, Type
, EquivType
);
6602 T
= State
.getAttributedType(ASAttr
, Type
, Type
);
6603 T
= S
.BuildAddressSpaceAttr(T
, ASIdx
, ASArgExpr
, Attr
.getLoc());
6611 // The keyword-based type attributes imply which address space to use.
6612 ASIdx
= S
.getLangOpts().SYCLIsDevice
? Attr
.asSYCLLangAS()
6613 : Attr
.asOpenCLLangAS();
6614 if (S
.getLangOpts().HLSL
)
6615 ASIdx
= Attr
.asHLSLLangAS();
6617 if (ASIdx
== LangAS::Default
)
6618 llvm_unreachable("Invalid address space");
6620 if (DiagnoseMultipleAddrSpaceAttributes(S
, Type
.getAddressSpace(), ASIdx
,
6626 Type
= S
.Context
.getAddrSpaceQualType(Type
, ASIdx
);
6630 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
6631 /// attribute on the specified type.
6633 /// Returns 'true' if the attribute was handled.
6634 static bool handleObjCOwnershipTypeAttr(TypeProcessingState
&state
,
6635 ParsedAttr
&attr
, QualType
&type
) {
6636 bool NonObjCPointer
= false;
6638 if (!type
->isDependentType() && !type
->isUndeducedType()) {
6639 if (const PointerType
*ptr
= type
->getAs
<PointerType
>()) {
6640 QualType pointee
= ptr
->getPointeeType();
6641 if (pointee
->isObjCRetainableType() || pointee
->isPointerType())
6643 // It is important not to lose the source info that there was an attribute
6644 // applied to non-objc pointer. We will create an attributed type but
6645 // its type will be the same as the original type.
6646 NonObjCPointer
= true;
6647 } else if (!type
->isObjCRetainableType()) {
6651 // Don't accept an ownership attribute in the declspec if it would
6652 // just be the return type of a block pointer.
6653 if (state
.isProcessingDeclSpec()) {
6654 Declarator
&D
= state
.getDeclarator();
6655 if (maybeMovePastReturnType(D
, D
.getNumTypeObjects(),
6656 /*onlyBlockPointers=*/true))
6661 Sema
&S
= state
.getSema();
6662 SourceLocation AttrLoc
= attr
.getLoc();
6663 if (AttrLoc
.isMacroID())
6665 S
.getSourceManager().getImmediateExpansionRange(AttrLoc
).getBegin();
6667 if (!attr
.isArgIdent(0)) {
6668 S
.Diag(AttrLoc
, diag::err_attribute_argument_type
) << attr
6669 << AANT_ArgumentString
;
6674 IdentifierInfo
*II
= attr
.getArgAsIdent(0)->Ident
;
6675 Qualifiers::ObjCLifetime lifetime
;
6676 if (II
->isStr("none"))
6677 lifetime
= Qualifiers::OCL_ExplicitNone
;
6678 else if (II
->isStr("strong"))
6679 lifetime
= Qualifiers::OCL_Strong
;
6680 else if (II
->isStr("weak"))
6681 lifetime
= Qualifiers::OCL_Weak
;
6682 else if (II
->isStr("autoreleasing"))
6683 lifetime
= Qualifiers::OCL_Autoreleasing
;
6685 S
.Diag(AttrLoc
, diag::warn_attribute_type_not_supported
) << attr
<< II
;
6690 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6691 // outside of ARC mode.
6692 if (!S
.getLangOpts().ObjCAutoRefCount
&&
6693 lifetime
!= Qualifiers::OCL_Weak
&&
6694 lifetime
!= Qualifiers::OCL_ExplicitNone
) {
6698 SplitQualType underlyingType
= type
.split();
6700 // Check for redundant/conflicting ownership qualifiers.
6701 if (Qualifiers::ObjCLifetime previousLifetime
6702 = type
.getQualifiers().getObjCLifetime()) {
6703 // If it's written directly, that's an error.
6704 if (S
.Context
.hasDirectOwnershipQualifier(type
)) {
6705 S
.Diag(AttrLoc
, diag::err_attr_objc_ownership_redundant
)
6710 // Otherwise, if the qualifiers actually conflict, pull sugar off
6711 // and remove the ObjCLifetime qualifiers.
6712 if (previousLifetime
!= lifetime
) {
6713 // It's possible to have multiple local ObjCLifetime qualifiers. We
6714 // can't stop after we reach a type that is directly qualified.
6715 const Type
*prevTy
= nullptr;
6716 while (!prevTy
|| prevTy
!= underlyingType
.Ty
) {
6717 prevTy
= underlyingType
.Ty
;
6718 underlyingType
= underlyingType
.getSingleStepDesugaredType();
6720 underlyingType
.Quals
.removeObjCLifetime();
6724 underlyingType
.Quals
.addObjCLifetime(lifetime
);
6726 if (NonObjCPointer
) {
6727 StringRef name
= attr
.getAttrName()->getName();
6729 case Qualifiers::OCL_None
:
6730 case Qualifiers::OCL_ExplicitNone
:
6732 case Qualifiers::OCL_Strong
: name
= "__strong"; break;
6733 case Qualifiers::OCL_Weak
: name
= "__weak"; break;
6734 case Qualifiers::OCL_Autoreleasing
: name
= "__autoreleasing"; break;
6736 S
.Diag(AttrLoc
, diag::warn_type_attribute_wrong_type
) << name
6737 << TDS_ObjCObjOrBlock
<< type
;
6740 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6741 // because having both 'T' and '__unsafe_unretained T' exist in the type
6742 // system causes unfortunate widespread consistency problems. (For example,
6743 // they're not considered compatible types, and we mangle them identicially
6744 // as template arguments.) These problems are all individually fixable,
6745 // but it's easier to just not add the qualifier and instead sniff it out
6746 // in specific places using isObjCInertUnsafeUnretainedType().
6748 // Doing this does means we miss some trivial consistency checks that
6749 // would've triggered in ARC, but that's better than trying to solve all
6750 // the coexistence problems with __unsafe_unretained.
6751 if (!S
.getLangOpts().ObjCAutoRefCount
&&
6752 lifetime
== Qualifiers::OCL_ExplicitNone
) {
6753 type
= state
.getAttributedType(
6754 createSimpleAttr
<ObjCInertUnsafeUnretainedAttr
>(S
.Context
, attr
),
6759 QualType origType
= type
;
6760 if (!NonObjCPointer
)
6761 type
= S
.Context
.getQualifiedType(underlyingType
);
6763 // If we have a valid source location for the attribute, use an
6764 // AttributedType instead.
6765 if (AttrLoc
.isValid()) {
6766 type
= state
.getAttributedType(::new (S
.Context
)
6767 ObjCOwnershipAttr(S
.Context
, attr
, II
),
6771 auto diagnoseOrDelay
= [](Sema
&S
, SourceLocation loc
,
6772 unsigned diagnostic
, QualType type
) {
6773 if (S
.DelayedDiagnostics
.shouldDelayDiagnostics()) {
6774 S
.DelayedDiagnostics
.add(
6775 sema::DelayedDiagnostic::makeForbiddenType(
6776 S
.getSourceManager().getExpansionLoc(loc
),
6777 diagnostic
, type
, /*ignored*/ 0));
6779 S
.Diag(loc
, diagnostic
);
6783 // Sometimes, __weak isn't allowed.
6784 if (lifetime
== Qualifiers::OCL_Weak
&&
6785 !S
.getLangOpts().ObjCWeak
&& !NonObjCPointer
) {
6787 // Use a specialized diagnostic if the runtime just doesn't support them.
6788 unsigned diagnostic
=
6789 (S
.getLangOpts().ObjCWeakRuntime
? diag::err_arc_weak_disabled
6790 : diag::err_arc_weak_no_runtime
);
6792 // In any case, delay the diagnostic until we know what we're parsing.
6793 diagnoseOrDelay(S
, AttrLoc
, diagnostic
, type
);
6799 // Forbid __weak for class objects marked as
6800 // objc_arc_weak_reference_unavailable
6801 if (lifetime
== Qualifiers::OCL_Weak
) {
6802 if (const ObjCObjectPointerType
*ObjT
=
6803 type
->getAs
<ObjCObjectPointerType
>()) {
6804 if (ObjCInterfaceDecl
*Class
= ObjT
->getInterfaceDecl()) {
6805 if (Class
->isArcWeakrefUnavailable()) {
6806 S
.Diag(AttrLoc
, diag::err_arc_unsupported_weak_class
);
6807 S
.Diag(ObjT
->getInterfaceDecl()->getLocation(),
6808 diag::note_class_declared
);
6817 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6818 /// attribute on the specified type. Returns true to indicate that
6819 /// the attribute was handled, false to indicate that the type does
6820 /// not permit the attribute.
6821 static bool handleObjCGCTypeAttr(TypeProcessingState
&state
, ParsedAttr
&attr
,
6823 Sema
&S
= state
.getSema();
6825 // Delay if this isn't some kind of pointer.
6826 if (!type
->isPointerType() &&
6827 !type
->isObjCObjectPointerType() &&
6828 !type
->isBlockPointerType())
6831 if (type
.getObjCGCAttr() != Qualifiers::GCNone
) {
6832 S
.Diag(attr
.getLoc(), diag::err_attribute_multiple_objc_gc
);
6837 // Check the attribute arguments.
6838 if (!attr
.isArgIdent(0)) {
6839 S
.Diag(attr
.getLoc(), diag::err_attribute_argument_type
)
6840 << attr
<< AANT_ArgumentString
;
6844 Qualifiers::GC GCAttr
;
6845 if (attr
.getNumArgs() > 1) {
6846 S
.Diag(attr
.getLoc(), diag::err_attribute_wrong_number_arguments
) << attr
6852 IdentifierInfo
*II
= attr
.getArgAsIdent(0)->Ident
;
6853 if (II
->isStr("weak"))
6854 GCAttr
= Qualifiers::Weak
;
6855 else if (II
->isStr("strong"))
6856 GCAttr
= Qualifiers::Strong
;
6858 S
.Diag(attr
.getLoc(), diag::warn_attribute_type_not_supported
)
6864 QualType origType
= type
;
6865 type
= S
.Context
.getObjCGCQualType(origType
, GCAttr
);
6867 // Make an attributed type to preserve the source information.
6868 if (attr
.getLoc().isValid())
6869 type
= state
.getAttributedType(
6870 ::new (S
.Context
) ObjCGCAttr(S
.Context
, attr
, II
), origType
, type
);
6876 /// A helper class to unwrap a type down to a function for the
6877 /// purposes of applying attributes there.
6880 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
6881 /// if (unwrapped.isFunctionType()) {
6882 /// const FunctionType *fn = unwrapped.get();
6883 /// // change fn somehow
6884 /// T = unwrapped.wrap(fn);
6886 struct FunctionTypeUnwrapper
{
6900 const FunctionType
*Fn
;
6901 SmallVector
<unsigned char /*WrapKind*/, 8> Stack
;
6903 FunctionTypeUnwrapper(Sema
&S
, QualType T
) : Original(T
) {
6905 const Type
*Ty
= T
.getTypePtr();
6906 if (isa
<FunctionType
>(Ty
)) {
6907 Fn
= cast
<FunctionType
>(Ty
);
6909 } else if (isa
<ParenType
>(Ty
)) {
6910 T
= cast
<ParenType
>(Ty
)->getInnerType();
6911 Stack
.push_back(Parens
);
6912 } else if (isa
<ConstantArrayType
>(Ty
) || isa
<VariableArrayType
>(Ty
) ||
6913 isa
<IncompleteArrayType
>(Ty
)) {
6914 T
= cast
<ArrayType
>(Ty
)->getElementType();
6915 Stack
.push_back(Array
);
6916 } else if (isa
<PointerType
>(Ty
)) {
6917 T
= cast
<PointerType
>(Ty
)->getPointeeType();
6918 Stack
.push_back(Pointer
);
6919 } else if (isa
<BlockPointerType
>(Ty
)) {
6920 T
= cast
<BlockPointerType
>(Ty
)->getPointeeType();
6921 Stack
.push_back(BlockPointer
);
6922 } else if (isa
<MemberPointerType
>(Ty
)) {
6923 T
= cast
<MemberPointerType
>(Ty
)->getPointeeType();
6924 Stack
.push_back(MemberPointer
);
6925 } else if (isa
<ReferenceType
>(Ty
)) {
6926 T
= cast
<ReferenceType
>(Ty
)->getPointeeType();
6927 Stack
.push_back(Reference
);
6928 } else if (isa
<AttributedType
>(Ty
)) {
6929 T
= cast
<AttributedType
>(Ty
)->getEquivalentType();
6930 Stack
.push_back(Attributed
);
6931 } else if (isa
<MacroQualifiedType
>(Ty
)) {
6932 T
= cast
<MacroQualifiedType
>(Ty
)->getUnderlyingType();
6933 Stack
.push_back(MacroQualified
);
6935 const Type
*DTy
= Ty
->getUnqualifiedDesugaredType();
6941 T
= QualType(DTy
, 0);
6942 Stack
.push_back(Desugar
);
6947 bool isFunctionType() const { return (Fn
!= nullptr); }
6948 const FunctionType
*get() const { return Fn
; }
6950 QualType
wrap(Sema
&S
, const FunctionType
*New
) {
6951 // If T wasn't modified from the unwrapped type, do nothing.
6952 if (New
== get()) return Original
;
6955 return wrap(S
.Context
, Original
, 0);
6959 QualType
wrap(ASTContext
&C
, QualType Old
, unsigned I
) {
6960 if (I
== Stack
.size())
6961 return C
.getQualifiedType(Fn
, Old
.getQualifiers());
6963 // Build up the inner type, applying the qualifiers from the old
6964 // type to the new type.
6965 SplitQualType SplitOld
= Old
.split();
6967 // As a special case, tail-recurse if there are no qualifiers.
6968 if (SplitOld
.Quals
.empty())
6969 return wrap(C
, SplitOld
.Ty
, I
);
6970 return C
.getQualifiedType(wrap(C
, SplitOld
.Ty
, I
), SplitOld
.Quals
);
6973 QualType
wrap(ASTContext
&C
, const Type
*Old
, unsigned I
) {
6974 if (I
== Stack
.size()) return QualType(Fn
, 0);
6976 switch (static_cast<WrapKind
>(Stack
[I
++])) {
6978 // This is the point at which we potentially lose source
6980 return wrap(C
, Old
->getUnqualifiedDesugaredType(), I
);
6983 return wrap(C
, cast
<AttributedType
>(Old
)->getEquivalentType(), I
);
6986 QualType New
= wrap(C
, cast
<ParenType
>(Old
)->getInnerType(), I
);
6987 return C
.getParenType(New
);
6990 case MacroQualified
:
6991 return wrap(C
, cast
<MacroQualifiedType
>(Old
)->getUnderlyingType(), I
);
6994 if (const auto *CAT
= dyn_cast
<ConstantArrayType
>(Old
)) {
6995 QualType New
= wrap(C
, CAT
->getElementType(), I
);
6996 return C
.getConstantArrayType(New
, CAT
->getSize(), CAT
->getSizeExpr(),
6997 CAT
->getSizeModifier(),
6998 CAT
->getIndexTypeCVRQualifiers());
7001 if (const auto *VAT
= dyn_cast
<VariableArrayType
>(Old
)) {
7002 QualType New
= wrap(C
, VAT
->getElementType(), I
);
7003 return C
.getVariableArrayType(
7004 New
, VAT
->getSizeExpr(), VAT
->getSizeModifier(),
7005 VAT
->getIndexTypeCVRQualifiers(), VAT
->getBracketsRange());
7008 const auto *IAT
= cast
<IncompleteArrayType
>(Old
);
7009 QualType New
= wrap(C
, IAT
->getElementType(), I
);
7010 return C
.getIncompleteArrayType(New
, IAT
->getSizeModifier(),
7011 IAT
->getIndexTypeCVRQualifiers());
7015 QualType New
= wrap(C
, cast
<PointerType
>(Old
)->getPointeeType(), I
);
7016 return C
.getPointerType(New
);
7019 case BlockPointer
: {
7020 QualType New
= wrap(C
, cast
<BlockPointerType
>(Old
)->getPointeeType(),I
);
7021 return C
.getBlockPointerType(New
);
7024 case MemberPointer
: {
7025 const MemberPointerType
*OldMPT
= cast
<MemberPointerType
>(Old
);
7026 QualType New
= wrap(C
, OldMPT
->getPointeeType(), I
);
7027 return C
.getMemberPointerType(New
, OldMPT
->getClass());
7031 const ReferenceType
*OldRef
= cast
<ReferenceType
>(Old
);
7032 QualType New
= wrap(C
, OldRef
->getPointeeType(), I
);
7033 if (isa
<LValueReferenceType
>(OldRef
))
7034 return C
.getLValueReferenceType(New
, OldRef
->isSpelledAsLValue());
7036 return C
.getRValueReferenceType(New
);
7040 llvm_unreachable("unknown wrapping kind");
7043 } // end anonymous namespace
7045 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState
&State
,
7046 ParsedAttr
&PAttr
, QualType
&Type
) {
7047 Sema
&S
= State
.getSema();
7050 switch (PAttr
.getKind()) {
7051 default: llvm_unreachable("Unknown attribute kind");
7052 case ParsedAttr::AT_Ptr32
:
7053 A
= createSimpleAttr
<Ptr32Attr
>(S
.Context
, PAttr
);
7055 case ParsedAttr::AT_Ptr64
:
7056 A
= createSimpleAttr
<Ptr64Attr
>(S
.Context
, PAttr
);
7058 case ParsedAttr::AT_SPtr
:
7059 A
= createSimpleAttr
<SPtrAttr
>(S
.Context
, PAttr
);
7061 case ParsedAttr::AT_UPtr
:
7062 A
= createSimpleAttr
<UPtrAttr
>(S
.Context
, PAttr
);
7066 std::bitset
<attr::LastAttr
> Attrs
;
7067 QualType Desugared
= Type
;
7069 if (const TypedefType
*TT
= dyn_cast
<TypedefType
>(Desugared
)) {
7070 Desugared
= TT
->desugar();
7072 } else if (const ElaboratedType
*ET
= dyn_cast
<ElaboratedType
>(Desugared
)) {
7073 Desugared
= ET
->desugar();
7076 const AttributedType
*AT
= dyn_cast
<AttributedType
>(Desugared
);
7079 Attrs
[AT
->getAttrKind()] = true;
7080 Desugared
= AT
->getModifiedType();
7083 // You cannot specify duplicate type attributes, so if the attribute has
7084 // already been applied, flag it.
7085 attr::Kind NewAttrKind
= A
->getKind();
7086 if (Attrs
[NewAttrKind
]) {
7087 S
.Diag(PAttr
.getLoc(), diag::warn_duplicate_attribute_exact
) << PAttr
;
7090 Attrs
[NewAttrKind
] = true;
7092 // You cannot have both __sptr and __uptr on the same type, nor can you
7093 // have __ptr32 and __ptr64.
7094 if (Attrs
[attr::Ptr32
] && Attrs
[attr::Ptr64
]) {
7095 S
.Diag(PAttr
.getLoc(), diag::err_attributes_are_not_compatible
)
7097 << "'__ptr64'" << /*isRegularKeyword=*/0;
7099 } else if (Attrs
[attr::SPtr
] && Attrs
[attr::UPtr
]) {
7100 S
.Diag(PAttr
.getLoc(), diag::err_attributes_are_not_compatible
)
7102 << "'__uptr'" << /*isRegularKeyword=*/0;
7106 // Check the raw (i.e., desugared) Canonical type to see if it
7107 // is a pointer type.
7108 if (!isa
<PointerType
>(Desugared
)) {
7109 // Pointer type qualifiers can only operate on pointer types, but not
7110 // pointer-to-member types.
7111 if (Type
->isMemberPointerType())
7112 S
.Diag(PAttr
.getLoc(), diag::err_attribute_no_member_pointers
) << PAttr
;
7114 S
.Diag(PAttr
.getLoc(), diag::err_attribute_pointers_only
) << PAttr
<< 0;
7118 // Add address space to type based on its attributes.
7119 LangAS ASIdx
= LangAS::Default
;
7121 S
.Context
.getTargetInfo().getPointerWidth(LangAS::Default
);
7122 if (PtrWidth
== 32) {
7123 if (Attrs
[attr::Ptr64
])
7124 ASIdx
= LangAS::ptr64
;
7125 else if (Attrs
[attr::UPtr
])
7126 ASIdx
= LangAS::ptr32_uptr
;
7127 } else if (PtrWidth
== 64 && Attrs
[attr::Ptr32
]) {
7128 if (S
.Context
.getTargetInfo().getTriple().isOSzOS() || Attrs
[attr::UPtr
])
7129 ASIdx
= LangAS::ptr32_uptr
;
7131 ASIdx
= LangAS::ptr32_sptr
;
7134 QualType Pointee
= Type
->getPointeeType();
7135 if (ASIdx
!= LangAS::Default
)
7136 Pointee
= S
.Context
.getAddrSpaceQualType(
7137 S
.Context
.removeAddrSpaceQualType(Pointee
), ASIdx
);
7138 Type
= State
.getAttributedType(A
, Type
, S
.Context
.getPointerType(Pointee
));
7142 static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState
&State
,
7143 QualType
&QT
, ParsedAttr
&PAttr
) {
7144 assert(PAttr
.getKind() == ParsedAttr::AT_WebAssemblyFuncref
);
7146 Sema
&S
= State
.getSema();
7147 Attr
*A
= createSimpleAttr
<WebAssemblyFuncrefAttr
>(S
.Context
, PAttr
);
7149 std::bitset
<attr::LastAttr
> Attrs
;
7150 attr::Kind NewAttrKind
= A
->getKind();
7151 const auto *AT
= dyn_cast
<AttributedType
>(QT
);
7153 Attrs
[AT
->getAttrKind()] = true;
7154 AT
= dyn_cast
<AttributedType
>(AT
->getModifiedType());
7157 // You cannot specify duplicate type attributes, so if the attribute has
7158 // already been applied, flag it.
7159 if (Attrs
[NewAttrKind
]) {
7160 S
.Diag(PAttr
.getLoc(), diag::warn_duplicate_attribute_exact
) << PAttr
;
7164 // Add address space to type based on its attributes.
7165 LangAS ASIdx
= LangAS::wasm_funcref
;
7166 QualType Pointee
= QT
->getPointeeType();
7167 Pointee
= S
.Context
.getAddrSpaceQualType(
7168 S
.Context
.removeAddrSpaceQualType(Pointee
), ASIdx
);
7169 QT
= State
.getAttributedType(A
, QT
, S
.Context
.getPointerType(Pointee
));
7173 static void HandleSwiftAttr(TypeProcessingState
&State
, TypeAttrLocation TAL
,
7174 QualType
&QT
, ParsedAttr
&PAttr
) {
7175 if (TAL
== TAL_DeclName
)
7178 Sema
&S
= State
.getSema();
7179 auto &D
= State
.getDeclarator();
7181 // If the attribute appears in declaration specifiers
7182 // it should be handled as a declaration attribute,
7183 // unless it's associated with a type or a function
7184 // prototype (i.e. appears on a parameter or result type).
7185 if (State
.isProcessingDeclSpec()) {
7186 if (!(D
.isPrototypeContext() ||
7187 D
.getContext() == DeclaratorContext::TypeName
))
7190 if (auto *chunk
= D
.getInnermostNonParenChunk()) {
7191 moveAttrFromListToList(PAttr
, State
.getCurrentAttributes(),
7192 const_cast<DeclaratorChunk
*>(chunk
)->getAttrs());
7198 if (!S
.checkStringLiteralArgumentAttr(PAttr
, 0, Str
)) {
7203 // If the attribute as attached to a paren move it closer to
7204 // the declarator. This can happen in block declarations when
7205 // an attribute is placed before `^` i.e. `(__attribute__((...)) ^)`.
7207 // Note that it's actually invalid to use GNU style attributes
7208 // in a block but such cases are currently handled gracefully
7209 // but the parser and behavior should be consistent between
7210 // cases when attribute appears before/after block's result
7211 // type and inside (^).
7212 if (TAL
== TAL_DeclChunk
) {
7213 auto chunkIdx
= State
.getCurrentChunkIndex();
7214 if (chunkIdx
>= 1 &&
7215 D
.getTypeObject(chunkIdx
).Kind
== DeclaratorChunk::Paren
) {
7216 moveAttrFromListToList(PAttr
, State
.getCurrentAttributes(),
7217 D
.getTypeObject(chunkIdx
- 1).getAttrs());
7222 auto *A
= ::new (S
.Context
) SwiftAttrAttr(S
.Context
, PAttr
, Str
);
7223 QT
= State
.getAttributedType(A
, QT
, QT
);
7224 PAttr
.setUsedAsTypeAttr();
7227 /// Rebuild an attributed type without the nullability attribute on it.
7228 static QualType
rebuildAttributedTypeWithoutNullability(ASTContext
&Ctx
,
7230 auto Attributed
= dyn_cast
<AttributedType
>(Type
.getTypePtr());
7234 // Skip the nullability attribute; we're done.
7235 if (Attributed
->getImmediateNullability())
7236 return Attributed
->getModifiedType();
7238 // Build the modified type.
7239 QualType Modified
= rebuildAttributedTypeWithoutNullability(
7240 Ctx
, Attributed
->getModifiedType());
7241 assert(Modified
.getTypePtr() != Attributed
->getModifiedType().getTypePtr());
7242 return Ctx
.getAttributedType(Attributed
->getAttrKind(), Modified
,
7243 Attributed
->getEquivalentType(),
7244 Attributed
->getAttr());
7247 /// Map a nullability attribute kind to a nullability kind.
7248 static NullabilityKind
mapNullabilityAttrKind(ParsedAttr::Kind kind
) {
7250 case ParsedAttr::AT_TypeNonNull
:
7251 return NullabilityKind::NonNull
;
7253 case ParsedAttr::AT_TypeNullable
:
7254 return NullabilityKind::Nullable
;
7256 case ParsedAttr::AT_TypeNullableResult
:
7257 return NullabilityKind::NullableResult
;
7259 case ParsedAttr::AT_TypeNullUnspecified
:
7260 return NullabilityKind::Unspecified
;
7263 llvm_unreachable("not a nullability attribute kind");
7267 static bool CheckNullabilityTypeSpecifier(
7268 Sema
&S
, TypeProcessingState
*State
, ParsedAttr
*PAttr
, QualType
&QT
,
7269 NullabilityKind Nullability
, SourceLocation NullabilityLoc
,
7270 bool IsContextSensitive
, bool AllowOnArrayType
, bool OverrideExisting
) {
7271 bool Implicit
= (State
== nullptr);
7273 recordNullabilitySeen(S
, NullabilityLoc
);
7275 // Check for existing nullability attributes on the type.
7276 QualType Desugared
= QT
;
7277 while (auto *Attributed
= dyn_cast
<AttributedType
>(Desugared
.getTypePtr())) {
7278 // Check whether there is already a null
7279 if (auto ExistingNullability
= Attributed
->getImmediateNullability()) {
7280 // Duplicated nullability.
7281 if (Nullability
== *ExistingNullability
) {
7285 S
.Diag(NullabilityLoc
, diag::warn_nullability_duplicate
)
7286 << DiagNullabilityKind(Nullability
, IsContextSensitive
)
7287 << FixItHint::CreateRemoval(NullabilityLoc
);
7292 if (!OverrideExisting
) {
7293 // Conflicting nullability.
7294 S
.Diag(NullabilityLoc
, diag::err_nullability_conflicting
)
7295 << DiagNullabilityKind(Nullability
, IsContextSensitive
)
7296 << DiagNullabilityKind(*ExistingNullability
, false);
7300 // Rebuild the attributed type, dropping the existing nullability.
7301 QT
= rebuildAttributedTypeWithoutNullability(S
.Context
, QT
);
7304 Desugared
= Attributed
->getModifiedType();
7307 // If there is already a different nullability specifier, complain.
7308 // This (unlike the code above) looks through typedefs that might
7309 // have nullability specifiers on them, which means we cannot
7310 // provide a useful Fix-It.
7311 if (auto ExistingNullability
= Desugared
->getNullability()) {
7312 if (Nullability
!= *ExistingNullability
&& !Implicit
) {
7313 S
.Diag(NullabilityLoc
, diag::err_nullability_conflicting
)
7314 << DiagNullabilityKind(Nullability
, IsContextSensitive
)
7315 << DiagNullabilityKind(*ExistingNullability
, false);
7317 // Try to find the typedef with the existing nullability specifier.
7318 if (auto TT
= Desugared
->getAs
<TypedefType
>()) {
7319 TypedefNameDecl
*typedefDecl
= TT
->getDecl();
7320 QualType underlyingType
= typedefDecl
->getUnderlyingType();
7321 if (auto typedefNullability
=
7322 AttributedType::stripOuterNullability(underlyingType
)) {
7323 if (*typedefNullability
== *ExistingNullability
) {
7324 S
.Diag(typedefDecl
->getLocation(), diag::note_nullability_here
)
7325 << DiagNullabilityKind(*ExistingNullability
, false);
7334 // If this definitely isn't a pointer type, reject the specifier.
7335 if (!Desugared
->canHaveNullability() &&
7336 !(AllowOnArrayType
&& Desugared
->isArrayType())) {
7338 S
.Diag(NullabilityLoc
, diag::err_nullability_nonpointer
)
7339 << DiagNullabilityKind(Nullability
, IsContextSensitive
) << QT
;
7344 // For the context-sensitive keywords/Objective-C property
7345 // attributes, require that the type be a single-level pointer.
7346 if (IsContextSensitive
) {
7347 // Make sure that the pointee isn't itself a pointer type.
7348 const Type
*pointeeType
= nullptr;
7349 if (Desugared
->isArrayType())
7350 pointeeType
= Desugared
->getArrayElementTypeNoTypeQual();
7351 else if (Desugared
->isAnyPointerType())
7352 pointeeType
= Desugared
->getPointeeType().getTypePtr();
7354 if (pointeeType
&& (pointeeType
->isAnyPointerType() ||
7355 pointeeType
->isObjCObjectPointerType() ||
7356 pointeeType
->isMemberPointerType())) {
7357 S
.Diag(NullabilityLoc
, diag::err_nullability_cs_multilevel
)
7358 << DiagNullabilityKind(Nullability
, true) << QT
;
7359 S
.Diag(NullabilityLoc
, diag::note_nullability_type_specifier
)
7360 << DiagNullabilityKind(Nullability
, false) << QT
7361 << FixItHint::CreateReplacement(NullabilityLoc
,
7362 getNullabilitySpelling(Nullability
));
7367 // Form the attributed type.
7370 Attr
*A
= createNullabilityAttr(S
.Context
, *PAttr
, Nullability
);
7371 QT
= State
->getAttributedType(A
, QT
, QT
);
7373 QT
= S
.Context
.getAttributedType(Nullability
, QT
, QT
);
7378 static bool CheckNullabilityTypeSpecifier(TypeProcessingState
&State
,
7379 QualType
&Type
, ParsedAttr
&Attr
,
7380 bool AllowOnArrayType
) {
7381 NullabilityKind Nullability
= mapNullabilityAttrKind(Attr
.getKind());
7382 SourceLocation NullabilityLoc
= Attr
.getLoc();
7383 bool IsContextSensitive
= Attr
.isContextSensitiveKeywordAttribute();
7385 return CheckNullabilityTypeSpecifier(State
.getSema(), &State
, &Attr
, Type
,
7386 Nullability
, NullabilityLoc
,
7387 IsContextSensitive
, AllowOnArrayType
,
7388 /*overrideExisting*/ false);
7391 bool Sema::CheckImplicitNullabilityTypeSpecifier(QualType
&Type
,
7392 NullabilityKind Nullability
,
7393 SourceLocation DiagLoc
,
7394 bool AllowArrayTypes
,
7395 bool OverrideExisting
) {
7396 return CheckNullabilityTypeSpecifier(
7397 *this, nullptr, nullptr, Type
, Nullability
, DiagLoc
,
7398 /*isContextSensitive*/ false, AllowArrayTypes
, OverrideExisting
);
7401 /// Check the application of the Objective-C '__kindof' qualifier to
7403 static bool checkObjCKindOfType(TypeProcessingState
&state
, QualType
&type
,
7405 Sema
&S
= state
.getSema();
7407 if (isa
<ObjCTypeParamType
>(type
)) {
7408 // Build the attributed type to record where __kindof occurred.
7409 type
= state
.getAttributedType(
7410 createSimpleAttr
<ObjCKindOfAttr
>(S
.Context
, attr
), type
, type
);
7414 // Find out if it's an Objective-C object or object pointer type;
7415 const ObjCObjectPointerType
*ptrType
= type
->getAs
<ObjCObjectPointerType
>();
7416 const ObjCObjectType
*objType
= ptrType
? ptrType
->getObjectType()
7417 : type
->getAs
<ObjCObjectType
>();
7419 // If not, we can't apply __kindof.
7421 // FIXME: Handle dependent types that aren't yet object types.
7422 S
.Diag(attr
.getLoc(), diag::err_objc_kindof_nonobject
)
7427 // Rebuild the "equivalent" type, which pushes __kindof down into
7429 // There is no need to apply kindof on an unqualified id type.
7430 QualType equivType
= S
.Context
.getObjCObjectType(
7431 objType
->getBaseType(), objType
->getTypeArgsAsWritten(),
7432 objType
->getProtocols(),
7433 /*isKindOf=*/objType
->isObjCUnqualifiedId() ? false : true);
7435 // If we started with an object pointer type, rebuild it.
7437 equivType
= S
.Context
.getObjCObjectPointerType(equivType
);
7438 if (auto nullability
= type
->getNullability()) {
7439 // We create a nullability attribute from the __kindof attribute.
7440 // Make sure that will make sense.
7441 assert(attr
.getAttributeSpellingListIndex() == 0 &&
7442 "multiple spellings for __kindof?");
7443 Attr
*A
= createNullabilityAttr(S
.Context
, attr
, *nullability
);
7444 A
->setImplicit(true);
7445 equivType
= state
.getAttributedType(A
, equivType
, equivType
);
7449 // Build the attributed type to record where __kindof occurred.
7450 type
= state
.getAttributedType(
7451 createSimpleAttr
<ObjCKindOfAttr
>(S
.Context
, attr
), type
, equivType
);
7455 /// Distribute a nullability type attribute that cannot be applied to
7456 /// the type specifier to a pointer, block pointer, or member pointer
7457 /// declarator, complaining if necessary.
7459 /// \returns true if the nullability annotation was distributed, false
7461 static bool distributeNullabilityTypeAttr(TypeProcessingState
&state
,
7462 QualType type
, ParsedAttr
&attr
) {
7463 Declarator
&declarator
= state
.getDeclarator();
7465 /// Attempt to move the attribute to the specified chunk.
7466 auto moveToChunk
= [&](DeclaratorChunk
&chunk
, bool inFunction
) -> bool {
7467 // If there is already a nullability attribute there, don't add
7469 if (hasNullabilityAttr(chunk
.getAttrs()))
7472 // Complain about the nullability qualifier being in the wrong
7479 PK_MemberFunctionPointer
,
7481 = chunk
.Kind
== DeclaratorChunk::Pointer
? (inFunction
? PK_FunctionPointer
7483 : chunk
.Kind
== DeclaratorChunk::BlockPointer
? PK_BlockPointer
7484 : inFunction
? PK_MemberFunctionPointer
: PK_MemberPointer
;
7486 auto diag
= state
.getSema().Diag(attr
.getLoc(),
7487 diag::warn_nullability_declspec
)
7488 << DiagNullabilityKind(mapNullabilityAttrKind(attr
.getKind()),
7489 attr
.isContextSensitiveKeywordAttribute())
7491 << static_cast<unsigned>(pointerKind
);
7493 // FIXME: MemberPointer chunks don't carry the location of the *.
7494 if (chunk
.Kind
!= DeclaratorChunk::MemberPointer
) {
7495 diag
<< FixItHint::CreateRemoval(attr
.getLoc())
7496 << FixItHint::CreateInsertion(
7497 state
.getSema().getPreprocessor().getLocForEndOfToken(
7499 " " + attr
.getAttrName()->getName().str() + " ");
7502 moveAttrFromListToList(attr
, state
.getCurrentAttributes(),
7507 // Move it to the outermost pointer, member pointer, or block
7508 // pointer declarator.
7509 for (unsigned i
= state
.getCurrentChunkIndex(); i
!= 0; --i
) {
7510 DeclaratorChunk
&chunk
= declarator
.getTypeObject(i
-1);
7511 switch (chunk
.Kind
) {
7512 case DeclaratorChunk::Pointer
:
7513 case DeclaratorChunk::BlockPointer
:
7514 case DeclaratorChunk::MemberPointer
:
7515 return moveToChunk(chunk
, false);
7517 case DeclaratorChunk::Paren
:
7518 case DeclaratorChunk::Array
:
7521 case DeclaratorChunk::Function
:
7522 // Try to move past the return type to a function/block/member
7523 // function pointer.
7524 if (DeclaratorChunk
*dest
= maybeMovePastReturnType(
7526 /*onlyBlockPointers=*/false)) {
7527 return moveToChunk(*dest
, true);
7532 // Don't walk through these.
7533 case DeclaratorChunk::Reference
:
7534 case DeclaratorChunk::Pipe
:
7542 static Attr
*getCCTypeAttr(ASTContext
&Ctx
, ParsedAttr
&Attr
) {
7543 assert(!Attr
.isInvalid());
7544 switch (Attr
.getKind()) {
7546 llvm_unreachable("not a calling convention attribute");
7547 case ParsedAttr::AT_CDecl
:
7548 return createSimpleAttr
<CDeclAttr
>(Ctx
, Attr
);
7549 case ParsedAttr::AT_FastCall
:
7550 return createSimpleAttr
<FastCallAttr
>(Ctx
, Attr
);
7551 case ParsedAttr::AT_StdCall
:
7552 return createSimpleAttr
<StdCallAttr
>(Ctx
, Attr
);
7553 case ParsedAttr::AT_ThisCall
:
7554 return createSimpleAttr
<ThisCallAttr
>(Ctx
, Attr
);
7555 case ParsedAttr::AT_RegCall
:
7556 return createSimpleAttr
<RegCallAttr
>(Ctx
, Attr
);
7557 case ParsedAttr::AT_Pascal
:
7558 return createSimpleAttr
<PascalAttr
>(Ctx
, Attr
);
7559 case ParsedAttr::AT_SwiftCall
:
7560 return createSimpleAttr
<SwiftCallAttr
>(Ctx
, Attr
);
7561 case ParsedAttr::AT_SwiftAsyncCall
:
7562 return createSimpleAttr
<SwiftAsyncCallAttr
>(Ctx
, Attr
);
7563 case ParsedAttr::AT_VectorCall
:
7564 return createSimpleAttr
<VectorCallAttr
>(Ctx
, Attr
);
7565 case ParsedAttr::AT_AArch64VectorPcs
:
7566 return createSimpleAttr
<AArch64VectorPcsAttr
>(Ctx
, Attr
);
7567 case ParsedAttr::AT_AArch64SVEPcs
:
7568 return createSimpleAttr
<AArch64SVEPcsAttr
>(Ctx
, Attr
);
7569 case ParsedAttr::AT_ArmStreaming
:
7570 return createSimpleAttr
<ArmStreamingAttr
>(Ctx
, Attr
);
7571 case ParsedAttr::AT_AMDGPUKernelCall
:
7572 return createSimpleAttr
<AMDGPUKernelCallAttr
>(Ctx
, Attr
);
7573 case ParsedAttr::AT_Pcs
: {
7574 // The attribute may have had a fixit applied where we treated an
7575 // identifier as a string literal. The contents of the string are valid,
7576 // but the form may not be.
7578 if (Attr
.isArgExpr(0))
7579 Str
= cast
<StringLiteral
>(Attr
.getArgAsExpr(0))->getString();
7581 Str
= Attr
.getArgAsIdent(0)->Ident
->getName();
7582 PcsAttr::PCSType Type
;
7583 if (!PcsAttr::ConvertStrToPCSType(Str
, Type
))
7584 llvm_unreachable("already validated the attribute");
7585 return ::new (Ctx
) PcsAttr(Ctx
, Attr
, Type
);
7587 case ParsedAttr::AT_IntelOclBicc
:
7588 return createSimpleAttr
<IntelOclBiccAttr
>(Ctx
, Attr
);
7589 case ParsedAttr::AT_MSABI
:
7590 return createSimpleAttr
<MSABIAttr
>(Ctx
, Attr
);
7591 case ParsedAttr::AT_SysVABI
:
7592 return createSimpleAttr
<SysVABIAttr
>(Ctx
, Attr
);
7593 case ParsedAttr::AT_PreserveMost
:
7594 return createSimpleAttr
<PreserveMostAttr
>(Ctx
, Attr
);
7595 case ParsedAttr::AT_PreserveAll
:
7596 return createSimpleAttr
<PreserveAllAttr
>(Ctx
, Attr
);
7597 case ParsedAttr::AT_M68kRTD
:
7598 return createSimpleAttr
<M68kRTDAttr
>(Ctx
, Attr
);
7599 case ParsedAttr::AT_PreserveNone
:
7600 return createSimpleAttr
<PreserveNoneAttr
>(Ctx
, Attr
);
7601 case ParsedAttr::AT_RISCVVectorCC
:
7602 return createSimpleAttr
<RISCVVectorCCAttr
>(Ctx
, Attr
);
7604 llvm_unreachable("unexpected attribute kind!");
7607 std::optional
<FunctionEffectMode
>
7608 Sema::ActOnEffectExpression(Expr
*CondExpr
, StringRef AttributeName
) {
7609 if (CondExpr
->isTypeDependent() || CondExpr
->isValueDependent())
7610 return FunctionEffectMode::Dependent
;
7612 std::optional
<llvm::APSInt
> ConditionValue
=
7613 CondExpr
->getIntegerConstantExpr(Context
);
7614 if (!ConditionValue
) {
7615 // FIXME: err_attribute_argument_type doesn't quote the attribute
7616 // name but needs to; users are inconsistent.
7617 Diag(CondExpr
->getExprLoc(), diag::err_attribute_argument_type
)
7618 << AttributeName
<< AANT_ArgumentIntegerConstant
7619 << CondExpr
->getSourceRange();
7620 return std::nullopt
;
7622 return !ConditionValue
->isZero() ? FunctionEffectMode::True
7623 : FunctionEffectMode::False
;
7627 handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState
&TPState
,
7628 ParsedAttr
&PAttr
, QualType
&QT
,
7629 FunctionTypeUnwrapper
&Unwrapped
) {
7630 // Delay if this is not a function type.
7631 if (!Unwrapped
.isFunctionType())
7634 Sema
&S
= TPState
.getSema();
7636 // Require FunctionProtoType.
7637 auto *FPT
= Unwrapped
.get()->getAs
<FunctionProtoType
>();
7638 if (FPT
== nullptr) {
7639 S
.Diag(PAttr
.getLoc(), diag::err_func_with_effects_no_prototype
)
7640 << PAttr
.getAttrName()->getName();
7644 // Parse the new attribute.
7645 // non/blocking or non/allocating? Or conditional (computed)?
7646 bool IsNonBlocking
= PAttr
.getKind() == ParsedAttr::AT_NonBlocking
||
7647 PAttr
.getKind() == ParsedAttr::AT_Blocking
;
7649 FunctionEffectMode NewMode
= FunctionEffectMode::None
;
7650 Expr
*CondExpr
= nullptr; // only valid if dependent
7652 if (PAttr
.getKind() == ParsedAttr::AT_NonBlocking
||
7653 PAttr
.getKind() == ParsedAttr::AT_NonAllocating
) {
7654 if (!PAttr
.checkAtMostNumArgs(S
, 1)) {
7659 // Parse the condition, if any.
7660 if (PAttr
.getNumArgs() == 1) {
7661 CondExpr
= PAttr
.getArgAsExpr(0);
7662 std::optional
<FunctionEffectMode
> MaybeMode
=
7663 S
.ActOnEffectExpression(CondExpr
, PAttr
.getAttrName()->getName());
7668 NewMode
= *MaybeMode
;
7669 if (NewMode
!= FunctionEffectMode::Dependent
)
7672 NewMode
= FunctionEffectMode::True
;
7675 // This is the `blocking` or `allocating` attribute.
7676 if (S
.CheckAttrNoArgs(PAttr
)) {
7677 // The attribute has been marked invalid.
7680 NewMode
= FunctionEffectMode::False
;
7683 const FunctionEffect::Kind FEKind
=
7684 (NewMode
== FunctionEffectMode::False
)
7685 ? (IsNonBlocking
? FunctionEffect::Kind::Blocking
7686 : FunctionEffect::Kind::Allocating
)
7687 : (IsNonBlocking
? FunctionEffect::Kind::NonBlocking
7688 : FunctionEffect::Kind::NonAllocating
);
7689 const FunctionEffectWithCondition NewEC
{FunctionEffect(FEKind
),
7690 EffectConditionExpr(CondExpr
)};
7692 if (S
.diagnoseConflictingFunctionEffect(FPT
->getFunctionEffects(), NewEC
,
7698 // Add the effect to the FunctionProtoType.
7699 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
7700 FunctionEffectSet
FX(EPI
.FunctionEffects
);
7701 FunctionEffectSet::Conflicts Errs
;
7702 [[maybe_unused
]] bool Success
= FX
.insert(NewEC
, Errs
);
7703 assert(Success
&& "effect conflicts should have been diagnosed above");
7704 EPI
.FunctionEffects
= FunctionEffectsRef(FX
);
7706 QualType NewType
= S
.Context
.getFunctionType(FPT
->getReturnType(),
7707 FPT
->getParamTypes(), EPI
);
7708 QT
= Unwrapped
.wrap(S
, NewType
->getAs
<FunctionType
>());
7712 static bool checkMutualExclusion(TypeProcessingState
&state
,
7713 const FunctionProtoType::ExtProtoInfo
&EPI
,
7715 AttributeCommonInfo::Kind OtherKind
) {
7716 auto OtherAttr
= std::find_if(
7717 state
.getCurrentAttributes().begin(), state
.getCurrentAttributes().end(),
7718 [OtherKind
](const ParsedAttr
&A
) { return A
.getKind() == OtherKind
; });
7719 if (OtherAttr
== state
.getCurrentAttributes().end() || OtherAttr
->isInvalid())
7722 Sema
&S
= state
.getSema();
7723 S
.Diag(Attr
.getLoc(), diag::err_attributes_are_not_compatible
)
7724 << *OtherAttr
<< Attr
7725 << (OtherAttr
->isRegularKeywordAttribute() ||
7726 Attr
.isRegularKeywordAttribute());
7727 S
.Diag(OtherAttr
->getLoc(), diag::note_conflicting_attribute
);
7732 static bool handleArmStateAttribute(Sema
&S
,
7733 FunctionProtoType::ExtProtoInfo
&EPI
,
7735 FunctionType::ArmStateValue State
) {
7736 if (!Attr
.getNumArgs()) {
7737 S
.Diag(Attr
.getLoc(), diag::err_missing_arm_state
) << Attr
;
7742 for (unsigned I
= 0; I
< Attr
.getNumArgs(); ++I
) {
7743 StringRef StateName
;
7744 SourceLocation LiteralLoc
;
7745 if (!S
.checkStringLiteralArgumentAttr(Attr
, I
, StateName
, &LiteralLoc
))
7749 FunctionType::ArmStateValue ExistingState
;
7750 if (StateName
== "za") {
7751 Shift
= FunctionType::SME_ZAShift
;
7752 ExistingState
= FunctionType::getArmZAState(EPI
.AArch64SMEAttributes
);
7753 } else if (StateName
== "zt0") {
7754 Shift
= FunctionType::SME_ZT0Shift
;
7755 ExistingState
= FunctionType::getArmZT0State(EPI
.AArch64SMEAttributes
);
7757 S
.Diag(LiteralLoc
, diag::err_unknown_arm_state
) << StateName
;
7762 // __arm_in(S), __arm_out(S), __arm_inout(S) and __arm_preserves(S)
7763 // are all mutually exclusive for the same S, so check if there are
7764 // conflicting attributes.
7765 if (ExistingState
!= FunctionType::ARM_None
&& ExistingState
!= State
) {
7766 S
.Diag(LiteralLoc
, diag::err_conflicting_attributes_arm_state
)
7772 EPI
.setArmSMEAttribute(
7773 (FunctionType::AArch64SMETypeAttributes
)((State
<< Shift
)));
7778 /// Process an individual function attribute. Returns true to
7779 /// indicate that the attribute was handled, false if it wasn't.
7780 static bool handleFunctionTypeAttr(TypeProcessingState
&state
, ParsedAttr
&attr
,
7781 QualType
&type
, CUDAFunctionTarget CFT
) {
7782 Sema
&S
= state
.getSema();
7784 FunctionTypeUnwrapper
unwrapped(S
, type
);
7786 if (attr
.getKind() == ParsedAttr::AT_NoReturn
) {
7787 if (S
.CheckAttrNoArgs(attr
))
7790 // Delay if this is not a function type.
7791 if (!unwrapped
.isFunctionType())
7794 // Otherwise we can process right away.
7795 FunctionType::ExtInfo EI
= unwrapped
.get()->getExtInfo().withNoReturn(true);
7796 type
= unwrapped
.wrap(S
, S
.Context
.adjustFunctionType(unwrapped
.get(), EI
));
7800 if (attr
.getKind() == ParsedAttr::AT_CmseNSCall
) {
7801 // Delay if this is not a function type.
7802 if (!unwrapped
.isFunctionType())
7805 // Ignore if we don't have CMSE enabled.
7806 if (!S
.getLangOpts().Cmse
) {
7807 S
.Diag(attr
.getLoc(), diag::warn_attribute_ignored
) << attr
;
7812 // Otherwise we can process right away.
7813 FunctionType::ExtInfo EI
=
7814 unwrapped
.get()->getExtInfo().withCmseNSCall(true);
7815 type
= unwrapped
.wrap(S
, S
.Context
.adjustFunctionType(unwrapped
.get(), EI
));
7819 // ns_returns_retained is not always a type attribute, but if we got
7820 // here, we're treating it as one right now.
7821 if (attr
.getKind() == ParsedAttr::AT_NSReturnsRetained
) {
7822 if (attr
.getNumArgs()) return true;
7824 // Delay if this is not a function type.
7825 if (!unwrapped
.isFunctionType())
7828 // Check whether the return type is reasonable.
7829 if (S
.ObjC().checkNSReturnsRetainedReturnType(
7830 attr
.getLoc(), unwrapped
.get()->getReturnType()))
7833 // Only actually change the underlying type in ARC builds.
7834 QualType origType
= type
;
7835 if (state
.getSema().getLangOpts().ObjCAutoRefCount
) {
7836 FunctionType::ExtInfo EI
7837 = unwrapped
.get()->getExtInfo().withProducesResult(true);
7838 type
= unwrapped
.wrap(S
, S
.Context
.adjustFunctionType(unwrapped
.get(), EI
));
7840 type
= state
.getAttributedType(
7841 createSimpleAttr
<NSReturnsRetainedAttr
>(S
.Context
, attr
),
7846 if (attr
.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters
) {
7847 if (S
.CheckAttrTarget(attr
) || S
.CheckAttrNoArgs(attr
))
7850 // Delay if this is not a function type.
7851 if (!unwrapped
.isFunctionType())
7854 FunctionType::ExtInfo EI
=
7855 unwrapped
.get()->getExtInfo().withNoCallerSavedRegs(true);
7856 type
= unwrapped
.wrap(S
, S
.Context
.adjustFunctionType(unwrapped
.get(), EI
));
7860 if (attr
.getKind() == ParsedAttr::AT_AnyX86NoCfCheck
) {
7861 if (!S
.getLangOpts().CFProtectionBranch
) {
7862 S
.Diag(attr
.getLoc(), diag::warn_nocf_check_attribute_ignored
);
7867 if (S
.CheckAttrTarget(attr
) || S
.CheckAttrNoArgs(attr
))
7870 // If this is not a function type, warning will be asserted by subject
7872 if (!unwrapped
.isFunctionType())
7875 FunctionType::ExtInfo EI
=
7876 unwrapped
.get()->getExtInfo().withNoCfCheck(true);
7877 type
= unwrapped
.wrap(S
, S
.Context
.adjustFunctionType(unwrapped
.get(), EI
));
7881 if (attr
.getKind() == ParsedAttr::AT_Regparm
) {
7883 if (S
.CheckRegparmAttr(attr
, value
))
7886 // Delay if this is not a function type.
7887 if (!unwrapped
.isFunctionType())
7890 // Diagnose regparm with fastcall.
7891 const FunctionType
*fn
= unwrapped
.get();
7892 CallingConv CC
= fn
->getCallConv();
7893 if (CC
== CC_X86FastCall
) {
7894 S
.Diag(attr
.getLoc(), diag::err_attributes_are_not_compatible
)
7895 << FunctionType::getNameForCallConv(CC
) << "regparm"
7896 << attr
.isRegularKeywordAttribute();
7901 FunctionType::ExtInfo EI
=
7902 unwrapped
.get()->getExtInfo().withRegParm(value
);
7903 type
= unwrapped
.wrap(S
, S
.Context
.adjustFunctionType(unwrapped
.get(), EI
));
7907 if (attr
.getKind() == ParsedAttr::AT_ArmStreaming
||
7908 attr
.getKind() == ParsedAttr::AT_ArmStreamingCompatible
||
7909 attr
.getKind() == ParsedAttr::AT_ArmPreserves
||
7910 attr
.getKind() == ParsedAttr::AT_ArmIn
||
7911 attr
.getKind() == ParsedAttr::AT_ArmOut
||
7912 attr
.getKind() == ParsedAttr::AT_ArmInOut
) {
7913 if (S
.CheckAttrTarget(attr
))
7916 if (attr
.getKind() == ParsedAttr::AT_ArmStreaming
||
7917 attr
.getKind() == ParsedAttr::AT_ArmStreamingCompatible
)
7918 if (S
.CheckAttrNoArgs(attr
))
7921 if (!unwrapped
.isFunctionType())
7924 const auto *FnTy
= unwrapped
.get()->getAs
<FunctionProtoType
>();
7926 // SME ACLE attributes are not supported on K&R-style unprototyped C
7928 S
.Diag(attr
.getLoc(), diag::warn_attribute_wrong_decl_type
) <<
7929 attr
<< attr
.isRegularKeywordAttribute() << ExpectedFunctionWithProtoType
;
7934 FunctionProtoType::ExtProtoInfo EPI
= FnTy
->getExtProtoInfo();
7935 switch (attr
.getKind()) {
7936 case ParsedAttr::AT_ArmStreaming
:
7937 if (checkMutualExclusion(state
, EPI
, attr
,
7938 ParsedAttr::AT_ArmStreamingCompatible
))
7940 EPI
.setArmSMEAttribute(FunctionType::SME_PStateSMEnabledMask
);
7942 case ParsedAttr::AT_ArmStreamingCompatible
:
7943 if (checkMutualExclusion(state
, EPI
, attr
, ParsedAttr::AT_ArmStreaming
))
7945 EPI
.setArmSMEAttribute(FunctionType::SME_PStateSMCompatibleMask
);
7947 case ParsedAttr::AT_ArmPreserves
:
7948 if (handleArmStateAttribute(S
, EPI
, attr
, FunctionType::ARM_Preserves
))
7951 case ParsedAttr::AT_ArmIn
:
7952 if (handleArmStateAttribute(S
, EPI
, attr
, FunctionType::ARM_In
))
7955 case ParsedAttr::AT_ArmOut
:
7956 if (handleArmStateAttribute(S
, EPI
, attr
, FunctionType::ARM_Out
))
7959 case ParsedAttr::AT_ArmInOut
:
7960 if (handleArmStateAttribute(S
, EPI
, attr
, FunctionType::ARM_InOut
))
7964 llvm_unreachable("Unsupported attribute");
7967 QualType newtype
= S
.Context
.getFunctionType(FnTy
->getReturnType(),
7968 FnTy
->getParamTypes(), EPI
);
7969 type
= unwrapped
.wrap(S
, newtype
->getAs
<FunctionType
>());
7973 if (attr
.getKind() == ParsedAttr::AT_NoThrow
) {
7974 // Delay if this is not a function type.
7975 if (!unwrapped
.isFunctionType())
7978 if (S
.CheckAttrNoArgs(attr
)) {
7983 // Otherwise we can process right away.
7984 auto *Proto
= unwrapped
.get()->castAs
<FunctionProtoType
>();
7986 // MSVC ignores nothrow if it is in conflict with an explicit exception
7988 if (Proto
->hasExceptionSpec()) {
7989 switch (Proto
->getExceptionSpecType()) {
7991 llvm_unreachable("This doesn't have an exception spec!");
7993 case EST_DynamicNone
:
7994 case EST_BasicNoexcept
:
7995 case EST_NoexceptTrue
:
7997 // Exception spec doesn't conflict with nothrow, so don't warn.
8000 case EST_Uninstantiated
:
8001 case EST_DependentNoexcept
:
8002 case EST_Unevaluated
:
8003 // We don't have enough information to properly determine if there is a
8004 // conflict, so suppress the warning.
8008 case EST_NoexceptFalse
:
8009 S
.Diag(attr
.getLoc(), diag::warn_nothrow_attribute_ignored
);
8015 type
= unwrapped
.wrap(
8017 .getFunctionTypeWithExceptionSpec(
8019 FunctionProtoType::ExceptionSpecInfo
{EST_NoThrow
})
8020 ->getAs
<FunctionType
>());
8024 if (attr
.getKind() == ParsedAttr::AT_NonBlocking
||
8025 attr
.getKind() == ParsedAttr::AT_NonAllocating
||
8026 attr
.getKind() == ParsedAttr::AT_Blocking
||
8027 attr
.getKind() == ParsedAttr::AT_Allocating
) {
8028 return handleNonBlockingNonAllocatingTypeAttr(state
, attr
, type
, unwrapped
);
8031 // Delay if the type didn't work out to a function.
8032 if (!unwrapped
.isFunctionType()) return false;
8034 // Otherwise, a calling convention.
8036 if (S
.CheckCallingConvAttr(attr
, CC
, /*FunctionDecl=*/nullptr, CFT
))
8039 const FunctionType
*fn
= unwrapped
.get();
8040 CallingConv CCOld
= fn
->getCallConv();
8041 Attr
*CCAttr
= getCCTypeAttr(S
.Context
, attr
);
8044 // Error out on when there's already an attribute on the type
8045 // and the CCs don't match.
8046 if (S
.getCallingConvAttributedType(type
)) {
8047 S
.Diag(attr
.getLoc(), diag::err_attributes_are_not_compatible
)
8048 << FunctionType::getNameForCallConv(CC
)
8049 << FunctionType::getNameForCallConv(CCOld
)
8050 << attr
.isRegularKeywordAttribute();
8056 // Diagnose use of variadic functions with calling conventions that
8057 // don't support them (e.g. because they're callee-cleanup).
8058 // We delay warning about this on unprototyped function declarations
8059 // until after redeclaration checking, just in case we pick up a
8060 // prototype that way. And apparently we also "delay" warning about
8061 // unprototyped function types in general, despite not necessarily having
8062 // much ability to diagnose it later.
8063 if (!supportsVariadicCall(CC
)) {
8064 const FunctionProtoType
*FnP
= dyn_cast
<FunctionProtoType
>(fn
);
8065 if (FnP
&& FnP
->isVariadic()) {
8066 // stdcall and fastcall are ignored with a warning for GCC and MS
8068 if (CC
== CC_X86StdCall
|| CC
== CC_X86FastCall
)
8069 return S
.Diag(attr
.getLoc(), diag::warn_cconv_unsupported
)
8070 << FunctionType::getNameForCallConv(CC
)
8071 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction
;
8074 return S
.Diag(attr
.getLoc(), diag::err_cconv_varargs
)
8075 << FunctionType::getNameForCallConv(CC
);
8079 // Also diagnose fastcall with regparm.
8080 if (CC
== CC_X86FastCall
&& fn
->getHasRegParm()) {
8081 S
.Diag(attr
.getLoc(), diag::err_attributes_are_not_compatible
)
8082 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall
)
8083 << attr
.isRegularKeywordAttribute();
8088 // Modify the CC from the wrapped function type, wrap it all back, and then
8089 // wrap the whole thing in an AttributedType as written. The modified type
8090 // might have a different CC if we ignored the attribute.
8091 QualType Equivalent
;
8095 auto EI
= unwrapped
.get()->getExtInfo().withCallingConv(CC
);
8097 unwrapped
.wrap(S
, S
.Context
.adjustFunctionType(unwrapped
.get(), EI
));
8099 type
= state
.getAttributedType(CCAttr
, type
, Equivalent
);
8103 bool Sema::hasExplicitCallingConv(QualType T
) {
8104 const AttributedType
*AT
;
8106 // Stop if we'd be stripping off a typedef sugar node to reach the
8108 while ((AT
= T
->getAs
<AttributedType
>()) &&
8109 AT
->getAs
<TypedefType
>() == T
->getAs
<TypedefType
>()) {
8110 if (AT
->isCallingConv())
8112 T
= AT
->getModifiedType();
8117 void Sema::adjustMemberFunctionCC(QualType
&T
, bool HasThisPointer
,
8118 bool IsCtorOrDtor
, SourceLocation Loc
) {
8119 FunctionTypeUnwrapper
Unwrapped(*this, T
);
8120 const FunctionType
*FT
= Unwrapped
.get();
8121 bool IsVariadic
= (isa
<FunctionProtoType
>(FT
) &&
8122 cast
<FunctionProtoType
>(FT
)->isVariadic());
8123 CallingConv CurCC
= FT
->getCallConv();
8125 Context
.getDefaultCallingConvention(IsVariadic
, HasThisPointer
);
8130 // MS compiler ignores explicit calling convention attributes on structors. We
8131 // should do the same.
8132 if (Context
.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor
) {
8133 // Issue a warning on ignored calling convention -- except of __stdcall.
8134 // Again, this is what MS compiler does.
8135 if (CurCC
!= CC_X86StdCall
)
8136 Diag(Loc
, diag::warn_cconv_unsupported
)
8137 << FunctionType::getNameForCallConv(CurCC
)
8138 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor
;
8139 // Default adjustment.
8141 // Only adjust types with the default convention. For example, on Windows
8142 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8143 // __thiscall type to __cdecl for static methods.
8144 CallingConv DefaultCC
=
8145 Context
.getDefaultCallingConvention(IsVariadic
, !HasThisPointer
);
8147 if (CurCC
!= DefaultCC
)
8150 if (hasExplicitCallingConv(T
))
8154 FT
= Context
.adjustFunctionType(FT
, FT
->getExtInfo().withCallingConv(ToCC
));
8155 QualType Wrapped
= Unwrapped
.wrap(*this, FT
);
8156 T
= Context
.getAdjustedType(T
, Wrapped
);
8159 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
8160 /// and float scalars, although arrays, pointers, and function return values are
8161 /// allowed in conjunction with this construct. Aggregates with this attribute
8162 /// are invalid, even if they are of the same size as a corresponding scalar.
8163 /// The raw attribute should contain precisely 1 argument, the vector size for
8164 /// the variable, measured in bytes. If curType and rawAttr are well formed,
8165 /// this routine will return a new vector type.
8166 static void HandleVectorSizeAttr(QualType
&CurType
, const ParsedAttr
&Attr
,
8168 // Check the attribute arguments.
8169 if (Attr
.getNumArgs() != 1) {
8170 S
.Diag(Attr
.getLoc(), diag::err_attribute_wrong_number_arguments
) << Attr
8176 Expr
*SizeExpr
= Attr
.getArgAsExpr(0);
8177 QualType T
= S
.BuildVectorType(CurType
, SizeExpr
, Attr
.getLoc());
8184 /// Process the OpenCL-like ext_vector_type attribute when it occurs on
8186 static void HandleExtVectorTypeAttr(QualType
&CurType
, const ParsedAttr
&Attr
,
8188 // check the attribute arguments.
8189 if (Attr
.getNumArgs() != 1) {
8190 S
.Diag(Attr
.getLoc(), diag::err_attribute_wrong_number_arguments
) << Attr
8195 Expr
*SizeExpr
= Attr
.getArgAsExpr(0);
8196 QualType T
= S
.BuildExtVectorType(CurType
, SizeExpr
, Attr
.getLoc());
8201 static bool isPermittedNeonBaseType(QualType
&Ty
, VectorKind VecKind
, Sema
&S
) {
8202 const BuiltinType
*BTy
= Ty
->getAs
<BuiltinType
>();
8206 llvm::Triple Triple
= S
.Context
.getTargetInfo().getTriple();
8208 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8210 bool IsPolyUnsigned
= Triple
.getArch() == llvm::Triple::aarch64
||
8211 Triple
.getArch() == llvm::Triple::aarch64_32
||
8212 Triple
.getArch() == llvm::Triple::aarch64_be
;
8213 if (VecKind
== VectorKind::NeonPoly
) {
8214 if (IsPolyUnsigned
) {
8215 // AArch64 polynomial vectors are unsigned.
8216 return BTy
->getKind() == BuiltinType::UChar
||
8217 BTy
->getKind() == BuiltinType::UShort
||
8218 BTy
->getKind() == BuiltinType::ULong
||
8219 BTy
->getKind() == BuiltinType::ULongLong
;
8221 // AArch32 polynomial vectors are signed.
8222 return BTy
->getKind() == BuiltinType::SChar
||
8223 BTy
->getKind() == BuiltinType::Short
||
8224 BTy
->getKind() == BuiltinType::LongLong
;
8228 // Non-polynomial vector types: the usual suspects are allowed, as well as
8229 // float64_t on AArch64.
8230 if ((Triple
.isArch64Bit() || Triple
.getArch() == llvm::Triple::aarch64_32
) &&
8231 BTy
->getKind() == BuiltinType::Double
)
8234 return BTy
->getKind() == BuiltinType::SChar
||
8235 BTy
->getKind() == BuiltinType::UChar
||
8236 BTy
->getKind() == BuiltinType::Short
||
8237 BTy
->getKind() == BuiltinType::UShort
||
8238 BTy
->getKind() == BuiltinType::Int
||
8239 BTy
->getKind() == BuiltinType::UInt
||
8240 BTy
->getKind() == BuiltinType::Long
||
8241 BTy
->getKind() == BuiltinType::ULong
||
8242 BTy
->getKind() == BuiltinType::LongLong
||
8243 BTy
->getKind() == BuiltinType::ULongLong
||
8244 BTy
->getKind() == BuiltinType::Float
||
8245 BTy
->getKind() == BuiltinType::Half
||
8246 BTy
->getKind() == BuiltinType::BFloat16
;
8249 static bool verifyValidIntegerConstantExpr(Sema
&S
, const ParsedAttr
&Attr
,
8250 llvm::APSInt
&Result
) {
8251 const auto *AttrExpr
= Attr
.getArgAsExpr(0);
8252 if (!AttrExpr
->isTypeDependent()) {
8253 if (std::optional
<llvm::APSInt
> Res
=
8254 AttrExpr
->getIntegerConstantExpr(S
.Context
)) {
8259 S
.Diag(Attr
.getLoc(), diag::err_attribute_argument_type
)
8260 << Attr
<< AANT_ArgumentIntegerConstant
<< AttrExpr
->getSourceRange();
8265 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8266 /// "neon_polyvector_type" attributes are used to create vector types that
8267 /// are mangled according to ARM's ABI. Otherwise, these types are identical
8268 /// to those created with the "vector_size" attribute. Unlike "vector_size"
8269 /// the argument to these Neon attributes is the number of vector elements,
8270 /// not the vector size in bytes. The vector width and element type must
8271 /// match one of the standard Neon vector types.
8272 static void HandleNeonVectorTypeAttr(QualType
&CurType
, const ParsedAttr
&Attr
,
8273 Sema
&S
, VectorKind VecKind
) {
8274 bool IsTargetCUDAAndHostARM
= false;
8275 if (S
.getLangOpts().CUDAIsDevice
) {
8276 const TargetInfo
*AuxTI
= S
.getASTContext().getAuxTargetInfo();
8277 IsTargetCUDAAndHostARM
=
8278 AuxTI
&& (AuxTI
->getTriple().isAArch64() || AuxTI
->getTriple().isARM());
8281 // Target must have NEON (or MVE, whose vectors are similar enough
8282 // not to need a separate attribute)
8283 if (!S
.Context
.getTargetInfo().hasFeature("mve") &&
8284 VecKind
== VectorKind::Neon
&&
8285 S
.Context
.getTargetInfo().getTriple().isArmMClass()) {
8286 S
.Diag(Attr
.getLoc(), diag::err_attribute_unsupported_m_profile
)
8291 if (!S
.Context
.getTargetInfo().hasFeature("mve") &&
8292 VecKind
== VectorKind::NeonPoly
&&
8293 S
.Context
.getTargetInfo().getTriple().isArmMClass()) {
8294 S
.Diag(Attr
.getLoc(), diag::err_attribute_unsupported_m_profile
)
8300 // Check the attribute arguments.
8301 if (Attr
.getNumArgs() != 1) {
8302 S
.Diag(Attr
.getLoc(), diag::err_attribute_wrong_number_arguments
)
8307 // The number of elements must be an ICE.
8308 llvm::APSInt
numEltsInt(32);
8309 if (!verifyValidIntegerConstantExpr(S
, Attr
, numEltsInt
))
8312 // Only certain element types are supported for Neon vectors.
8313 if (!isPermittedNeonBaseType(CurType
, VecKind
, S
) &&
8314 !IsTargetCUDAAndHostARM
) {
8315 S
.Diag(Attr
.getLoc(), diag::err_attribute_invalid_vector_type
) << CurType
;
8320 // The total size of the vector must be 64 or 128 bits.
8321 unsigned typeSize
= static_cast<unsigned>(S
.Context
.getTypeSize(CurType
));
8322 unsigned numElts
= static_cast<unsigned>(numEltsInt
.getZExtValue());
8323 unsigned vecSize
= typeSize
* numElts
;
8324 if (vecSize
!= 64 && vecSize
!= 128) {
8325 S
.Diag(Attr
.getLoc(), diag::err_attribute_bad_neon_vector_size
) << CurType
;
8330 CurType
= S
.Context
.getVectorType(CurType
, numElts
, VecKind
);
8333 /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8334 /// used to create fixed-length versions of sizeless SVE types defined by
8335 /// the ACLE, such as svint32_t and svbool_t.
8336 static void HandleArmSveVectorBitsTypeAttr(QualType
&CurType
, ParsedAttr
&Attr
,
8338 // Target must have SVE.
8339 if (!S
.Context
.getTargetInfo().hasFeature("sve")) {
8340 S
.Diag(Attr
.getLoc(), diag::err_attribute_unsupported
) << Attr
<< "'sve'";
8345 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8346 // if <bits>+ syntax is used.
8347 if (!S
.getLangOpts().VScaleMin
||
8348 S
.getLangOpts().VScaleMin
!= S
.getLangOpts().VScaleMax
) {
8349 S
.Diag(Attr
.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported
)
8355 // Check the attribute arguments.
8356 if (Attr
.getNumArgs() != 1) {
8357 S
.Diag(Attr
.getLoc(), diag::err_attribute_wrong_number_arguments
)
8363 // The vector size must be an integer constant expression.
8364 llvm::APSInt
SveVectorSizeInBits(32);
8365 if (!verifyValidIntegerConstantExpr(S
, Attr
, SveVectorSizeInBits
))
8368 unsigned VecSize
= static_cast<unsigned>(SveVectorSizeInBits
.getZExtValue());
8370 // The attribute vector size must match -msve-vector-bits.
8371 if (VecSize
!= S
.getLangOpts().VScaleMin
* 128) {
8372 S
.Diag(Attr
.getLoc(), diag::err_attribute_bad_sve_vector_size
)
8373 << VecSize
<< S
.getLangOpts().VScaleMin
* 128;
8378 // Attribute can only be attached to a single SVE vector or predicate type.
8379 if (!CurType
->isSveVLSBuiltinType()) {
8380 S
.Diag(Attr
.getLoc(), diag::err_attribute_invalid_sve_type
)
8386 const auto *BT
= CurType
->castAs
<BuiltinType
>();
8388 QualType EltType
= CurType
->getSveEltType(S
.Context
);
8389 unsigned TypeSize
= S
.Context
.getTypeSize(EltType
);
8390 VectorKind VecKind
= VectorKind::SveFixedLengthData
;
8391 if (BT
->getKind() == BuiltinType::SveBool
) {
8392 // Predicates are represented as i8.
8393 VecSize
/= S
.Context
.getCharWidth() * S
.Context
.getCharWidth();
8394 VecKind
= VectorKind::SveFixedLengthPredicate
;
8396 VecSize
/= TypeSize
;
8397 CurType
= S
.Context
.getVectorType(EltType
, VecSize
, VecKind
);
8400 static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState
&State
,
8403 const VectorType
*VT
= dyn_cast
<VectorType
>(CurType
);
8404 if (!VT
|| VT
->getVectorKind() != VectorKind::Neon
) {
8405 State
.getSema().Diag(Attr
.getLoc(),
8406 diag::err_attribute_arm_mve_polymorphism
);
8412 State
.getAttributedType(createSimpleAttr
<ArmMveStrictPolymorphismAttr
>(
8413 State
.getSema().Context
, Attr
),
8417 /// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8418 /// used to create fixed-length versions of sizeless RVV types such as
8420 static void HandleRISCVRVVVectorBitsTypeAttr(QualType
&CurType
,
8421 ParsedAttr
&Attr
, Sema
&S
) {
8422 // Target must have vector extension.
8423 if (!S
.Context
.getTargetInfo().hasFeature("zve32x")) {
8424 S
.Diag(Attr
.getLoc(), diag::err_attribute_unsupported
)
8425 << Attr
<< "'zve32x'";
8430 auto VScale
= S
.Context
.getTargetInfo().getVScaleRange(S
.getLangOpts());
8431 if (!VScale
|| !VScale
->first
|| VScale
->first
!= VScale
->second
) {
8432 S
.Diag(Attr
.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported
)
8438 // Check the attribute arguments.
8439 if (Attr
.getNumArgs() != 1) {
8440 S
.Diag(Attr
.getLoc(), diag::err_attribute_wrong_number_arguments
)
8446 // The vector size must be an integer constant expression.
8447 llvm::APSInt
RVVVectorSizeInBits(32);
8448 if (!verifyValidIntegerConstantExpr(S
, Attr
, RVVVectorSizeInBits
))
8451 // Attribute can only be attached to a single RVV vector type.
8452 if (!CurType
->isRVVVLSBuiltinType()) {
8453 S
.Diag(Attr
.getLoc(), diag::err_attribute_invalid_rvv_type
)
8459 unsigned VecSize
= static_cast<unsigned>(RVVVectorSizeInBits
.getZExtValue());
8461 ASTContext::BuiltinVectorTypeInfo Info
=
8462 S
.Context
.getBuiltinVectorTypeInfo(CurType
->castAs
<BuiltinType
>());
8463 unsigned MinElts
= Info
.EC
.getKnownMinValue();
8465 VectorKind VecKind
= VectorKind::RVVFixedLengthData
;
8466 unsigned ExpectedSize
= VScale
->first
* MinElts
;
8467 QualType EltType
= CurType
->getRVVEltType(S
.Context
);
8468 unsigned EltSize
= S
.Context
.getTypeSize(EltType
);
8470 if (Info
.ElementType
== S
.Context
.BoolTy
) {
8471 NumElts
= VecSize
/ S
.Context
.getCharWidth();
8476 VecKind
= VectorKind::RVVFixedLengthMask_1
;
8479 VecKind
= VectorKind::RVVFixedLengthMask_2
;
8482 VecKind
= VectorKind::RVVFixedLengthMask_4
;
8486 VecKind
= VectorKind::RVVFixedLengthMask
;
8488 ExpectedSize
*= EltSize
;
8489 NumElts
= VecSize
/ EltSize
;
8492 // The attribute vector size must match -mrvv-vector-bits.
8493 if (VecSize
!= ExpectedSize
) {
8494 S
.Diag(Attr
.getLoc(), diag::err_attribute_bad_rvv_vector_size
)
8495 << VecSize
<< ExpectedSize
;
8500 CurType
= S
.Context
.getVectorType(EltType
, NumElts
, VecKind
);
8503 /// Handle OpenCL Access Qualifier Attribute.
8504 static void HandleOpenCLAccessAttr(QualType
&CurType
, const ParsedAttr
&Attr
,
8506 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8507 if (!(CurType
->isImageType() || CurType
->isPipeType())) {
8508 S
.Diag(Attr
.getLoc(), diag::err_opencl_invalid_access_qualifier
);
8513 if (const TypedefType
* TypedefTy
= CurType
->getAs
<TypedefType
>()) {
8514 QualType BaseTy
= TypedefTy
->desugar();
8516 std::string PrevAccessQual
;
8517 if (BaseTy
->isPipeType()) {
8518 if (TypedefTy
->getDecl()->hasAttr
<OpenCLAccessAttr
>()) {
8519 OpenCLAccessAttr
*Attr
=
8520 TypedefTy
->getDecl()->getAttr
<OpenCLAccessAttr
>();
8521 PrevAccessQual
= Attr
->getSpelling();
8523 PrevAccessQual
= "read_only";
8525 } else if (const BuiltinType
* ImgType
= BaseTy
->getAs
<BuiltinType
>()) {
8527 switch (ImgType
->getKind()) {
8528 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8529 case BuiltinType::Id: \
8530 PrevAccessQual = #Access; \
8532 #include "clang/Basic/OpenCLImageTypes.def"
8534 llvm_unreachable("Unable to find corresponding image type.");
8537 llvm_unreachable("unexpected type");
8539 StringRef AttrName
= Attr
.getAttrName()->getName();
8540 if (PrevAccessQual
== AttrName
.ltrim("_")) {
8541 // Duplicated qualifiers
8542 S
.Diag(Attr
.getLoc(), diag::warn_duplicate_declspec
)
8543 << AttrName
<< Attr
.getRange();
8545 // Contradicting qualifiers
8546 S
.Diag(Attr
.getLoc(), diag::err_opencl_multiple_access_qualifiers
);
8549 S
.Diag(TypedefTy
->getDecl()->getBeginLoc(),
8550 diag::note_opencl_typedef_access_qualifier
) << PrevAccessQual
;
8551 } else if (CurType
->isPipeType()) {
8552 if (Attr
.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only
) {
8553 QualType ElemType
= CurType
->castAs
<PipeType
>()->getElementType();
8554 CurType
= S
.Context
.getWritePipeType(ElemType
);
8559 /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8560 static void HandleMatrixTypeAttr(QualType
&CurType
, const ParsedAttr
&Attr
,
8562 if (!S
.getLangOpts().MatrixTypes
) {
8563 S
.Diag(Attr
.getLoc(), diag::err_builtin_matrix_disabled
);
8567 if (Attr
.getNumArgs() != 2) {
8568 S
.Diag(Attr
.getLoc(), diag::err_attribute_wrong_number_arguments
)
8573 Expr
*RowsExpr
= Attr
.getArgAsExpr(0);
8574 Expr
*ColsExpr
= Attr
.getArgAsExpr(1);
8575 QualType T
= S
.BuildMatrixType(CurType
, RowsExpr
, ColsExpr
, Attr
.getLoc());
8580 static void HandleAnnotateTypeAttr(TypeProcessingState
&State
,
8581 QualType
&CurType
, const ParsedAttr
&PA
) {
8582 Sema
&S
= State
.getSema();
8584 if (PA
.getNumArgs() < 1) {
8585 S
.Diag(PA
.getLoc(), diag::err_attribute_too_few_arguments
) << PA
<< 1;
8589 // Make sure that there is a string literal as the annotation's first
8592 if (!S
.checkStringLiteralArgumentAttr(PA
, 0, Str
))
8595 llvm::SmallVector
<Expr
*, 4> Args
;
8596 Args
.reserve(PA
.getNumArgs() - 1);
8597 for (unsigned Idx
= 1; Idx
< PA
.getNumArgs(); Idx
++) {
8598 assert(!PA
.isArgIdent(Idx
));
8599 Args
.push_back(PA
.getArgAsExpr(Idx
));
8601 if (!S
.ConstantFoldAttrArgs(PA
, Args
))
8603 auto *AnnotateTypeAttr
=
8604 AnnotateTypeAttr::Create(S
.Context
, Str
, Args
.data(), Args
.size(), PA
);
8605 CurType
= State
.getAttributedType(AnnotateTypeAttr
, CurType
, CurType
);
8608 static void HandleLifetimeBoundAttr(TypeProcessingState
&State
,
8611 if (State
.getDeclarator().isDeclarationOfFunction()) {
8612 CurType
= State
.getAttributedType(
8613 createSimpleAttr
<LifetimeBoundAttr
>(State
.getSema().Context
, Attr
),
8618 static void HandleLifetimeCaptureByAttr(TypeProcessingState
&State
,
8619 QualType
&CurType
, ParsedAttr
&PA
) {
8620 if (State
.getDeclarator().isDeclarationOfFunction()) {
8621 auto *Attr
= State
.getSema().ParseLifetimeCaptureByAttr(PA
, "this");
8623 CurType
= State
.getAttributedType(Attr
, CurType
, CurType
);
8627 static void HandleHLSLParamModifierAttr(TypeProcessingState
&State
,
8629 const ParsedAttr
&Attr
, Sema
&S
) {
8630 // Don't apply this attribute to template dependent types. It is applied on
8631 // substitution during template instantiation. Also skip parsing this if we've
8632 // already modified the type based on an earlier attribute.
8633 if (CurType
->isDependentType() || State
.didParseHLSLParamMod())
8635 if (Attr
.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout
||
8636 Attr
.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out
) {
8637 CurType
= S
.HLSL().getInoutParameterType(CurType
);
8638 State
.setParsedHLSLParamMod(true);
8642 static void processTypeAttrs(TypeProcessingState
&state
, QualType
&type
,
8643 TypeAttrLocation TAL
,
8644 const ParsedAttributesView
&attrs
,
8645 CUDAFunctionTarget CFT
) {
8647 state
.setParsedNoDeref(false);
8651 // Scan through and apply attributes to this type where it makes sense. Some
8652 // attributes (such as __address_space__, __vector_size__, etc) apply to the
8653 // type, but others can be present in the type specifiers even though they
8654 // apply to the decl. Here we apply type attributes and ignore the rest.
8656 // This loop modifies the list pretty frequently, but we still need to make
8657 // sure we visit every element once. Copy the attributes list, and iterate
8659 ParsedAttributesView AttrsCopy
{attrs
};
8660 for (ParsedAttr
&attr
: AttrsCopy
) {
8662 // Skip attributes that were marked to be invalid.
8663 if (attr
.isInvalid())
8666 if (attr
.isStandardAttributeSyntax() || attr
.isRegularKeywordAttribute()) {
8667 // [[gnu::...]] attributes are treated as declaration attributes, so may
8668 // not appertain to a DeclaratorChunk. If we handle them as type
8669 // attributes, accept them in that position and diagnose the GCC
8671 if (attr
.isGNUScope()) {
8672 assert(attr
.isStandardAttributeSyntax());
8673 bool IsTypeAttr
= attr
.isTypeAttr();
8674 if (TAL
== TAL_DeclChunk
) {
8675 state
.getSema().Diag(attr
.getLoc(),
8677 ? diag::warn_gcc_ignores_type_attr
8678 : diag::warn_cxx11_gnu_attribute_on_type
)
8683 } else if (TAL
!= TAL_DeclSpec
&& TAL
!= TAL_DeclChunk
&&
8684 !attr
.isTypeAttr()) {
8685 // Otherwise, only consider type processing for a C++11 attribute if
8686 // - it has actually been applied to a type (decl-specifier-seq or
8687 // declarator chunk), or
8688 // - it is a type attribute, irrespective of where it was applied (so
8689 // that we can support the legacy behavior of some type attributes
8690 // that can be applied to the declaration name).
8695 // If this is an attribute we can handle, do so now,
8696 // otherwise, add it to the FnAttrs list for rechaining.
8697 switch (attr
.getKind()) {
8699 // A [[]] attribute on a declarator chunk must appertain to a type.
8700 if ((attr
.isStandardAttributeSyntax() ||
8701 attr
.isRegularKeywordAttribute()) &&
8702 TAL
== TAL_DeclChunk
) {
8703 state
.getSema().Diag(attr
.getLoc(), diag::err_attribute_not_type_attr
)
8704 << attr
<< attr
.isRegularKeywordAttribute();
8705 attr
.setUsedAsTypeAttr();
8709 case ParsedAttr::UnknownAttribute
:
8710 if (attr
.isStandardAttributeSyntax()) {
8711 state
.getSema().Diag(attr
.getLoc(),
8712 diag::warn_unknown_attribute_ignored
)
8713 << attr
<< attr
.getRange();
8714 // Mark the attribute as invalid so we don't emit the same diagnostic
8720 case ParsedAttr::IgnoredAttribute
:
8723 case ParsedAttr::AT_BTFTypeTag
:
8724 HandleBTFTypeTagAttribute(type
, attr
, state
);
8725 attr
.setUsedAsTypeAttr();
8728 case ParsedAttr::AT_MayAlias
:
8729 // FIXME: This attribute needs to actually be handled, but if we ignore
8730 // it it breaks large amounts of Linux software.
8731 attr
.setUsedAsTypeAttr();
8733 case ParsedAttr::AT_OpenCLPrivateAddressSpace
:
8734 case ParsedAttr::AT_OpenCLGlobalAddressSpace
:
8735 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace
:
8736 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace
:
8737 case ParsedAttr::AT_OpenCLLocalAddressSpace
:
8738 case ParsedAttr::AT_OpenCLConstantAddressSpace
:
8739 case ParsedAttr::AT_OpenCLGenericAddressSpace
:
8740 case ParsedAttr::AT_HLSLGroupSharedAddressSpace
:
8741 case ParsedAttr::AT_AddressSpace
:
8742 HandleAddressSpaceTypeAttribute(type
, attr
, state
);
8743 attr
.setUsedAsTypeAttr();
8745 OBJC_POINTER_TYPE_ATTRS_CASELIST
:
8746 if (!handleObjCPointerTypeAttr(state
, attr
, type
))
8747 distributeObjCPointerTypeAttr(state
, attr
, type
);
8748 attr
.setUsedAsTypeAttr();
8750 case ParsedAttr::AT_VectorSize
:
8751 HandleVectorSizeAttr(type
, attr
, state
.getSema());
8752 attr
.setUsedAsTypeAttr();
8754 case ParsedAttr::AT_ExtVectorType
:
8755 HandleExtVectorTypeAttr(type
, attr
, state
.getSema());
8756 attr
.setUsedAsTypeAttr();
8758 case ParsedAttr::AT_NeonVectorType
:
8759 HandleNeonVectorTypeAttr(type
, attr
, state
.getSema(), VectorKind::Neon
);
8760 attr
.setUsedAsTypeAttr();
8762 case ParsedAttr::AT_NeonPolyVectorType
:
8763 HandleNeonVectorTypeAttr(type
, attr
, state
.getSema(),
8764 VectorKind::NeonPoly
);
8765 attr
.setUsedAsTypeAttr();
8767 case ParsedAttr::AT_ArmSveVectorBits
:
8768 HandleArmSveVectorBitsTypeAttr(type
, attr
, state
.getSema());
8769 attr
.setUsedAsTypeAttr();
8771 case ParsedAttr::AT_ArmMveStrictPolymorphism
: {
8772 HandleArmMveStrictPolymorphismAttr(state
, type
, attr
);
8773 attr
.setUsedAsTypeAttr();
8776 case ParsedAttr::AT_RISCVRVVVectorBits
:
8777 HandleRISCVRVVVectorBitsTypeAttr(type
, attr
, state
.getSema());
8778 attr
.setUsedAsTypeAttr();
8780 case ParsedAttr::AT_OpenCLAccess
:
8781 HandleOpenCLAccessAttr(type
, attr
, state
.getSema());
8782 attr
.setUsedAsTypeAttr();
8784 case ParsedAttr::AT_LifetimeBound
:
8785 if (TAL
== TAL_DeclChunk
)
8786 HandleLifetimeBoundAttr(state
, type
, attr
);
8788 case ParsedAttr::AT_LifetimeCaptureBy
:
8789 if (TAL
== TAL_DeclChunk
)
8790 HandleLifetimeCaptureByAttr(state
, type
, attr
);
8793 case ParsedAttr::AT_NoDeref
: {
8794 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
8795 // See https://github.com/llvm/llvm-project/issues/55790 for details.
8796 // For the time being, we simply emit a warning that the attribute is
8798 if (attr
.isStandardAttributeSyntax()) {
8799 state
.getSema().Diag(attr
.getLoc(), diag::warn_attribute_ignored
)
8803 ASTContext
&Ctx
= state
.getSema().Context
;
8804 type
= state
.getAttributedType(createSimpleAttr
<NoDerefAttr
>(Ctx
, attr
),
8806 attr
.setUsedAsTypeAttr();
8807 state
.setParsedNoDeref(true);
8811 case ParsedAttr::AT_MatrixType
:
8812 HandleMatrixTypeAttr(type
, attr
, state
.getSema());
8813 attr
.setUsedAsTypeAttr();
8816 case ParsedAttr::AT_WebAssemblyFuncref
: {
8817 if (!HandleWebAssemblyFuncrefAttr(state
, type
, attr
))
8818 attr
.setUsedAsTypeAttr();
8822 case ParsedAttr::AT_HLSLParamModifier
: {
8823 HandleHLSLParamModifierAttr(state
, type
, attr
, state
.getSema());
8824 attr
.setUsedAsTypeAttr();
8828 case ParsedAttr::AT_SwiftAttr
: {
8829 HandleSwiftAttr(state
, TAL
, type
, attr
);
8833 MS_TYPE_ATTRS_CASELIST
:
8834 if (!handleMSPointerTypeQualifierAttr(state
, attr
, type
))
8835 attr
.setUsedAsTypeAttr();
8839 NULLABILITY_TYPE_ATTRS_CASELIST
:
8840 // Either add nullability here or try to distribute it. We
8841 // don't want to distribute the nullability specifier past any
8842 // dependent type, because that complicates the user model.
8843 if (type
->canHaveNullability() || type
->isDependentType() ||
8844 type
->isArrayType() ||
8845 !distributeNullabilityTypeAttr(state
, type
, attr
)) {
8847 if (TAL
== TAL_DeclChunk
)
8848 endIndex
= state
.getCurrentChunkIndex();
8850 endIndex
= state
.getDeclarator().getNumTypeObjects();
8851 bool allowOnArrayType
=
8852 state
.getDeclarator().isPrototypeContext() &&
8853 !hasOuterPointerLikeChunk(state
.getDeclarator(), endIndex
);
8854 if (CheckNullabilityTypeSpecifier(state
, type
, attr
,
8855 allowOnArrayType
)) {
8859 attr
.setUsedAsTypeAttr();
8863 case ParsedAttr::AT_ObjCKindOf
:
8864 // '__kindof' must be part of the decl-specifiers.
8871 state
.getSema().Diag(attr
.getLoc(),
8872 diag::err_objc_kindof_wrong_position
)
8873 << FixItHint::CreateRemoval(attr
.getLoc())
8874 << FixItHint::CreateInsertion(
8875 state
.getDeclarator().getDeclSpec().getBeginLoc(),
8880 // Apply it regardless.
8881 if (checkObjCKindOfType(state
, type
, attr
))
8885 case ParsedAttr::AT_NoThrow
:
8886 // Exception Specifications aren't generally supported in C mode throughout
8887 // clang, so revert to attribute-based handling for C.
8888 if (!state
.getSema().getLangOpts().CPlusPlus
)
8891 FUNCTION_TYPE_ATTRS_CASELIST
:
8892 attr
.setUsedAsTypeAttr();
8894 // Attributes with standard syntax have strict rules for what they
8895 // appertain to and hence should not use the "distribution" logic below.
8896 if (attr
.isStandardAttributeSyntax() ||
8897 attr
.isRegularKeywordAttribute()) {
8898 if (!handleFunctionTypeAttr(state
, attr
, type
, CFT
)) {
8899 diagnoseBadTypeAttribute(state
.getSema(), attr
, type
);
8905 // Never process function type attributes as part of the
8906 // declaration-specifiers.
8907 if (TAL
== TAL_DeclSpec
)
8908 distributeFunctionTypeAttrFromDeclSpec(state
, attr
, type
, CFT
);
8910 // Otherwise, handle the possible delays.
8911 else if (!handleFunctionTypeAttr(state
, attr
, type
, CFT
))
8912 distributeFunctionTypeAttr(state
, attr
, type
);
8914 case ParsedAttr::AT_AcquireHandle
: {
8915 if (!type
->isFunctionType())
8918 if (attr
.getNumArgs() != 1) {
8919 state
.getSema().Diag(attr
.getLoc(),
8920 diag::err_attribute_wrong_number_arguments
)
8926 StringRef HandleType
;
8927 if (!state
.getSema().checkStringLiteralArgumentAttr(attr
, 0, HandleType
))
8929 type
= state
.getAttributedType(
8930 AcquireHandleAttr::Create(state
.getSema().Context
, HandleType
, attr
),
8932 attr
.setUsedAsTypeAttr();
8935 case ParsedAttr::AT_AnnotateType
: {
8936 HandleAnnotateTypeAttr(state
, type
, attr
);
8937 attr
.setUsedAsTypeAttr();
8940 case ParsedAttr::AT_HLSLResourceClass
:
8941 case ParsedAttr::AT_HLSLROV
:
8942 case ParsedAttr::AT_HLSLRawBuffer
:
8943 case ParsedAttr::AT_HLSLContainedType
: {
8944 // Only collect HLSL resource type attributes that are in
8945 // decl-specifier-seq; do not collect attributes on declarations or those
8946 // that get to slide after declaration name.
8947 if (TAL
== TAL_DeclSpec
&&
8948 state
.getSema().HLSL().handleResourceTypeAttr(type
, attr
))
8949 attr
.setUsedAsTypeAttr();
8954 // Handle attributes that are defined in a macro. We do not want this to be
8955 // applied to ObjC builtin attributes.
8956 if (isa
<AttributedType
>(type
) && attr
.hasMacroIdentifier() &&
8957 !type
.getQualifiers().hasObjCLifetime() &&
8958 !type
.getQualifiers().hasObjCGCAttr() &&
8959 attr
.getKind() != ParsedAttr::AT_ObjCGC
&&
8960 attr
.getKind() != ParsedAttr::AT_ObjCOwnership
) {
8961 const IdentifierInfo
*MacroII
= attr
.getMacroIdentifier();
8962 type
= state
.getSema().Context
.getMacroQualifiedType(type
, MacroII
);
8963 state
.setExpansionLocForMacroQualifiedType(
8964 cast
<MacroQualifiedType
>(type
.getTypePtr()),
8965 attr
.getMacroExpansionLoc());
8970 void Sema::completeExprArrayBound(Expr
*E
) {
8971 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParens())) {
8972 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(DRE
->getDecl())) {
8973 if (isTemplateInstantiation(Var
->getTemplateSpecializationKind())) {
8974 auto *Def
= Var
->getDefinition();
8976 SourceLocation PointOfInstantiation
= E
->getExprLoc();
8977 runWithSufficientStackSpace(PointOfInstantiation
, [&] {
8978 InstantiateVariableDefinition(PointOfInstantiation
, Var
);
8980 Def
= Var
->getDefinition();
8982 // If we don't already have a point of instantiation, and we managed
8983 // to instantiate a definition, this is the point of instantiation.
8984 // Otherwise, we don't request an end-of-TU instantiation, so this is
8985 // not a point of instantiation.
8986 // FIXME: Is this really the right behavior?
8987 if (Var
->getPointOfInstantiation().isInvalid() && Def
) {
8988 assert(Var
->getTemplateSpecializationKind() ==
8989 TSK_ImplicitInstantiation
&&
8990 "explicit instantiation with no point of instantiation");
8991 Var
->setTemplateSpecializationKind(
8992 Var
->getTemplateSpecializationKind(), PointOfInstantiation
);
8996 // Update the type to the definition's type both here and within the
9000 QualType T
= Def
->getType();
9002 // FIXME: Update the type on all intervening expressions.
9006 // We still go on to try to complete the type independently, as it
9007 // may also require instantiations or diagnostics if it remains
9012 if (const auto CastE
= dyn_cast
<ExplicitCastExpr
>(E
)) {
9013 QualType DestType
= CastE
->getTypeAsWritten();
9014 if (const auto *IAT
= Context
.getAsIncompleteArrayType(DestType
)) {
9015 // C++20 [expr.static.cast]p.4: ... If T is array of unknown bound,
9016 // this direct-initialization defines the type of the expression
9018 QualType ResultType
= Context
.getConstantArrayType(
9019 IAT
->getElementType(),
9020 llvm::APInt(Context
.getTypeSize(Context
.getSizeType()), 1),
9021 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal
,
9022 /*IndexTypeQuals=*/0);
9023 E
->setType(ResultType
);
9028 QualType
Sema::getCompletedType(Expr
*E
) {
9029 // Incomplete array types may be completed by the initializer attached to
9030 // their definitions. For static data members of class templates and for
9031 // variable templates, we need to instantiate the definition to get this
9032 // initializer and complete the type.
9033 if (E
->getType()->isIncompleteArrayType())
9034 completeExprArrayBound(E
);
9036 // FIXME: Are there other cases which require instantiating something other
9037 // than the type to complete the type of an expression?
9039 return E
->getType();
9042 bool Sema::RequireCompleteExprType(Expr
*E
, CompleteTypeKind Kind
,
9043 TypeDiagnoser
&Diagnoser
) {
9044 return RequireCompleteType(E
->getExprLoc(), getCompletedType(E
), Kind
,
9048 bool Sema::RequireCompleteExprType(Expr
*E
, unsigned DiagID
) {
9049 BoundTypeDiagnoser
<> Diagnoser(DiagID
);
9050 return RequireCompleteExprType(E
, CompleteTypeKind::Default
, Diagnoser
);
9053 bool Sema::RequireCompleteType(SourceLocation Loc
, QualType T
,
9054 CompleteTypeKind Kind
,
9055 TypeDiagnoser
&Diagnoser
) {
9056 if (RequireCompleteTypeImpl(Loc
, T
, Kind
, &Diagnoser
))
9058 if (const TagType
*Tag
= T
->getAs
<TagType
>()) {
9059 if (!Tag
->getDecl()->isCompleteDefinitionRequired()) {
9060 Tag
->getDecl()->setCompleteDefinitionRequired();
9061 Consumer
.HandleTagDeclRequiredDefinition(Tag
->getDecl());
9067 bool Sema::hasStructuralCompatLayout(Decl
*D
, Decl
*Suggested
) {
9068 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls
;
9072 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9073 // and isolate from other C++ specific checks.
9074 StructuralEquivalenceContext
Ctx(
9075 D
->getASTContext(), Suggested
->getASTContext(), NonEquivalentDecls
,
9076 StructuralEquivalenceKind::Default
,
9077 false /*StrictTypeSpelling*/, true /*Complain*/,
9078 true /*ErrorOnTagTypeMismatch*/);
9079 return Ctx
.IsEquivalent(D
, Suggested
);
9082 bool Sema::hasAcceptableDefinition(NamedDecl
*D
, NamedDecl
**Suggested
,
9083 AcceptableKind Kind
, bool OnlyNeedComplete
) {
9084 // Easy case: if we don't have modules, all declarations are visible.
9085 if (!getLangOpts().Modules
&& !getLangOpts().ModulesLocalVisibility
)
9088 // If this definition was instantiated from a template, map back to the
9089 // pattern from which it was instantiated.
9090 if (isa
<TagDecl
>(D
) && cast
<TagDecl
>(D
)->isBeingDefined()) {
9091 // We're in the middle of defining it; this definition should be treated
9094 } else if (auto *RD
= dyn_cast
<CXXRecordDecl
>(D
)) {
9095 if (auto *Pattern
= RD
->getTemplateInstantiationPattern())
9097 D
= RD
->getDefinition();
9098 } else if (auto *ED
= dyn_cast
<EnumDecl
>(D
)) {
9099 if (auto *Pattern
= ED
->getTemplateInstantiationPattern())
9101 if (OnlyNeedComplete
&& (ED
->isFixed() || getLangOpts().MSVCCompat
)) {
9102 // If the enum has a fixed underlying type, it may have been forward
9103 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9104 // the enum and assign it the underlying type of `int`. Since we're only
9105 // looking for a complete type (not a definition), any visible declaration
9107 *Suggested
= nullptr;
9108 for (auto *Redecl
: ED
->redecls()) {
9109 if (isAcceptable(Redecl
, Kind
))
9111 if (Redecl
->isThisDeclarationADefinition() ||
9112 (Redecl
->isCanonicalDecl() && !*Suggested
))
9113 *Suggested
= Redecl
;
9118 D
= ED
->getDefinition();
9119 } else if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
9120 if (auto *Pattern
= FD
->getTemplateInstantiationPattern())
9122 D
= FD
->getDefinition();
9123 } else if (auto *VD
= dyn_cast
<VarDecl
>(D
)) {
9124 if (auto *Pattern
= VD
->getTemplateInstantiationPattern())
9126 D
= VD
->getDefinition();
9129 assert(D
&& "missing definition for pattern of instantiated definition");
9133 auto DefinitionIsAcceptable
= [&] {
9134 // The (primary) definition might be in a visible module.
9135 if (isAcceptable(D
, Kind
))
9138 // A visible module might have a merged definition instead.
9139 if (D
->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D
)
9140 : hasVisibleMergedDefinition(D
)) {
9141 if (CodeSynthesisContexts
.empty() &&
9142 !getLangOpts().ModulesLocalVisibility
) {
9143 // Cache the fact that this definition is implicitly visible because
9144 // there is a visible merged definition.
9145 D
->setVisibleDespiteOwningModule();
9153 if (DefinitionIsAcceptable())
9156 // The external source may have additional definitions of this entity that are
9157 // visible, so complete the redeclaration chain now and ask again.
9158 if (auto *Source
= Context
.getExternalSource()) {
9159 Source
->CompleteRedeclChain(D
);
9160 return DefinitionIsAcceptable();
9166 /// Determine whether there is any declaration of \p D that was ever a
9167 /// definition (perhaps before module merging) and is currently visible.
9168 /// \param D The definition of the entity.
9169 /// \param Suggested Filled in with the declaration that should be made visible
9170 /// in order to provide a definition of this entity.
9171 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9172 /// not defined. This only matters for enums with a fixed underlying
9173 /// type, since in all other cases, a type is complete if and only if it
9175 bool Sema::hasVisibleDefinition(NamedDecl
*D
, NamedDecl
**Suggested
,
9176 bool OnlyNeedComplete
) {
9177 return hasAcceptableDefinition(D
, Suggested
, Sema::AcceptableKind::Visible
,
9181 /// Determine whether there is any declaration of \p D that was ever a
9182 /// definition (perhaps before module merging) and is currently
9184 /// \param D The definition of the entity.
9185 /// \param Suggested Filled in with the declaration that should be made
9187 /// in order to provide a definition of this entity.
9188 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9189 /// not defined. This only matters for enums with a fixed underlying
9190 /// type, since in all other cases, a type is complete if and only if it
9192 bool Sema::hasReachableDefinition(NamedDecl
*D
, NamedDecl
**Suggested
,
9193 bool OnlyNeedComplete
) {
9194 return hasAcceptableDefinition(D
, Suggested
, Sema::AcceptableKind::Reachable
,
9198 /// Locks in the inheritance model for the given class and all of its bases.
9199 static void assignInheritanceModel(Sema
&S
, CXXRecordDecl
*RD
) {
9200 RD
= RD
->getMostRecentNonInjectedDecl();
9201 if (!RD
->hasAttr
<MSInheritanceAttr
>()) {
9202 MSInheritanceModel IM
;
9203 bool BestCase
= false;
9204 switch (S
.MSPointerToMemberRepresentationMethod
) {
9205 case LangOptions::PPTMK_BestCase
:
9207 IM
= RD
->calculateInheritanceModel();
9209 case LangOptions::PPTMK_FullGeneralitySingleInheritance
:
9210 IM
= MSInheritanceModel::Single
;
9212 case LangOptions::PPTMK_FullGeneralityMultipleInheritance
:
9213 IM
= MSInheritanceModel::Multiple
;
9215 case LangOptions::PPTMK_FullGeneralityVirtualInheritance
:
9216 IM
= MSInheritanceModel::Unspecified
;
9220 SourceRange Loc
= S
.ImplicitMSInheritanceAttrLoc
.isValid()
9221 ? S
.ImplicitMSInheritanceAttrLoc
9222 : RD
->getSourceRange();
9223 RD
->addAttr(MSInheritanceAttr::CreateImplicit(
9224 S
.getASTContext(), BestCase
, Loc
, MSInheritanceAttr::Spelling(IM
)));
9225 S
.Consumer
.AssignInheritanceModel(RD
);
9229 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc
, QualType T
,
9230 CompleteTypeKind Kind
,
9231 TypeDiagnoser
*Diagnoser
) {
9232 // FIXME: Add this assertion to make sure we always get instantiation points.
9233 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9234 // FIXME: Add this assertion to help us flush out problems with
9235 // checking for dependent types and type-dependent expressions.
9237 // assert(!T->isDependentType() &&
9238 // "Can't ask whether a dependent type is complete");
9240 if (const MemberPointerType
*MPTy
= T
->getAs
<MemberPointerType
>()) {
9241 if (!MPTy
->getClass()->isDependentType()) {
9242 if (getLangOpts().CompleteMemberPointers
&&
9243 !MPTy
->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
9244 RequireCompleteType(Loc
, QualType(MPTy
->getClass(), 0), Kind
,
9245 diag::err_memptr_incomplete
))
9248 // We lock in the inheritance model once somebody has asked us to ensure
9249 // that a pointer-to-member type is complete.
9250 if (Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
9251 (void)isCompleteType(Loc
, QualType(MPTy
->getClass(), 0));
9252 assignInheritanceModel(*this, MPTy
->getMostRecentCXXRecordDecl());
9257 NamedDecl
*Def
= nullptr;
9258 bool AcceptSizeless
= (Kind
== CompleteTypeKind::AcceptSizeless
);
9259 bool Incomplete
= (T
->isIncompleteType(&Def
) ||
9260 (!AcceptSizeless
&& T
->isSizelessBuiltinType()));
9262 // Check that any necessary explicit specializations are visible. For an
9263 // enum, we just need the declaration, so don't check this.
9264 if (Def
&& !isa
<EnumDecl
>(Def
))
9265 checkSpecializationReachability(Loc
, Def
);
9267 // If we have a complete type, we're done.
9269 NamedDecl
*Suggested
= nullptr;
9271 !hasReachableDefinition(Def
, &Suggested
, /*OnlyNeedComplete=*/true)) {
9272 // If the user is going to see an error here, recover by making the
9273 // definition visible.
9274 bool TreatAsComplete
= Diagnoser
&& !isSFINAEContext();
9275 if (Diagnoser
&& Suggested
)
9276 diagnoseMissingImport(Loc
, Suggested
, MissingImportKind::Definition
,
9277 /*Recover*/ TreatAsComplete
);
9278 return !TreatAsComplete
;
9279 } else if (Def
&& !TemplateInstCallbacks
.empty()) {
9280 CodeSynthesisContext TempInst
;
9281 TempInst
.Kind
= CodeSynthesisContext::Memoization
;
9282 TempInst
.Template
= Def
;
9283 TempInst
.Entity
= Def
;
9284 TempInst
.PointOfInstantiation
= Loc
;
9285 atTemplateBegin(TemplateInstCallbacks
, *this, TempInst
);
9286 atTemplateEnd(TemplateInstCallbacks
, *this, TempInst
);
9292 TagDecl
*Tag
= dyn_cast_or_null
<TagDecl
>(Def
);
9293 ObjCInterfaceDecl
*IFace
= dyn_cast_or_null
<ObjCInterfaceDecl
>(Def
);
9295 // Give the external source a chance to provide a definition of the type.
9296 // This is kept separate from completing the redeclaration chain so that
9297 // external sources such as LLDB can avoid synthesizing a type definition
9298 // unless it's actually needed.
9300 // Avoid diagnosing invalid decls as incomplete.
9301 if (Def
->isInvalidDecl())
9304 // Give the external AST source a chance to complete the type.
9305 if (auto *Source
= Context
.getExternalSource()) {
9306 if (Tag
&& Tag
->hasExternalLexicalStorage())
9307 Source
->CompleteType(Tag
);
9308 if (IFace
&& IFace
->hasExternalLexicalStorage())
9309 Source
->CompleteType(IFace
);
9310 // If the external source completed the type, go through the motions
9311 // again to ensure we're allowed to use the completed type.
9312 if (!T
->isIncompleteType())
9313 return RequireCompleteTypeImpl(Loc
, T
, Kind
, Diagnoser
);
9317 // If we have a class template specialization or a class member of a
9318 // class template specialization, or an array with known size of such,
9319 // try to instantiate it.
9320 if (auto *RD
= dyn_cast_or_null
<CXXRecordDecl
>(Tag
)) {
9321 bool Instantiated
= false;
9322 bool Diagnosed
= false;
9323 if (RD
->isDependentContext()) {
9324 // Don't try to instantiate a dependent class (eg, a member template of
9325 // an instantiated class template specialization).
9326 // FIXME: Can this ever happen?
9327 } else if (auto *ClassTemplateSpec
=
9328 dyn_cast
<ClassTemplateSpecializationDecl
>(RD
)) {
9329 if (ClassTemplateSpec
->getSpecializationKind() == TSK_Undeclared
) {
9330 runWithSufficientStackSpace(Loc
, [&] {
9331 Diagnosed
= InstantiateClassTemplateSpecialization(
9332 Loc
, ClassTemplateSpec
, TSK_ImplicitInstantiation
,
9333 /*Complain=*/Diagnoser
);
9335 Instantiated
= true;
9338 CXXRecordDecl
*Pattern
= RD
->getInstantiatedFromMemberClass();
9339 if (!RD
->isBeingDefined() && Pattern
) {
9340 MemberSpecializationInfo
*MSI
= RD
->getMemberSpecializationInfo();
9341 assert(MSI
&& "Missing member specialization information?");
9342 // This record was instantiated from a class within a template.
9343 if (MSI
->getTemplateSpecializationKind() !=
9344 TSK_ExplicitSpecialization
) {
9345 runWithSufficientStackSpace(Loc
, [&] {
9346 Diagnosed
= InstantiateClass(Loc
, RD
, Pattern
,
9347 getTemplateInstantiationArgs(RD
),
9348 TSK_ImplicitInstantiation
,
9349 /*Complain=*/Diagnoser
);
9351 Instantiated
= true;
9357 // Instantiate* might have already complained that the template is not
9358 // defined, if we asked it to.
9359 if (Diagnoser
&& Diagnosed
)
9361 // If we instantiated a definition, check that it's usable, even if
9362 // instantiation produced an error, so that repeated calls to this
9363 // function give consistent answers.
9364 if (!T
->isIncompleteType())
9365 return RequireCompleteTypeImpl(Loc
, T
, Kind
, Diagnoser
);
9369 // FIXME: If we didn't instantiate a definition because of an explicit
9370 // specialization declaration, check that it's visible.
9375 Diagnoser
->diagnose(*this, Loc
, T
);
9377 // If the type was a forward declaration of a class/struct/union
9378 // type, produce a note.
9379 if (Tag
&& !Tag
->isInvalidDecl() && !Tag
->getLocation().isInvalid())
9380 Diag(Tag
->getLocation(),
9381 Tag
->isBeingDefined() ? diag::note_type_being_defined
9382 : diag::note_forward_declaration
)
9383 << Context
.getTagDeclType(Tag
);
9385 // If the Objective-C class was a forward declaration, produce a note.
9386 if (IFace
&& !IFace
->isInvalidDecl() && !IFace
->getLocation().isInvalid())
9387 Diag(IFace
->getLocation(), diag::note_forward_class
);
9389 // If we have external information that we can use to suggest a fix,
9392 ExternalSource
->MaybeDiagnoseMissingCompleteType(Loc
, T
);
9397 bool Sema::RequireCompleteType(SourceLocation Loc
, QualType T
,
9398 CompleteTypeKind Kind
, unsigned DiagID
) {
9399 BoundTypeDiagnoser
<> Diagnoser(DiagID
);
9400 return RequireCompleteType(Loc
, T
, Kind
, Diagnoser
);
9403 /// Get diagnostic %select index for tag kind for
9404 /// literal type diagnostic message.
9405 /// WARNING: Indexes apply to particular diagnostics only!
9407 /// \returns diagnostic %select index.
9408 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag
) {
9410 case TagTypeKind::Struct
:
9412 case TagTypeKind::Interface
:
9414 case TagTypeKind::Class
:
9416 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9420 bool Sema::RequireLiteralType(SourceLocation Loc
, QualType T
,
9421 TypeDiagnoser
&Diagnoser
) {
9422 assert(!T
->isDependentType() && "type should not be dependent");
9424 QualType ElemType
= Context
.getBaseElementType(T
);
9425 if ((isCompleteType(Loc
, ElemType
) || ElemType
->isVoidType()) &&
9426 T
->isLiteralType(Context
))
9429 Diagnoser
.diagnose(*this, Loc
, T
);
9431 if (T
->isVariableArrayType())
9434 const RecordType
*RT
= ElemType
->getAs
<RecordType
>();
9438 const CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(RT
->getDecl());
9440 // A partially-defined class type can't be a literal type, because a literal
9441 // class type must have a trivial destructor (which can't be checked until
9442 // the class definition is complete).
9443 if (RequireCompleteType(Loc
, ElemType
, diag::note_non_literal_incomplete
, T
))
9446 // [expr.prim.lambda]p3:
9447 // This class type is [not] a literal type.
9448 if (RD
->isLambda() && !getLangOpts().CPlusPlus17
) {
9449 Diag(RD
->getLocation(), diag::note_non_literal_lambda
);
9453 // If the class has virtual base classes, then it's not an aggregate, and
9454 // cannot have any constexpr constructors or a trivial default constructor,
9455 // so is non-literal. This is better to diagnose than the resulting absence
9456 // of constexpr constructors.
9457 if (RD
->getNumVBases()) {
9458 Diag(RD
->getLocation(), diag::note_non_literal_virtual_base
)
9459 << getLiteralDiagFromTagKind(RD
->getTagKind()) << RD
->getNumVBases();
9460 for (const auto &I
: RD
->vbases())
9461 Diag(I
.getBeginLoc(), diag::note_constexpr_virtual_base_here
)
9462 << I
.getSourceRange();
9463 } else if (!RD
->isAggregate() && !RD
->hasConstexprNonCopyMoveConstructor() &&
9464 !RD
->hasTrivialDefaultConstructor()) {
9465 Diag(RD
->getLocation(), diag::note_non_literal_no_constexpr_ctors
) << RD
;
9466 } else if (RD
->hasNonLiteralTypeFieldsOrBases()) {
9467 for (const auto &I
: RD
->bases()) {
9468 if (!I
.getType()->isLiteralType(Context
)) {
9469 Diag(I
.getBeginLoc(), diag::note_non_literal_base_class
)
9470 << RD
<< I
.getType() << I
.getSourceRange();
9474 for (const auto *I
: RD
->fields()) {
9475 if (!I
->getType()->isLiteralType(Context
) ||
9476 I
->getType().isVolatileQualified()) {
9477 Diag(I
->getLocation(), diag::note_non_literal_field
)
9478 << RD
<< I
<< I
->getType()
9479 << I
->getType().isVolatileQualified();
9483 } else if (getLangOpts().CPlusPlus20
? !RD
->hasConstexprDestructor()
9484 : !RD
->hasTrivialDestructor()) {
9485 // All fields and bases are of literal types, so have trivial or constexpr
9486 // destructors. If this class's destructor is non-trivial / non-constexpr,
9487 // it must be user-declared.
9488 CXXDestructorDecl
*Dtor
= RD
->getDestructor();
9489 assert(Dtor
&& "class has literal fields and bases but no dtor?");
9493 if (getLangOpts().CPlusPlus20
) {
9494 Diag(Dtor
->getLocation(), diag::note_non_literal_non_constexpr_dtor
)
9497 Diag(Dtor
->getLocation(), Dtor
->isUserProvided()
9498 ? diag::note_non_literal_user_provided_dtor
9499 : diag::note_non_literal_nontrivial_dtor
)
9501 if (!Dtor
->isUserProvided())
9502 SpecialMemberIsTrivial(Dtor
, CXXSpecialMemberKind::Destructor
,
9503 TAH_IgnoreTrivialABI
,
9511 bool Sema::RequireLiteralType(SourceLocation Loc
, QualType T
, unsigned DiagID
) {
9512 BoundTypeDiagnoser
<> Diagnoser(DiagID
);
9513 return RequireLiteralType(Loc
, T
, Diagnoser
);
9516 QualType
Sema::getElaboratedType(ElaboratedTypeKeyword Keyword
,
9517 const CXXScopeSpec
&SS
, QualType T
,
9518 TagDecl
*OwnedTagDecl
) {
9521 return Context
.getElaboratedType(
9522 Keyword
, SS
.isValid() ? SS
.getScopeRep() : nullptr, T
, OwnedTagDecl
);
9525 QualType
Sema::BuildTypeofExprType(Expr
*E
, TypeOfKind Kind
) {
9526 assert(!E
->hasPlaceholderType() && "unexpected placeholder");
9528 if (!getLangOpts().CPlusPlus
&& E
->refersToBitField())
9529 Diag(E
->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield
)
9530 << (Kind
== TypeOfKind::Unqualified
? 3 : 2);
9532 if (!E
->isTypeDependent()) {
9533 QualType T
= E
->getType();
9534 if (const TagType
*TT
= T
->getAs
<TagType
>())
9535 DiagnoseUseOfDecl(TT
->getDecl(), E
->getExprLoc());
9537 return Context
.getTypeOfExprType(E
, Kind
);
9541 BuildTypeCoupledDecls(Expr
*E
,
9542 llvm::SmallVectorImpl
<TypeCoupledDeclRefInfo
> &Decls
) {
9543 // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl.
9544 auto *CountDecl
= cast
<DeclRefExpr
>(E
)->getDecl();
9545 Decls
.push_back(TypeCoupledDeclRefInfo(CountDecl
, /*IsDref*/ false));
9548 QualType
Sema::BuildCountAttributedArrayOrPointerType(QualType WrappedTy
,
9552 assert(WrappedTy
->isIncompleteArrayType() || WrappedTy
->isPointerType());
9554 llvm::SmallVector
<TypeCoupledDeclRefInfo
, 1> Decls
;
9555 BuildTypeCoupledDecls(CountExpr
, Decls
);
9556 /// When the resulting expression is invalid, we still create the AST using
9557 /// the original count expression for the sake of AST dump.
9558 return Context
.getCountAttributedType(WrappedTy
, CountExpr
, CountInBytes
,
9562 /// getDecltypeForExpr - Given an expr, will return the decltype for
9563 /// that expression, according to the rules in C++11
9564 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
9565 QualType
Sema::getDecltypeForExpr(Expr
*E
) {
9568 if (auto *ImplCastExpr
= dyn_cast
<ImplicitCastExpr
>(E
))
9569 IDExpr
= ImplCastExpr
->getSubExpr();
9571 if (auto *PackExpr
= dyn_cast
<PackIndexingExpr
>(E
)) {
9572 if (E
->isInstantiationDependent())
9573 IDExpr
= PackExpr
->getPackIdExpression();
9575 IDExpr
= PackExpr
->getSelectedExpr();
9578 if (E
->isTypeDependent())
9579 return Context
.DependentTy
;
9581 // C++11 [dcl.type.simple]p4:
9582 // The type denoted by decltype(e) is defined as follows:
9585 // - if E is an unparenthesized id-expression naming a non-type
9586 // template-parameter (13.2), decltype(E) is the type of the
9587 // template-parameter after performing any necessary type deduction
9588 // Note that this does not pick up the implicit 'const' for a template
9589 // parameter object. This rule makes no difference before C++20 so we apply
9590 // it unconditionally.
9591 if (const auto *SNTTPE
= dyn_cast
<SubstNonTypeTemplateParmExpr
>(IDExpr
))
9592 return SNTTPE
->getParameterType(Context
);
9594 // - if e is an unparenthesized id-expression or an unparenthesized class
9595 // member access (5.2.5), decltype(e) is the type of the entity named
9596 // by e. If there is no such entity, or if e names a set of overloaded
9597 // functions, the program is ill-formed;
9599 // We apply the same rules for Objective-C ivar and property references.
9600 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(IDExpr
)) {
9601 const ValueDecl
*VD
= DRE
->getDecl();
9602 QualType T
= VD
->getType();
9603 return isa
<TemplateParamObjectDecl
>(VD
) ? T
.getUnqualifiedType() : T
;
9605 if (const auto *ME
= dyn_cast
<MemberExpr
>(IDExpr
)) {
9606 if (const auto *VD
= ME
->getMemberDecl())
9607 if (isa
<FieldDecl
>(VD
) || isa
<VarDecl
>(VD
))
9608 return VD
->getType();
9609 } else if (const auto *IR
= dyn_cast
<ObjCIvarRefExpr
>(IDExpr
)) {
9610 return IR
->getDecl()->getType();
9611 } else if (const auto *PR
= dyn_cast
<ObjCPropertyRefExpr
>(IDExpr
)) {
9612 if (PR
->isExplicitProperty())
9613 return PR
->getExplicitProperty()->getType();
9614 } else if (const auto *PE
= dyn_cast
<PredefinedExpr
>(IDExpr
)) {
9615 return PE
->getType();
9618 // C++11 [expr.lambda.prim]p18:
9619 // Every occurrence of decltype((x)) where x is a possibly
9620 // parenthesized id-expression that names an entity of automatic
9621 // storage duration is treated as if x were transformed into an
9622 // access to a corresponding data member of the closure type that
9623 // would have been declared if x were an odr-use of the denoted
9625 if (getCurLambda() && isa
<ParenExpr
>(IDExpr
)) {
9626 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(IDExpr
->IgnoreParens())) {
9627 if (auto *Var
= dyn_cast
<VarDecl
>(DRE
->getDecl())) {
9628 QualType T
= getCapturedDeclRefType(Var
, DRE
->getLocation());
9630 return Context
.getLValueReferenceType(T
);
9635 return Context
.getReferenceQualifiedType(E
);
9638 QualType
Sema::BuildDecltypeType(Expr
*E
, bool AsUnevaluated
) {
9639 assert(!E
->hasPlaceholderType() && "unexpected placeholder");
9641 if (AsUnevaluated
&& CodeSynthesisContexts
.empty() &&
9642 !E
->isInstantiationDependent() && E
->HasSideEffects(Context
, false)) {
9643 // The expression operand for decltype is in an unevaluated expression
9644 // context, so side effects could result in unintended consequences.
9645 // Exclude instantiation-dependent expressions, because 'decltype' is often
9646 // used to build SFINAE gadgets.
9647 Diag(E
->getExprLoc(), diag::warn_side_effects_unevaluated_context
);
9649 return Context
.getDecltypeType(E
, getDecltypeForExpr(E
));
9652 QualType
Sema::ActOnPackIndexingType(QualType Pattern
, Expr
*IndexExpr
,
9654 SourceLocation EllipsisLoc
) {
9658 // Diagnose unexpanded packs but continue to improve recovery.
9659 if (!Pattern
->containsUnexpandedParameterPack())
9660 Diag(Loc
, diag::err_expected_name_of_pack
) << Pattern
;
9662 QualType Type
= BuildPackIndexingType(Pattern
, IndexExpr
, Loc
, EllipsisLoc
);
9665 Diag(Loc
, getLangOpts().CPlusPlus26
? diag::warn_cxx23_pack_indexing
9666 : diag::ext_pack_indexing
);
9670 QualType
Sema::BuildPackIndexingType(QualType Pattern
, Expr
*IndexExpr
,
9672 SourceLocation EllipsisLoc
,
9673 bool FullySubstituted
,
9674 ArrayRef
<QualType
> Expansions
) {
9676 std::optional
<int64_t> Index
;
9677 if (FullySubstituted
&& !IndexExpr
->isValueDependent() &&
9678 !IndexExpr
->isTypeDependent()) {
9679 llvm::APSInt
Value(Context
.getIntWidth(Context
.getSizeType()));
9680 ExprResult Res
= CheckConvertedConstantExpression(
9681 IndexExpr
, Context
.getSizeType(), Value
, CCEK_ArrayBound
);
9682 if (!Res
.isUsable())
9684 Index
= Value
.getExtValue();
9685 IndexExpr
= Res
.get();
9688 if (FullySubstituted
&& Index
) {
9689 if (*Index
< 0 || *Index
>= int64_t(Expansions
.size())) {
9690 Diag(IndexExpr
->getBeginLoc(), diag::err_pack_index_out_of_bound
)
9691 << *Index
<< Pattern
<< Expansions
.size();
9696 return Context
.getPackIndexingType(Pattern
, IndexExpr
, FullySubstituted
,
9697 Expansions
, Index
.value_or(-1));
9700 static QualType
GetEnumUnderlyingType(Sema
&S
, QualType BaseType
,
9701 SourceLocation Loc
) {
9702 assert(BaseType
->isEnumeralType());
9703 EnumDecl
*ED
= BaseType
->castAs
<EnumType
>()->getDecl();
9704 assert(ED
&& "EnumType has no EnumDecl");
9706 S
.DiagnoseUseOfDecl(ED
, Loc
);
9708 QualType Underlying
= ED
->getIntegerType();
9709 assert(!Underlying
.isNull());
9714 QualType
Sema::BuiltinEnumUnderlyingType(QualType BaseType
,
9715 SourceLocation Loc
) {
9716 if (!BaseType
->isEnumeralType()) {
9717 Diag(Loc
, diag::err_only_enums_have_underlying_types
);
9721 // The enum could be incomplete if we're parsing its definition or
9722 // recovering from an error.
9723 NamedDecl
*FwdDecl
= nullptr;
9724 if (BaseType
->isIncompleteType(&FwdDecl
)) {
9725 Diag(Loc
, diag::err_underlying_type_of_incomplete_enum
) << BaseType
;
9726 Diag(FwdDecl
->getLocation(), diag::note_forward_declaration
) << FwdDecl
;
9730 return GetEnumUnderlyingType(*this, BaseType
, Loc
);
9733 QualType
Sema::BuiltinAddPointer(QualType BaseType
, SourceLocation Loc
) {
9734 QualType Pointer
= BaseType
.isReferenceable() || BaseType
->isVoidType()
9735 ? BuildPointerType(BaseType
.getNonReferenceType(), Loc
,
9739 return Pointer
.isNull() ? QualType() : Pointer
;
9742 QualType
Sema::BuiltinRemovePointer(QualType BaseType
, SourceLocation Loc
) {
9743 // We don't want block pointers or ObjectiveC's id type.
9744 if (!BaseType
->isAnyPointerType() || BaseType
->isObjCIdType())
9747 return BaseType
->getPointeeType();
9750 QualType
Sema::BuiltinDecay(QualType BaseType
, SourceLocation Loc
) {
9751 QualType Underlying
= BaseType
.getNonReferenceType();
9752 if (Underlying
->isArrayType())
9753 return Context
.getDecayedType(Underlying
);
9755 if (Underlying
->isFunctionType())
9756 return BuiltinAddPointer(BaseType
, Loc
);
9758 SplitQualType Split
= Underlying
.getSplitUnqualifiedType();
9759 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
9760 // in the same group of qualifiers as 'const' and 'volatile', we're extending
9761 // '__decay(T)' so that it removes all qualifiers.
9762 Split
.Quals
.removeCVRQualifiers();
9763 return Context
.getQualifiedType(Split
);
9766 QualType
Sema::BuiltinAddReference(QualType BaseType
, UTTKind UKind
,
9767 SourceLocation Loc
) {
9768 assert(LangOpts
.CPlusPlus
);
9769 QualType Reference
=
9770 BaseType
.isReferenceable()
9771 ? BuildReferenceType(BaseType
,
9772 UKind
== UnaryTransformType::AddLvalueReference
,
9773 Loc
, DeclarationName())
9775 return Reference
.isNull() ? QualType() : Reference
;
9778 QualType
Sema::BuiltinRemoveExtent(QualType BaseType
, UTTKind UKind
,
9779 SourceLocation Loc
) {
9780 if (UKind
== UnaryTransformType::RemoveAllExtents
)
9781 return Context
.getBaseElementType(BaseType
);
9783 if (const auto *AT
= Context
.getAsArrayType(BaseType
))
9784 return AT
->getElementType();
9789 QualType
Sema::BuiltinRemoveReference(QualType BaseType
, UTTKind UKind
,
9790 SourceLocation Loc
) {
9791 assert(LangOpts
.CPlusPlus
);
9792 QualType T
= BaseType
.getNonReferenceType();
9793 if (UKind
== UTTKind::RemoveCVRef
&&
9794 (T
.isConstQualified() || T
.isVolatileQualified())) {
9796 QualType Unqual
= Context
.getUnqualifiedArrayType(T
, Quals
);
9797 Quals
.removeConst();
9798 Quals
.removeVolatile();
9799 T
= Context
.getQualifiedType(Unqual
, Quals
);
9804 QualType
Sema::BuiltinChangeCVRQualifiers(QualType BaseType
, UTTKind UKind
,
9805 SourceLocation Loc
) {
9806 if ((BaseType
->isReferenceType() && UKind
!= UTTKind::RemoveRestrict
) ||
9807 BaseType
->isFunctionType())
9811 QualType Unqual
= Context
.getUnqualifiedArrayType(BaseType
, Quals
);
9813 if (UKind
== UTTKind::RemoveConst
|| UKind
== UTTKind::RemoveCV
)
9814 Quals
.removeConst();
9815 if (UKind
== UTTKind::RemoveVolatile
|| UKind
== UTTKind::RemoveCV
)
9816 Quals
.removeVolatile();
9817 if (UKind
== UTTKind::RemoveRestrict
)
9818 Quals
.removeRestrict();
9820 return Context
.getQualifiedType(Unqual
, Quals
);
9823 static QualType
ChangeIntegralSignedness(Sema
&S
, QualType BaseType
,
9825 SourceLocation Loc
) {
9826 if (BaseType
->isEnumeralType()) {
9827 QualType Underlying
= GetEnumUnderlyingType(S
, BaseType
, Loc
);
9828 if (auto *BitInt
= dyn_cast
<BitIntType
>(Underlying
)) {
9829 unsigned int Bits
= BitInt
->getNumBits();
9831 return S
.Context
.getBitIntType(!IsMakeSigned
, Bits
);
9833 S
.Diag(Loc
, diag::err_make_signed_integral_only
)
9834 << IsMakeSigned
<< /*_BitInt(1)*/ true << BaseType
<< 1 << Underlying
;
9837 if (Underlying
->isBooleanType()) {
9838 S
.Diag(Loc
, diag::err_make_signed_integral_only
)
9839 << IsMakeSigned
<< /*_BitInt(1)*/ false << BaseType
<< 1
9845 bool Int128Unsupported
= !S
.Context
.getTargetInfo().hasInt128Type();
9846 std::array
<CanQualType
*, 6> AllSignedIntegers
= {
9847 &S
.Context
.SignedCharTy
, &S
.Context
.ShortTy
, &S
.Context
.IntTy
,
9848 &S
.Context
.LongTy
, &S
.Context
.LongLongTy
, &S
.Context
.Int128Ty
};
9849 ArrayRef
<CanQualType
*> AvailableSignedIntegers(
9850 AllSignedIntegers
.data(), AllSignedIntegers
.size() - Int128Unsupported
);
9851 std::array
<CanQualType
*, 6> AllUnsignedIntegers
= {
9852 &S
.Context
.UnsignedCharTy
, &S
.Context
.UnsignedShortTy
,
9853 &S
.Context
.UnsignedIntTy
, &S
.Context
.UnsignedLongTy
,
9854 &S
.Context
.UnsignedLongLongTy
, &S
.Context
.UnsignedInt128Ty
};
9855 ArrayRef
<CanQualType
*> AvailableUnsignedIntegers(AllUnsignedIntegers
.data(),
9856 AllUnsignedIntegers
.size() -
9858 ArrayRef
<CanQualType
*> *Consider
=
9859 IsMakeSigned
? &AvailableSignedIntegers
: &AvailableUnsignedIntegers
;
9861 uint64_t BaseSize
= S
.Context
.getTypeSize(BaseType
);
9863 llvm::find_if(*Consider
, [&S
, BaseSize
](const CanQual
<Type
> *T
) {
9864 return BaseSize
== S
.Context
.getTypeSize(T
->getTypePtr());
9867 assert(Result
!= Consider
->end());
9868 return QualType((*Result
)->getTypePtr(), 0);
9871 QualType
Sema::BuiltinChangeSignedness(QualType BaseType
, UTTKind UKind
,
9872 SourceLocation Loc
) {
9873 bool IsMakeSigned
= UKind
== UnaryTransformType::MakeSigned
;
9874 if ((!BaseType
->isIntegerType() && !BaseType
->isEnumeralType()) ||
9875 BaseType
->isBooleanType() ||
9876 (BaseType
->isBitIntType() &&
9877 BaseType
->getAs
<BitIntType
>()->getNumBits() < 2)) {
9878 Diag(Loc
, diag::err_make_signed_integral_only
)
9879 << IsMakeSigned
<< BaseType
->isBitIntType() << BaseType
<< 0;
9883 bool IsNonIntIntegral
=
9884 BaseType
->isChar16Type() || BaseType
->isChar32Type() ||
9885 BaseType
->isWideCharType() || BaseType
->isEnumeralType();
9887 QualType Underlying
=
9889 ? ChangeIntegralSignedness(*this, BaseType
, IsMakeSigned
, Loc
)
9890 : IsMakeSigned
? Context
.getCorrespondingSignedType(BaseType
)
9891 : Context
.getCorrespondingUnsignedType(BaseType
);
9892 if (Underlying
.isNull())
9894 return Context
.getQualifiedType(Underlying
, BaseType
.getQualifiers());
9897 QualType
Sema::BuildUnaryTransformType(QualType BaseType
, UTTKind UKind
,
9898 SourceLocation Loc
) {
9899 if (BaseType
->isDependentType())
9900 return Context
.getUnaryTransformType(BaseType
, BaseType
, UKind
);
9903 case UnaryTransformType::EnumUnderlyingType
: {
9904 Result
= BuiltinEnumUnderlyingType(BaseType
, Loc
);
9907 case UnaryTransformType::AddPointer
: {
9908 Result
= BuiltinAddPointer(BaseType
, Loc
);
9911 case UnaryTransformType::RemovePointer
: {
9912 Result
= BuiltinRemovePointer(BaseType
, Loc
);
9915 case UnaryTransformType::Decay
: {
9916 Result
= BuiltinDecay(BaseType
, Loc
);
9919 case UnaryTransformType::AddLvalueReference
:
9920 case UnaryTransformType::AddRvalueReference
: {
9921 Result
= BuiltinAddReference(BaseType
, UKind
, Loc
);
9924 case UnaryTransformType::RemoveAllExtents
:
9925 case UnaryTransformType::RemoveExtent
: {
9926 Result
= BuiltinRemoveExtent(BaseType
, UKind
, Loc
);
9929 case UnaryTransformType::RemoveCVRef
:
9930 case UnaryTransformType::RemoveReference
: {
9931 Result
= BuiltinRemoveReference(BaseType
, UKind
, Loc
);
9934 case UnaryTransformType::RemoveConst
:
9935 case UnaryTransformType::RemoveCV
:
9936 case UnaryTransformType::RemoveRestrict
:
9937 case UnaryTransformType::RemoveVolatile
: {
9938 Result
= BuiltinChangeCVRQualifiers(BaseType
, UKind
, Loc
);
9941 case UnaryTransformType::MakeSigned
:
9942 case UnaryTransformType::MakeUnsigned
: {
9943 Result
= BuiltinChangeSignedness(BaseType
, UKind
, Loc
);
9948 return !Result
.isNull()
9949 ? Context
.getUnaryTransformType(BaseType
, Result
, UKind
)
9953 QualType
Sema::BuildAtomicType(QualType T
, SourceLocation Loc
) {
9954 if (!isDependentOrGNUAutoType(T
)) {
9955 // FIXME: It isn't entirely clear whether incomplete atomic types
9956 // are allowed or not; for simplicity, ban them for the moment.
9957 if (RequireCompleteType(Loc
, T
, diag::err_atomic_specifier_bad_type
, 0))
9960 int DisallowedKind
= -1;
9961 if (T
->isArrayType())
9963 else if (T
->isFunctionType())
9965 else if (T
->isReferenceType())
9967 else if (T
->isAtomicType())
9969 else if (T
.hasQualifiers())
9971 else if (T
->isSizelessType())
9973 else if (!T
.isTriviallyCopyableType(Context
) && getLangOpts().CPlusPlus
)
9974 // Some other non-trivially-copyable type (probably a C++ class)
9976 else if (T
->isBitIntType())
9978 else if (getLangOpts().C23
&& T
->isUndeducedAutoType())
9979 // _Atomic auto is prohibited in C23
9982 if (DisallowedKind
!= -1) {
9983 Diag(Loc
, diag::err_atomic_specifier_bad_type
) << DisallowedKind
<< T
;
9987 // FIXME: Do we need any handling for ARC here?
9990 // Build the pointer type.
9991 return Context
.getAtomicType(T
);