1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements type-related semantic analysis.
10//
11//===----------------------------------------------------------------------===//
12
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"
50#include <bitset>
51#include <optional>
52
53using namespace clang;
54
55enum TypeDiagSelector {
56 TDS_Function,
57 TDS_Pointer,
58 TDS_ObjCObjOrBlock
59};
60
61/// isOmittedBlockReturnType - Return true if this declarator is missing a
62/// return type because this is a omitted return type on a block literal.
63static bool isOmittedBlockReturnType(const Declarator &D) {
64 if (D.getContext() != DeclaratorContext::BlockLiteral ||
65 D.getDeclSpec().hasTypeSpecifier())
66 return false;
67
68 if (D.getNumTypeObjects() == 0)
69 return true; // ^{ ... }
70
71 if (D.getNumTypeObjects() == 1 &&
72 D.getTypeObject(i: 0).Kind == DeclaratorChunk::Function)
73 return true; // ^(int X, float Y) { ... }
74
75 return false;
76}
77
78/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
79/// doesn't apply to the given type.
80static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
81 QualType type) {
82 TypeDiagSelector WhichType;
83 bool useExpansionLoc = true;
84 switch (attr.getKind()) {
85 case ParsedAttr::AT_ObjCGC:
86 WhichType = TDS_Pointer;
87 break;
88 case ParsedAttr::AT_ObjCOwnership:
89 WhichType = TDS_ObjCObjOrBlock;
90 break;
91 default:
92 // Assume everything else was a function attribute.
93 WhichType = TDS_Function;
94 useExpansionLoc = false;
95 break;
96 }
97
98 SourceLocation loc = attr.getLoc();
99 StringRef name = attr.getAttrName()->getName();
100
101 // The GC attributes are usually written with macros; special-case them.
102 IdentifierInfo *II =
103 attr.isArgIdent(Arg: 0) ? attr.getArgAsIdent(Arg: 0)->getIdentifierInfo() : nullptr;
104 if (useExpansionLoc && loc.isMacroID() && II) {
105 if (II->isStr(Str: "strong")) {
106 if (S.findMacroSpelling(loc, name: "__strong")) name = "__strong";
107 } else if (II->isStr(Str: "weak")) {
108 if (S.findMacroSpelling(loc, name: "__weak")) name = "__weak";
109 }
110 }
111
112 S.Diag(Loc: loc, DiagID: attr.isRegularKeywordAttribute()
113 ? diag::err_type_attribute_wrong_type
114 : diag::warn_type_attribute_wrong_type)
115 << name << WhichType << type;
116}
117
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
123
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_MSABI: \
138 case ParsedAttr::AT_SysVABI: \
139 case ParsedAttr::AT_Pcs: \
140 case ParsedAttr::AT_IntelOclBicc: \
141 case ParsedAttr::AT_PreserveMost: \
142 case ParsedAttr::AT_PreserveAll: \
143 case ParsedAttr::AT_M68kRTD: \
144 case ParsedAttr::AT_PreserveNone: \
145 case ParsedAttr::AT_RISCVVectorCC: \
146 case ParsedAttr::AT_RISCVVLSCC
147
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_CFIUncheckedCallee: \
158 case ParsedAttr::AT_CFISalt: \
159 case ParsedAttr::AT_CmseNSCall: \
160 case ParsedAttr::AT_ArmStreaming: \
161 case ParsedAttr::AT_ArmStreamingCompatible: \
162 case ParsedAttr::AT_ArmPreserves: \
163 case ParsedAttr::AT_ArmIn: \
164 case ParsedAttr::AT_ArmOut: \
165 case ParsedAttr::AT_ArmInOut: \
166 case ParsedAttr::AT_ArmAgnostic: \
167 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
168 case ParsedAttr::AT_AnyX86NoCfCheck: \
169 CALLING_CONV_ATTRS_CASELIST
170
171// Microsoft-specific type qualifiers.
172#define MS_TYPE_ATTRS_CASELIST \
173 case ParsedAttr::AT_Ptr32: \
174 case ParsedAttr::AT_Ptr64: \
175 case ParsedAttr::AT_SPtr: \
176 case ParsedAttr::AT_UPtr
177
178// Nullability qualifiers.
179#define NULLABILITY_TYPE_ATTRS_CASELIST \
180 case ParsedAttr::AT_TypeNonNull: \
181 case ParsedAttr::AT_TypeNullable: \
182 case ParsedAttr::AT_TypeNullableResult: \
183 case ParsedAttr::AT_TypeNullUnspecified
184
185namespace {
186 /// An object which stores processing state for the entire
187 /// GetTypeForDeclarator process.
188 class TypeProcessingState {
189 Sema &sema;
190
191 /// The declarator being processed.
192 Declarator &declarator;
193
194 /// The index of the declarator chunk we're currently processing.
195 /// May be the total number of valid chunks, indicating the
196 /// DeclSpec.
197 unsigned chunkIndex;
198
199 /// The original set of attributes on the DeclSpec.
200 SmallVector<ParsedAttr *, 2> savedAttrs;
201
202 /// A list of attributes to diagnose the uselessness of when the
203 /// processing is complete.
204 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
205
206 /// Attributes corresponding to AttributedTypeLocs that we have not yet
207 /// populated.
208 // FIXME: The two-phase mechanism by which we construct Types and fill
209 // their TypeLocs makes it hard to correctly assign these. We keep the
210 // attributes in creation order as an attempt to make them line up
211 // properly.
212 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
213 SmallVector<TypeAttrPair, 8> AttrsForTypes;
214 bool AttrsForTypesSorted = true;
215
216 /// MacroQualifiedTypes mapping to macro expansion locations that will be
217 /// stored in a MacroQualifiedTypeLoc.
218 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
219
220 /// Flag to indicate we parsed a noderef attribute. This is used for
221 /// validating that noderef was used on a pointer or array.
222 bool parsedNoDeref;
223
224 // Flag to indicate that we already parsed a HLSL parameter modifier
225 // attribute. This prevents double-mutating the type.
226 bool ParsedHLSLParamMod;
227
228 public:
229 TypeProcessingState(Sema &sema, Declarator &declarator)
230 : sema(sema), declarator(declarator),
231 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false),
232 ParsedHLSLParamMod(false) {}
233
234 Sema &getSema() const {
235 return sema;
236 }
237
238 Declarator &getDeclarator() const {
239 return declarator;
240 }
241
242 bool isProcessingDeclSpec() const {
243 return chunkIndex == declarator.getNumTypeObjects();
244 }
245
246 unsigned getCurrentChunkIndex() const {
247 return chunkIndex;
248 }
249
250 void setCurrentChunkIndex(unsigned idx) {
251 assert(idx <= declarator.getNumTypeObjects());
252 chunkIndex = idx;
253 }
254
255 ParsedAttributesView &getCurrentAttributes() const {
256 if (isProcessingDeclSpec())
257 return getMutableDeclSpec().getAttributes();
258 return declarator.getTypeObject(i: chunkIndex).getAttrs();
259 }
260
261 /// Save the current set of attributes on the DeclSpec.
262 void saveDeclSpecAttrs() {
263 // Don't try to save them multiple times.
264 if (!savedAttrs.empty())
265 return;
266
267 DeclSpec &spec = getMutableDeclSpec();
268 llvm::append_range(C&: savedAttrs,
269 R: llvm::make_pointer_range(Range&: spec.getAttributes()));
270 }
271
272 /// Record that we had nowhere to put the given type attribute.
273 /// We will diagnose such attributes later.
274 void addIgnoredTypeAttr(ParsedAttr &attr) {
275 ignoredTypeAttrs.push_back(Elt: &attr);
276 }
277
278 /// Diagnose all the ignored type attributes, given that the
279 /// declarator worked out to the given type.
280 void diagnoseIgnoredTypeAttrs(QualType type) const {
281 for (auto *Attr : ignoredTypeAttrs)
282 diagnoseBadTypeAttribute(S&: getSema(), attr: *Attr, type);
283 }
284
285 /// Get an attributed type for the given attribute, and remember the Attr
286 /// object so that we can attach it to the AttributedTypeLoc.
287 QualType getAttributedType(Attr *A, QualType ModifiedType,
288 QualType EquivType) {
289 QualType T =
290 sema.Context.getAttributedType(attr: A, modifiedType: ModifiedType, equivalentType: EquivType);
291 AttrsForTypes.push_back(Elt: {cast<AttributedType>(Val: T.getTypePtr()), A});
292 AttrsForTypesSorted = false;
293 return T;
294 }
295
296 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
297 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
298 QualType WrappedType) {
299 return sema.Context.getBTFTagAttributedType(BTFAttr, Wrapped: WrappedType);
300 }
301
302 /// Get a OverflowBehaviorType type for the overflow_behavior type
303 /// attribute.
304 QualType
305 getOverflowBehaviorType(OverflowBehaviorType::OverflowBehaviorKind Kind,
306 QualType UnderlyingType) {
307 return sema.Context.getOverflowBehaviorType(Kind, Wrapped: UnderlyingType);
308 }
309
310 /// Completely replace the \c auto in \p TypeWithAuto by
311 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
312 /// necessary.
313 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
314 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
315 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
316 // Attributed type still should be an attributed type after replacement.
317 auto *NewAttrTy = cast<AttributedType>(Val: T.getTypePtr());
318 for (TypeAttrPair &A : AttrsForTypes) {
319 if (A.first == AttrTy)
320 A.first = NewAttrTy;
321 }
322 AttrsForTypesSorted = false;
323 }
324 return T;
325 }
326
327 /// Extract and remove the Attr* for a given attributed type.
328 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
329 if (!AttrsForTypesSorted) {
330 llvm::stable_sort(Range&: AttrsForTypes, C: llvm::less_first());
331 AttrsForTypesSorted = true;
332 }
333
334 // FIXME: This is quadratic if we have lots of reuses of the same
335 // attributed type.
336 for (auto It = llvm::partition_point(
337 Range&: AttrsForTypes,
338 P: [=](const TypeAttrPair &A) { return A.first < AT; });
339 It != AttrsForTypes.end() && It->first == AT; ++It) {
340 if (It->second) {
341 const Attr *Result = It->second;
342 It->second = nullptr;
343 return Result;
344 }
345 }
346
347 llvm_unreachable("no Attr* for AttributedType*");
348 }
349
350 SourceLocation
351 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
352 auto FoundLoc = LocsForMacros.find(Val: MQT);
353 assert(FoundLoc != LocsForMacros.end() &&
354 "Unable to find macro expansion location for MacroQualifedType");
355 return FoundLoc->second;
356 }
357
358 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
359 SourceLocation Loc) {
360 LocsForMacros[MQT] = Loc;
361 }
362
363 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
364
365 bool didParseNoDeref() const { return parsedNoDeref; }
366
367 void setParsedHLSLParamMod(bool Parsed) { ParsedHLSLParamMod = Parsed; }
368
369 bool didParseHLSLParamMod() const { return ParsedHLSLParamMod; }
370
371 ~TypeProcessingState() {
372 if (savedAttrs.empty())
373 return;
374
375 getMutableDeclSpec().getAttributes().clearListOnly();
376 for (ParsedAttr *AL : savedAttrs)
377 getMutableDeclSpec().getAttributes().addAtEnd(newAttr: AL);
378 }
379
380 private:
381 DeclSpec &getMutableDeclSpec() const {
382 return const_cast<DeclSpec&>(declarator.getDeclSpec());
383 }
384 };
385} // end anonymous namespace
386
387static void moveAttrFromListToList(ParsedAttr &attr,
388 ParsedAttributesView &fromList,
389 ParsedAttributesView &toList) {
390 fromList.remove(ToBeRemoved: &attr);
391 toList.addAtEnd(newAttr: &attr);
392}
393
394/// The location of a type attribute.
395enum TypeAttrLocation {
396 /// The attribute is in the decl-specifier-seq.
397 TAL_DeclSpec,
398 /// The attribute is part of a DeclaratorChunk.
399 TAL_DeclChunk,
400 /// The attribute is immediately after the declaration's name.
401 TAL_DeclName
402};
403
404static void
405processTypeAttrs(TypeProcessingState &state, QualType &type,
406 TypeAttrLocation TAL, const ParsedAttributesView &attrs,
407 CUDAFunctionTarget CFT = CUDAFunctionTarget::HostDevice);
408
409static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
410 QualType &type, CUDAFunctionTarget CFT);
411
412static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
413 ParsedAttr &attr, QualType &type);
414
415static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
416 QualType &type);
417
418static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
419 ParsedAttr &attr, QualType &type);
420
421static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
422 ParsedAttr &attr, QualType &type) {
423 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
424 return handleObjCGCTypeAttr(state, attr, type);
425 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
426 return handleObjCOwnershipTypeAttr(state, attr, type);
427}
428
429/// Given the index of a declarator chunk, check whether that chunk
430/// directly specifies the return type of a function and, if so, find
431/// an appropriate place for it.
432///
433/// \param i - a notional index which the search will start
434/// immediately inside
435///
436/// \param onlyBlockPointers Whether we should only look into block
437/// pointer types (vs. all pointer types).
438static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
439 unsigned i,
440 bool onlyBlockPointers) {
441 assert(i <= declarator.getNumTypeObjects());
442
443 DeclaratorChunk *result = nullptr;
444
445 // First, look inwards past parens for a function declarator.
446 for (; i != 0; --i) {
447 DeclaratorChunk &fnChunk = declarator.getTypeObject(i: i-1);
448 switch (fnChunk.Kind) {
449 case DeclaratorChunk::Paren:
450 continue;
451
452 // If we find anything except a function, bail out.
453 case DeclaratorChunk::Pointer:
454 case DeclaratorChunk::BlockPointer:
455 case DeclaratorChunk::Array:
456 case DeclaratorChunk::Reference:
457 case DeclaratorChunk::MemberPointer:
458 case DeclaratorChunk::Pipe:
459 return result;
460
461 // If we do find a function declarator, scan inwards from that,
462 // looking for a (block-)pointer declarator.
463 case DeclaratorChunk::Function:
464 for (--i; i != 0; --i) {
465 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i: i-1);
466 switch (ptrChunk.Kind) {
467 case DeclaratorChunk::Paren:
468 case DeclaratorChunk::Array:
469 case DeclaratorChunk::Function:
470 case DeclaratorChunk::Reference:
471 case DeclaratorChunk::Pipe:
472 continue;
473
474 case DeclaratorChunk::MemberPointer:
475 case DeclaratorChunk::Pointer:
476 if (onlyBlockPointers)
477 continue;
478
479 [[fallthrough]];
480
481 case DeclaratorChunk::BlockPointer:
482 result = &ptrChunk;
483 goto continue_outer;
484 }
485 llvm_unreachable("bad declarator chunk kind");
486 }
487
488 // If we run out of declarators doing that, we're done.
489 return result;
490 }
491 llvm_unreachable("bad declarator chunk kind");
492
493 // Okay, reconsider from our new point.
494 continue_outer: ;
495 }
496
497 // Ran out of chunks, bail out.
498 return result;
499}
500
501/// Given that an objc_gc attribute was written somewhere on a
502/// declaration *other* than on the declarator itself (for which, use
503/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
504/// didn't apply in whatever position it was written in, try to move
505/// it to a more appropriate position.
506static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
507 ParsedAttr &attr, QualType type) {
508 Declarator &declarator = state.getDeclarator();
509
510 // Move it to the outermost normal or block pointer declarator.
511 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
512 DeclaratorChunk &chunk = declarator.getTypeObject(i: i-1);
513 switch (chunk.Kind) {
514 case DeclaratorChunk::Pointer:
515 case DeclaratorChunk::BlockPointer: {
516 // But don't move an ARC ownership attribute to the return type
517 // of a block.
518 DeclaratorChunk *destChunk = nullptr;
519 if (state.isProcessingDeclSpec() &&
520 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
521 destChunk = maybeMovePastReturnType(declarator, i: i - 1,
522 /*onlyBlockPointers=*/true);
523 if (!destChunk) destChunk = &chunk;
524
525 moveAttrFromListToList(attr, fromList&: state.getCurrentAttributes(),
526 toList&: destChunk->getAttrs());
527 return;
528 }
529
530 case DeclaratorChunk::Paren:
531 case DeclaratorChunk::Array:
532 continue;
533
534 // We may be starting at the return type of a block.
535 case DeclaratorChunk::Function:
536 if (state.isProcessingDeclSpec() &&
537 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
538 if (DeclaratorChunk *dest = maybeMovePastReturnType(
539 declarator, i,
540 /*onlyBlockPointers=*/true)) {
541 moveAttrFromListToList(attr, fromList&: state.getCurrentAttributes(),
542 toList&: dest->getAttrs());
543 return;
544 }
545 }
546 goto error;
547
548 // Don't walk through these.
549 case DeclaratorChunk::Reference:
550 case DeclaratorChunk::MemberPointer:
551 case DeclaratorChunk::Pipe:
552 goto error;
553 }
554 }
555 error:
556
557 diagnoseBadTypeAttribute(S&: state.getSema(), attr, type);
558}
559
560/// Distribute an objc_gc type attribute that was written on the
561/// declarator.
562static void distributeObjCPointerTypeAttrFromDeclarator(
563 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
564 Declarator &declarator = state.getDeclarator();
565
566 // objc_gc goes on the innermost pointer to something that's not a
567 // pointer.
568 unsigned innermost = -1U;
569 bool considerDeclSpec = true;
570 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
571 DeclaratorChunk &chunk = declarator.getTypeObject(i);
572 switch (chunk.Kind) {
573 case DeclaratorChunk::Pointer:
574 case DeclaratorChunk::BlockPointer:
575 innermost = i;
576 continue;
577
578 case DeclaratorChunk::Reference:
579 case DeclaratorChunk::MemberPointer:
580 case DeclaratorChunk::Paren:
581 case DeclaratorChunk::Array:
582 case DeclaratorChunk::Pipe:
583 continue;
584
585 case DeclaratorChunk::Function:
586 considerDeclSpec = false;
587 goto done;
588 }
589 }
590 done:
591
592 // That might actually be the decl spec if we weren't blocked by
593 // anything in the declarator.
594 if (considerDeclSpec) {
595 if (handleObjCPointerTypeAttr(state, attr, type&: declSpecType)) {
596 // Splice the attribute into the decl spec. Prevents the
597 // attribute from being applied multiple times and gives
598 // the source-location-filler something to work with.
599 state.saveDeclSpecAttrs();
600 declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
601 Other&: declarator.getAttributes(), PA: &attr);
602 return;
603 }
604 }
605
606 // Otherwise, if we found an appropriate chunk, splice the attribute
607 // into it.
608 if (innermost != -1U) {
609 moveAttrFromListToList(attr, fromList&: declarator.getAttributes(),
610 toList&: declarator.getTypeObject(i: innermost).getAttrs());
611 return;
612 }
613
614 // Otherwise, diagnose when we're done building the type.
615 declarator.getAttributes().remove(ToBeRemoved: &attr);
616 state.addIgnoredTypeAttr(attr);
617}
618
619/// A function type attribute was written somewhere in a declaration
620/// *other* than on the declarator itself or in the decl spec. Given
621/// that it didn't apply in whatever position it was written in, try
622/// to move it to a more appropriate position.
623static void distributeFunctionTypeAttr(TypeProcessingState &state,
624 ParsedAttr &attr, QualType type) {
625 Declarator &declarator = state.getDeclarator();
626
627 // Try to push the attribute from the return type of a function to
628 // the function itself.
629 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
630 DeclaratorChunk &chunk = declarator.getTypeObject(i: i-1);
631 switch (chunk.Kind) {
632 case DeclaratorChunk::Function:
633 moveAttrFromListToList(attr, fromList&: state.getCurrentAttributes(),
634 toList&: chunk.getAttrs());
635 return;
636
637 case DeclaratorChunk::Paren:
638 case DeclaratorChunk::Pointer:
639 case DeclaratorChunk::BlockPointer:
640 case DeclaratorChunk::Array:
641 case DeclaratorChunk::Reference:
642 case DeclaratorChunk::MemberPointer:
643 case DeclaratorChunk::Pipe:
644 continue;
645 }
646 }
647
648 diagnoseBadTypeAttribute(S&: state.getSema(), attr, type);
649}
650
651/// Try to distribute a function type attribute to the innermost
652/// function chunk or type. Returns true if the attribute was
653/// distributed, false if no location was found.
654static bool distributeFunctionTypeAttrToInnermost(
655 TypeProcessingState &state, ParsedAttr &attr,
656 ParsedAttributesView &attrList, QualType &declSpecType,
657 CUDAFunctionTarget CFT) {
658 Declarator &declarator = state.getDeclarator();
659
660 // Put it on the innermost function chunk, if there is one.
661 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
662 DeclaratorChunk &chunk = declarator.getTypeObject(i);
663 if (chunk.Kind != DeclaratorChunk::Function) continue;
664
665 moveAttrFromListToList(attr, fromList&: attrList, toList&: chunk.getAttrs());
666 return true;
667 }
668
669 return handleFunctionTypeAttr(state, attr, type&: declSpecType, CFT);
670}
671
672/// A function type attribute was written in the decl spec. Try to
673/// apply it somewhere.
674static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
675 ParsedAttr &attr,
676 QualType &declSpecType,
677 CUDAFunctionTarget CFT) {
678 state.saveDeclSpecAttrs();
679
680 // Try to distribute to the innermost.
681 if (distributeFunctionTypeAttrToInnermost(
682 state, attr, attrList&: state.getCurrentAttributes(), declSpecType, CFT))
683 return;
684
685 // If that failed, diagnose the bad attribute when the declarator is
686 // fully built.
687 state.addIgnoredTypeAttr(attr);
688}
689
690/// A function type attribute was written on the declarator or declaration.
691/// Try to apply it somewhere.
692/// `Attrs` is the attribute list containing the declaration (either of the
693/// declarator or the declaration).
694static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
695 ParsedAttr &attr,
696 QualType &declSpecType,
697 CUDAFunctionTarget CFT) {
698 Declarator &declarator = state.getDeclarator();
699
700 // Try to distribute to the innermost.
701 if (distributeFunctionTypeAttrToInnermost(
702 state, attr, attrList&: declarator.getAttributes(), declSpecType, CFT))
703 return;
704
705 // If that failed, diagnose the bad attribute when the declarator is
706 // fully built.
707 declarator.getAttributes().remove(ToBeRemoved: &attr);
708 state.addIgnoredTypeAttr(attr);
709}
710
711/// Given that there are attributes written on the declarator or declaration
712/// itself, try to distribute any type attributes to the appropriate
713/// declarator chunk.
714///
715/// These are attributes like the following:
716/// int f ATTR;
717/// int (f ATTR)();
718/// but not necessarily this:
719/// int f() ATTR;
720///
721/// `Attrs` is the attribute list containing the declaration (either of the
722/// declarator or the declaration).
723static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
724 QualType &declSpecType,
725 CUDAFunctionTarget CFT) {
726 // The called functions in this loop actually remove things from the current
727 // list, so iterating over the existing list isn't possible. Instead, make a
728 // non-owning copy and iterate over that.
729 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
730 for (ParsedAttr &attr : AttrsCopy) {
731 // Do not distribute [[]] attributes. They have strict rules for what
732 // they appertain to.
733 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute())
734 continue;
735
736 switch (attr.getKind()) {
737 OBJC_POINTER_TYPE_ATTRS_CASELIST:
738 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
739 break;
740
741 FUNCTION_TYPE_ATTRS_CASELIST:
742 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT);
743 break;
744
745 MS_TYPE_ATTRS_CASELIST:
746 // Microsoft type attributes cannot go after the declarator-id.
747 continue;
748
749 NULLABILITY_TYPE_ATTRS_CASELIST:
750 // Nullability specifiers cannot go after the declarator-id.
751
752 // Objective-C __kindof does not get distributed.
753 case ParsedAttr::AT_ObjCKindOf:
754 continue;
755
756 default:
757 break;
758 }
759 }
760}
761
762/// Add a synthetic '()' to a block-literal declarator if it is
763/// required, given the return type.
764static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
765 QualType declSpecType) {
766 Declarator &declarator = state.getDeclarator();
767
768 // First, check whether the declarator would produce a function,
769 // i.e. whether the innermost semantic chunk is a function.
770 if (declarator.isFunctionDeclarator()) {
771 // If so, make that declarator a prototyped declarator.
772 declarator.getFunctionTypeInfo().hasPrototype = true;
773 return;
774 }
775
776 // If there are any type objects, the type as written won't name a
777 // function, regardless of the decl spec type. This is because a
778 // block signature declarator is always an abstract-declarator, and
779 // abstract-declarators can't just be parentheses chunks. Therefore
780 // we need to build a function chunk unless there are no type
781 // objects and the decl spec type is a function.
782 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
783 return;
784
785 // Note that there *are* cases with invalid declarators where
786 // declarators consist solely of parentheses. In general, these
787 // occur only in failed efforts to make function declarators, so
788 // faking up the function chunk is still the right thing to do.
789
790 // Otherwise, we need to fake up a function declarator.
791 SourceLocation loc = declarator.getBeginLoc();
792
793 // ...and *prepend* it to the declarator.
794 SourceLocation NoLoc;
795 declarator.AddInnermostTypeInfo(TI: DeclaratorChunk::getFunction(
796 /*HasProto=*/true,
797 /*IsAmbiguous=*/false,
798 /*LParenLoc=*/NoLoc,
799 /*ArgInfo=*/Params: nullptr,
800 /*NumParams=*/0,
801 /*EllipsisLoc=*/NoLoc,
802 /*RParenLoc=*/NoLoc,
803 /*RefQualifierIsLvalueRef=*/true,
804 /*RefQualifierLoc=*/NoLoc,
805 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
806 /*ESpecRange=*/SourceRange(),
807 /*Exceptions=*/nullptr,
808 /*ExceptionRanges=*/nullptr,
809 /*NumExceptions=*/0,
810 /*NoexceptExpr=*/nullptr,
811 /*ExceptionSpecTokens=*/nullptr,
812 /*DeclsInPrototype=*/{}, LocalRangeBegin: loc, LocalRangeEnd: loc, TheDeclarator&: declarator));
813
814 // For consistency, make sure the state still has us as processing
815 // the decl spec.
816 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
817 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
818}
819
820static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
821 unsigned &TypeQuals,
822 QualType TypeSoFar,
823 unsigned RemoveTQs,
824 unsigned DiagID) {
825 // If this occurs outside a template instantiation, warn the user about
826 // it; they probably didn't mean to specify a redundant qualifier.
827 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
828 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
829 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
830 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
831 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
832 if (!(RemoveTQs & Qual.first))
833 continue;
834
835 if (!S.inTemplateInstantiation()) {
836 if (TypeQuals & Qual.first)
837 S.Diag(Loc: Qual.second, DiagID)
838 << DeclSpec::getSpecifierName(Q: Qual.first) << TypeSoFar
839 << FixItHint::CreateRemoval(RemoveRange: Qual.second);
840 }
841
842 TypeQuals &= ~Qual.first;
843 }
844}
845
846/// Return true if this is omitted block return type. Also check type
847/// attributes and type qualifiers when returning true.
848static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
849 QualType Result) {
850 if (!isOmittedBlockReturnType(D: declarator))
851 return false;
852
853 // Warn if we see type attributes for omitted return type on a block literal.
854 SmallVector<ParsedAttr *, 2> ToBeRemoved;
855 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
856 if (AL.isInvalid() || !AL.isTypeAttr())
857 continue;
858 S.Diag(Loc: AL.getLoc(),
859 DiagID: diag::warn_block_literal_attributes_on_omitted_return_type)
860 << AL;
861 ToBeRemoved.push_back(Elt: &AL);
862 }
863 // Remove bad attributes from the list.
864 for (ParsedAttr *AL : ToBeRemoved)
865 declarator.getMutableDeclSpec().getAttributes().remove(ToBeRemoved: AL);
866
867 // Warn if we see type qualifiers for omitted return type on a block literal.
868 const DeclSpec &DS = declarator.getDeclSpec();
869 unsigned TypeQuals = DS.getTypeQualifiers();
870 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, TypeSoFar: Result, RemoveTQs: (unsigned)-1,
871 DiagID: diag::warn_block_literal_qualifiers_on_omitted_return_type);
872 declarator.getMutableDeclSpec().ClearTypeQualifiers();
873
874 return true;
875}
876
877static OpenCLAccessAttr::Spelling
878getImageAccess(const ParsedAttributesView &Attrs) {
879 for (const ParsedAttr &AL : Attrs)
880 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
881 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
882 return OpenCLAccessAttr::Keyword_read_only;
883}
884
885static UnaryTransformType::UTTKind
886TSTToUnaryTransformType(DeclSpec::TST SwitchTST) {
887 switch (SwitchTST) {
888#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
889 case TST_##Trait: \
890 return UnaryTransformType::Enum;
891#include "clang/Basic/TransformTypeTraits.def"
892 default:
893 llvm_unreachable("attempted to parse a non-unary transform builtin");
894 }
895}
896
897/// Convert the specified declspec to the appropriate type
898/// object.
899/// \param state Specifies the declarator containing the declaration specifier
900/// to be converted, along with other associated processing state.
901/// \returns The type described by the declaration specifiers. This function
902/// never returns null.
903static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
904 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
905 // checking.
906
907 Sema &S = state.getSema();
908 Declarator &declarator = state.getDeclarator();
909 DeclSpec &DS = declarator.getMutableDeclSpec();
910 SourceLocation DeclLoc = declarator.getIdentifierLoc();
911 if (DeclLoc.isInvalid())
912 DeclLoc = DS.getBeginLoc();
913
914 ASTContext &Context = S.Context;
915
916 QualType Result;
917 switch (DS.getTypeSpecType()) {
918 case DeclSpec::TST_void:
919 Result = Context.VoidTy;
920 break;
921 case DeclSpec::TST_char:
922 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
923 Result = Context.CharTy;
924 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
925 Result = Context.SignedCharTy;
926 else {
927 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
928 "Unknown TSS value");
929 Result = Context.UnsignedCharTy;
930 }
931 break;
932 case DeclSpec::TST_wchar:
933 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
934 Result = Context.WCharTy;
935 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
936 S.Diag(Loc: DS.getTypeSpecSignLoc(), DiagID: diag::ext_wchar_t_sign_spec)
937 << DS.getSpecifierName(T: DS.getTypeSpecType(),
938 Policy: Context.getPrintingPolicy());
939 Result = Context.getSignedWCharType();
940 } else {
941 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
942 "Unknown TSS value");
943 S.Diag(Loc: DS.getTypeSpecSignLoc(), DiagID: diag::ext_wchar_t_sign_spec)
944 << DS.getSpecifierName(T: DS.getTypeSpecType(),
945 Policy: Context.getPrintingPolicy());
946 Result = Context.getUnsignedWCharType();
947 }
948 break;
949 case DeclSpec::TST_char8:
950 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
951 "Unknown TSS value");
952 Result = Context.Char8Ty;
953 break;
954 case DeclSpec::TST_char16:
955 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
956 "Unknown TSS value");
957 Result = Context.Char16Ty;
958 break;
959 case DeclSpec::TST_char32:
960 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
961 "Unknown TSS value");
962 Result = Context.Char32Ty;
963 break;
964 case DeclSpec::TST_unspecified:
965 // If this is a missing declspec in a block literal return context, then it
966 // is inferred from the return statements inside the block.
967 // The declspec is always missing in a lambda expr context; it is either
968 // specified with a trailing return type or inferred.
969 if (S.getLangOpts().CPlusPlus14 &&
970 declarator.getContext() == DeclaratorContext::LambdaExpr) {
971 // In C++1y, a lambda's implicit return type is 'auto'.
972 Result = Context.getAutoDeductType();
973 break;
974 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
975 checkOmittedBlockReturnType(S, declarator,
976 Result: Context.DependentTy)) {
977 Result = Context.DependentTy;
978 break;
979 }
980
981 // Unspecified typespec defaults to int in C90. However, the C90 grammar
982 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
983 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
984 // Note that the one exception to this is function definitions, which are
985 // allowed to be completely missing a declspec. This is handled in the
986 // parser already though by it pretending to have seen an 'int' in this
987 // case.
988 if (S.getLangOpts().isImplicitIntRequired()) {
989 // Only emit the diagnostic for the first declarator in a DeclGroup, as
990 // the warning is always implied for all subsequent declarators, and the
991 // fix must only be applied exactly once as well.
992 if (declarator.isFirstDeclarator()) {
993 S.Diag(Loc: DeclLoc, DiagID: diag::warn_missing_type_specifier)
994 << DS.getSourceRange()
995 << FixItHint::CreateInsertion(InsertionLoc: DS.getBeginLoc(), Code: "int ");
996 }
997 } else if (!DS.hasTypeSpecifier()) {
998 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
999 // "At least one type specifier shall be given in the declaration
1000 // specifiers in each declaration, and in the specifier-qualifier list
1001 // in each struct declaration and type name."
1002 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
1003 if (declarator.isFirstDeclarator()) {
1004 S.Diag(Loc: DeclLoc, DiagID: diag::err_missing_type_specifier)
1005 << DS.getSourceRange();
1006 }
1007
1008 // When this occurs, often something is very broken with the value
1009 // being declared, poison it as invalid so we don't get chains of
1010 // errors.
1011 declarator.setInvalidType(true);
1012 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1013 DS.isTypeSpecPipe()) {
1014 if (declarator.isFirstDeclarator()) {
1015 S.Diag(Loc: DeclLoc, DiagID: diag::err_missing_actual_pipe_type)
1016 << DS.getSourceRange();
1017 }
1018 declarator.setInvalidType(true);
1019 } else if (declarator.isFirstDeclarator()) {
1020 assert(S.getLangOpts().isImplicitIntAllowed() &&
1021 "implicit int is disabled?");
1022 S.Diag(Loc: DeclLoc, DiagID: diag::ext_missing_type_specifier)
1023 << DS.getSourceRange()
1024 << FixItHint::CreateInsertion(InsertionLoc: DS.getBeginLoc(), Code: "int ");
1025 }
1026 }
1027
1028 [[fallthrough]];
1029 case DeclSpec::TST_int: {
1030 if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1031 switch (DS.getTypeSpecWidth()) {
1032 case TypeSpecifierWidth::Unspecified:
1033 Result = Context.IntTy;
1034 break;
1035 case TypeSpecifierWidth::Short:
1036 Result = Context.ShortTy;
1037 break;
1038 case TypeSpecifierWidth::Long:
1039 Result = Context.LongTy;
1040 break;
1041 case TypeSpecifierWidth::LongLong:
1042 Result = Context.LongLongTy;
1043
1044 if (S.getLangOpts().OpenCL) {
1045 // OpenCL v3.0 s6.3.4: 'long long' is a reserved data type.
1046 S.Diag(Loc: DS.getTypeSpecWidthLoc(), DiagID: diag::warn_opencl_longlong);
1047 } else if (!S.getLangOpts().C99) {
1048 // 'long long' is a C99 or C++11 feature.
1049 if (S.getLangOpts().CPlusPlus)
1050 S.Diag(Loc: DS.getTypeSpecWidthLoc(),
1051 DiagID: S.getLangOpts().CPlusPlus11 ?
1052 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1053 else
1054 S.Diag(Loc: DS.getTypeSpecWidthLoc(), DiagID: diag::ext_c99_longlong);
1055 }
1056 break;
1057 }
1058 } else {
1059 switch (DS.getTypeSpecWidth()) {
1060 case TypeSpecifierWidth::Unspecified:
1061 Result = Context.UnsignedIntTy;
1062 break;
1063 case TypeSpecifierWidth::Short:
1064 Result = Context.UnsignedShortTy;
1065 break;
1066 case TypeSpecifierWidth::Long:
1067 Result = Context.UnsignedLongTy;
1068 break;
1069 case TypeSpecifierWidth::LongLong:
1070 Result = Context.UnsignedLongLongTy;
1071
1072 if (S.getLangOpts().OpenCL) {
1073 // OpenCL v3.0 s6.3.4: 'long long' is a reserved data type.
1074 S.Diag(Loc: DS.getTypeSpecWidthLoc(), DiagID: diag::warn_opencl_longlong);
1075 } else if (!S.getLangOpts().C99) {
1076 // 'long long' is a C99 or C++11 feature.
1077 if (S.getLangOpts().CPlusPlus)
1078 S.Diag(Loc: DS.getTypeSpecWidthLoc(),
1079 DiagID: S.getLangOpts().CPlusPlus11 ?
1080 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1081 else
1082 S.Diag(Loc: DS.getTypeSpecWidthLoc(), DiagID: diag::ext_c99_longlong);
1083 }
1084 break;
1085 }
1086 }
1087 break;
1088 }
1089 case DeclSpec::TST_bitint: {
1090 if (!S.Context.getTargetInfo().hasBitIntType())
1091 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_type_unsupported) << "_BitInt";
1092 Result =
1093 S.BuildBitIntType(IsUnsigned: DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1094 BitWidth: DS.getRepAsExpr(), Loc: DS.getBeginLoc());
1095 if (Result.isNull()) {
1096 Result = Context.IntTy;
1097 declarator.setInvalidType(true);
1098 }
1099 break;
1100 }
1101 case DeclSpec::TST_accum: {
1102 switch (DS.getTypeSpecWidth()) {
1103 case TypeSpecifierWidth::Short:
1104 Result = Context.ShortAccumTy;
1105 break;
1106 case TypeSpecifierWidth::Unspecified:
1107 Result = Context.AccumTy;
1108 break;
1109 case TypeSpecifierWidth::Long:
1110 Result = Context.LongAccumTy;
1111 break;
1112 case TypeSpecifierWidth::LongLong:
1113 llvm_unreachable("Unable to specify long long as _Accum width");
1114 }
1115
1116 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1117 Result = Context.getCorrespondingUnsignedType(T: Result);
1118
1119 if (DS.isTypeSpecSat())
1120 Result = Context.getCorrespondingSaturatedType(Ty: Result);
1121
1122 break;
1123 }
1124 case DeclSpec::TST_fract: {
1125 switch (DS.getTypeSpecWidth()) {
1126 case TypeSpecifierWidth::Short:
1127 Result = Context.ShortFractTy;
1128 break;
1129 case TypeSpecifierWidth::Unspecified:
1130 Result = Context.FractTy;
1131 break;
1132 case TypeSpecifierWidth::Long:
1133 Result = Context.LongFractTy;
1134 break;
1135 case TypeSpecifierWidth::LongLong:
1136 llvm_unreachable("Unable to specify long long as _Fract width");
1137 }
1138
1139 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1140 Result = Context.getCorrespondingUnsignedType(T: Result);
1141
1142 if (DS.isTypeSpecSat())
1143 Result = Context.getCorrespondingSaturatedType(Ty: Result);
1144
1145 break;
1146 }
1147 case DeclSpec::TST_int128:
1148 if (!S.Context.getTargetInfo().hasInt128Type() &&
1149 !(S.getLangOpts().isTargetDevice()))
1150 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_type_unsupported)
1151 << "__int128";
1152 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1153 Result = Context.UnsignedInt128Ty;
1154 else
1155 Result = Context.Int128Ty;
1156 break;
1157 case DeclSpec::TST_float16:
1158 // CUDA host and device may have different _Float16 support, therefore
1159 // do not diagnose _Float16 usage to avoid false alarm.
1160 // ToDo: more precise diagnostics for CUDA.
1161 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1162 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1163 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_type_unsupported)
1164 << "_Float16";
1165 Result = Context.Float16Ty;
1166 break;
1167 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1168 case DeclSpec::TST_BFloat16:
1169 if (!S.Context.getTargetInfo().hasBFloat16Type() &&
1170 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) &&
1171 !S.getLangOpts().SYCLIsDevice)
1172 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_type_unsupported) << "__bf16";
1173 Result = Context.BFloat16Ty;
1174 break;
1175 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1176 case DeclSpec::TST_double:
1177 if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1178 Result = Context.LongDoubleTy;
1179 else
1180 Result = Context.DoubleTy;
1181 if (S.getLangOpts().OpenCL) {
1182 if (!S.getOpenCLOptions().isSupported(Ext: "cl_khr_fp64", LO: S.getLangOpts()))
1183 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_opencl_requires_extension)
1184 << 0 << Result
1185 << (S.getLangOpts().getOpenCLCompatibleVersion() == 300
1186 ? "cl_khr_fp64 and __opencl_c_fp64"
1187 : "cl_khr_fp64");
1188 else if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: S.getLangOpts()))
1189 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::ext_opencl_double_without_pragma);
1190 }
1191 break;
1192 case DeclSpec::TST_float128:
1193 if (!S.Context.getTargetInfo().hasFloat128Type() &&
1194 !S.getLangOpts().isTargetDevice())
1195 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_type_unsupported)
1196 << "__float128";
1197 Result = Context.Float128Ty;
1198 break;
1199 case DeclSpec::TST_ibm128:
1200 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1201 !S.getLangOpts().SYCLIsDevice &&
1202 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1203 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_type_unsupported) << "__ibm128";
1204 Result = Context.Ibm128Ty;
1205 break;
1206 case DeclSpec::TST_bool:
1207 Result = Context.BoolTy; // _Bool or bool
1208 break;
1209 case DeclSpec::TST_decimal32: // _Decimal32
1210 case DeclSpec::TST_decimal64: // _Decimal64
1211 case DeclSpec::TST_decimal128: // _Decimal128
1212 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_decimal_unsupported);
1213 Result = Context.IntTy;
1214 declarator.setInvalidType(true);
1215 break;
1216 case DeclSpec::TST_class:
1217 case DeclSpec::TST_enum:
1218 case DeclSpec::TST_union:
1219 case DeclSpec::TST_struct:
1220 case DeclSpec::TST_interface: {
1221 TagDecl *D = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl());
1222 if (!D) {
1223 // This can happen in C++ with ambiguous lookups.
1224 Result = Context.IntTy;
1225 declarator.setInvalidType(true);
1226 break;
1227 }
1228
1229 // If the type is deprecated or unavailable, diagnose it.
1230 S.DiagnoseUseOfDecl(D, Locs: DS.getTypeSpecTypeNameLoc());
1231
1232 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1233 DS.getTypeSpecComplex() == 0 &&
1234 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1235 "No qualifiers on tag names!");
1236
1237 ElaboratedTypeKeyword Keyword =
1238 KeywordHelpers::getKeywordForTypeSpec(TypeSpec: DS.getTypeSpecType());
1239 // TypeQuals handled by caller.
1240 Result = Context.getTagType(Keyword, Qualifier: DS.getTypeSpecScope().getScopeRep(), TD: D,
1241 OwnsTag: DS.isTypeSpecOwned());
1242 break;
1243 }
1244 case DeclSpec::TST_typename: {
1245 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1246 DS.getTypeSpecComplex() == 0 &&
1247 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1248 "Can't handle qualifiers on typedef names yet!");
1249 Result = S.GetTypeFromParser(Ty: DS.getRepAsType());
1250 if (Result.isNull()) {
1251 declarator.setInvalidType(true);
1252 }
1253
1254 // TypeQuals handled by caller.
1255 break;
1256 }
1257 case DeclSpec::TST_typeof_unqualType:
1258 case DeclSpec::TST_typeofType:
1259 // FIXME: Preserve type source info.
1260 Result = S.GetTypeFromParser(Ty: DS.getRepAsType());
1261 assert(!Result.isNull() && "Didn't get a type for typeof?");
1262 if (!Result->isDependentType())
1263 if (const auto *TT = Result->getAs<TagType>())
1264 S.DiagnoseUseOfDecl(D: TT->getDecl(), Locs: DS.getTypeSpecTypeLoc());
1265 // TypeQuals handled by caller.
1266 Result = Context.getTypeOfType(
1267 QT: Result, Kind: DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType
1268 ? TypeOfKind::Unqualified
1269 : TypeOfKind::Qualified);
1270 break;
1271 case DeclSpec::TST_typeof_unqualExpr:
1272 case DeclSpec::TST_typeofExpr: {
1273 Expr *E = DS.getRepAsExpr();
1274 assert(E && "Didn't get an expression for typeof?");
1275 // TypeQuals handled by caller.
1276 Result = S.BuildTypeofExprType(E, Kind: DS.getTypeSpecType() ==
1277 DeclSpec::TST_typeof_unqualExpr
1278 ? TypeOfKind::Unqualified
1279 : TypeOfKind::Qualified);
1280 if (Result.isNull()) {
1281 Result = Context.IntTy;
1282 declarator.setInvalidType(true);
1283 }
1284 break;
1285 }
1286 case DeclSpec::TST_decltype: {
1287 Expr *E = DS.getRepAsExpr();
1288 assert(E && "Didn't get an expression for decltype?");
1289 // TypeQuals handled by caller.
1290 Result = S.BuildDecltypeType(E);
1291 if (Result.isNull()) {
1292 Result = Context.IntTy;
1293 declarator.setInvalidType(true);
1294 }
1295 break;
1296 }
1297 case DeclSpec::TST_typename_pack_indexing: {
1298 Expr *E = DS.getPackIndexingExpr();
1299 assert(E && "Didn't get an expression for pack indexing");
1300 QualType Pattern = S.GetTypeFromParser(Ty: DS.getRepAsType());
1301 Result = S.BuildPackIndexingType(Pattern, IndexExpr: E, Loc: DS.getBeginLoc(),
1302 EllipsisLoc: DS.getEllipsisLoc());
1303 if (Result.isNull()) {
1304 declarator.setInvalidType(true);
1305 Result = Context.IntTy;
1306 }
1307 break;
1308 }
1309
1310#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1311#include "clang/Basic/TransformTypeTraits.def"
1312 Result = S.GetTypeFromParser(Ty: DS.getRepAsType());
1313 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1314 Result = S.BuildUnaryTransformType(
1315 BaseType: Result, UKind: TSTToUnaryTransformType(SwitchTST: DS.getTypeSpecType()),
1316 Loc: DS.getTypeSpecTypeLoc());
1317 if (Result.isNull()) {
1318 Result = Context.IntTy;
1319 declarator.setInvalidType(true);
1320 }
1321 break;
1322
1323 case DeclSpec::TST_auto:
1324 case DeclSpec::TST_decltype_auto: {
1325 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1326 ? AutoTypeKeyword::DecltypeAuto
1327 : AutoTypeKeyword::Auto;
1328
1329 TemplateDecl *TypeConstraintConcept = nullptr;
1330 llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1331 if (DS.isConstrainedAuto()) {
1332 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1333 TypeConstraintConcept =
1334 cast<TemplateDecl>(Val: TemplateId->Template.get().getAsTemplateDecl());
1335 TemplateArgumentListInfo TemplateArgsInfo;
1336 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1337 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1338 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1339 TemplateId->NumArgs);
1340 S.translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgsInfo);
1341 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1342 TemplateArgs.push_back(Elt: ArgLoc.getArgument());
1343 } else {
1344 declarator.setInvalidType(true);
1345 }
1346 }
1347 Result = S.Context.getAutoType(DK: DeducedKind::Undeduced, DeducedAsType: QualType(), Keyword: AutoKW,
1348 TypeConstraintConcept, TypeConstraintArgs: TemplateArgs);
1349 break;
1350 }
1351
1352 case DeclSpec::TST_auto_type:
1353 Result = Context.getAutoType(DK: DeducedKind::Undeduced, DeducedAsType: QualType(),
1354 Keyword: AutoTypeKeyword::GNUAutoType);
1355 break;
1356
1357 case DeclSpec::TST_unknown_anytype:
1358 Result = Context.UnknownAnyTy;
1359 break;
1360
1361 case DeclSpec::TST_atomic:
1362 Result = S.GetTypeFromParser(Ty: DS.getRepAsType());
1363 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1364 Result = S.BuildAtomicType(T: Result, Loc: DS.getTypeSpecTypeLoc());
1365 if (Result.isNull()) {
1366 Result = Context.IntTy;
1367 declarator.setInvalidType(true);
1368 }
1369 break;
1370
1371#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1372 case DeclSpec::TST_##ImgType##_t: \
1373 switch (getImageAccess(DS.getAttributes())) { \
1374 case OpenCLAccessAttr::Keyword_write_only: \
1375 Result = Context.Id##WOTy; \
1376 break; \
1377 case OpenCLAccessAttr::Keyword_read_write: \
1378 Result = Context.Id##RWTy; \
1379 break; \
1380 case OpenCLAccessAttr::Keyword_read_only: \
1381 Result = Context.Id##ROTy; \
1382 break; \
1383 case OpenCLAccessAttr::SpellingNotCalculated: \
1384 llvm_unreachable("Spelling not yet calculated"); \
1385 } \
1386 break;
1387#include "clang/Basic/OpenCLImageTypes.def"
1388
1389#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1390 case DeclSpec::TST_##Name: \
1391 Result = Context.SingletonId; \
1392 break;
1393#include "clang/Basic/HLSLIntangibleTypes.def"
1394
1395 case DeclSpec::TST_error:
1396 Result = Context.IntTy;
1397 declarator.setInvalidType(true);
1398 break;
1399 }
1400
1401 // FIXME: we want resulting declarations to be marked invalid, but claiming
1402 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1403 // a null type.
1404 if (Result->containsErrors())
1405 declarator.setInvalidType();
1406
1407 if (S.getLangOpts().OpenCL) {
1408 const auto &OpenCLOptions = S.getOpenCLOptions();
1409 bool IsOpenCLC30Compatible =
1410 S.getLangOpts().getOpenCLCompatibleVersion() == 300;
1411 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1412 // support.
1413 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1414 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1415 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1416 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1417 // only when the optional feature is supported
1418 if ((Result->isImageType() || Result->isSamplerT()) &&
1419 (IsOpenCLC30Compatible &&
1420 !OpenCLOptions.isSupported(Ext: "__opencl_c_images", LO: S.getLangOpts()))) {
1421 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_opencl_requires_extension)
1422 << 0 << Result << "__opencl_c_images";
1423 declarator.setInvalidType();
1424 } else if (Result->isOCLImage3dWOType() &&
1425 !OpenCLOptions.isSupported(Ext: "cl_khr_3d_image_writes",
1426 LO: S.getLangOpts())) {
1427 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_opencl_requires_extension)
1428 << 0 << Result
1429 << (IsOpenCLC30Compatible
1430 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1431 : "cl_khr_3d_image_writes");
1432 declarator.setInvalidType();
1433 }
1434 }
1435
1436 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1437 DS.getTypeSpecType() == DeclSpec::TST_fract;
1438
1439 // Only fixed point types can be saturated
1440 if (DS.isTypeSpecSat() && !IsFixedPointType)
1441 S.Diag(Loc: DS.getTypeSpecSatLoc(), DiagID: diag::err_invalid_saturation_spec)
1442 << DS.getSpecifierName(T: DS.getTypeSpecType(),
1443 Policy: Context.getPrintingPolicy());
1444
1445 // Handle complex types.
1446 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1447 if (S.getLangOpts().Freestanding)
1448 S.Diag(Loc: DS.getTypeSpecComplexLoc(), DiagID: diag::ext_freestanding_complex);
1449 Result = Context.getComplexType(T: Result);
1450 } else if (DS.isTypeAltiVecVector()) {
1451 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(T: Result));
1452 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1453 VectorKind VecKind = VectorKind::AltiVecVector;
1454 if (DS.isTypeAltiVecPixel())
1455 VecKind = VectorKind::AltiVecPixel;
1456 else if (DS.isTypeAltiVecBool())
1457 VecKind = VectorKind::AltiVecBool;
1458 Result = Context.getVectorType(VectorType: Result, NumElts: 128/typeSize, VecKind);
1459 }
1460
1461 // _Imaginary was a feature of C99 through C23 but was never supported in
1462 // Clang. The feature was removed in C2y, but we retain the unsupported
1463 // diagnostic for an improved user experience.
1464 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1465 S.Diag(Loc: DS.getTypeSpecComplexLoc(), DiagID: diag::err_imaginary_not_supported);
1466
1467 // Before we process any type attributes, synthesize a block literal
1468 // function declarator if necessary.
1469 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1470 maybeSynthesizeBlockSignature(state, declSpecType: Result);
1471
1472 // Apply any type attributes from the decl spec. This may cause the
1473 // list of type attributes to be temporarily saved while the type
1474 // attributes are pushed around.
1475 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1476 if (!DS.isTypeSpecPipe()) {
1477 // We also apply declaration attributes that "slide" to the decl spec.
1478 // Ordering can be important for attributes. The decalaration attributes
1479 // come syntactically before the decl spec attributes, so we process them
1480 // in that order.
1481 ParsedAttributesView SlidingAttrs;
1482 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1483 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1484 SlidingAttrs.addAtEnd(newAttr: &AL);
1485
1486 // For standard syntax attributes, which would normally appertain to the
1487 // declaration here, suggest moving them to the type instead. But only
1488 // do this for our own vendor attributes; moving other vendors'
1489 // attributes might hurt portability.
1490 // There's one special case that we need to deal with here: The
1491 // `MatrixType` attribute may only be used in a typedef declaration. If
1492 // it's being used anywhere else, don't output the warning as
1493 // ProcessDeclAttributes() will output an error anyway.
1494 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1495 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1496 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)) {
1497 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_type_attribute_deprecated_on_decl)
1498 << AL;
1499 }
1500 }
1501 }
1502 // During this call to processTypeAttrs(),
1503 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1504 // reference to the DeclSpec attributes, rather than the declaration
1505 // attributes. However, this doesn't matter, as getCurrentAttributes()
1506 // is only called when distributing attributes from one attribute list
1507 // to another. Declaration attributes are always C++11 attributes, and these
1508 // are never distributed.
1509 processTypeAttrs(state, type&: Result, TAL: TAL_DeclSpec, attrs: SlidingAttrs);
1510 processTypeAttrs(state, type&: Result, TAL: TAL_DeclSpec, attrs: DS.getAttributes());
1511 }
1512
1513 // Apply const/volatile/restrict qualifiers to T.
1514 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1515 // Warn about CV qualifiers on function types.
1516 // C99 6.7.3p8:
1517 // If the specification of a function type includes any type qualifiers,
1518 // the behavior is undefined.
1519 // C2y changed this behavior to be implementation-defined. Clang defines
1520 // the behavior in all cases to ignore the qualifier, as in C++.
1521 // C++11 [dcl.fct]p7:
1522 // The effect of a cv-qualifier-seq in a function declarator is not the
1523 // same as adding cv-qualification on top of the function type. In the
1524 // latter case, the cv-qualifiers are ignored.
1525 if (Result->isFunctionType()) {
1526 unsigned DiagId = diag::warn_typecheck_function_qualifiers_ignored;
1527 if (!S.getLangOpts().CPlusPlus && !S.getLangOpts().C2y)
1528 DiagId = diag::ext_typecheck_function_qualifiers_unspecified;
1529 diagnoseAndRemoveTypeQualifiers(
1530 S, DS, TypeQuals, TypeSoFar: Result, RemoveTQs: DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1531 DiagID: DiagId);
1532 // No diagnostic for 'restrict' or '_Atomic' applied to a
1533 // function type; we'll diagnose those later, in BuildQualifiedType.
1534 }
1535
1536 // C++11 [dcl.ref]p1:
1537 // Cv-qualified references are ill-formed except when the
1538 // cv-qualifiers are introduced through the use of a typedef-name
1539 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1540 //
1541 // There don't appear to be any other contexts in which a cv-qualified
1542 // reference type could be formed, so the 'ill-formed' clause here appears
1543 // to never happen.
1544 if (TypeQuals && Result->isReferenceType()) {
1545 diagnoseAndRemoveTypeQualifiers(
1546 S, DS, TypeQuals, TypeSoFar: Result,
1547 RemoveTQs: DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1548 DiagID: diag::warn_typecheck_reference_qualifiers);
1549 }
1550
1551 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1552 // than once in the same specifier-list or qualifier-list, either directly
1553 // or via one or more typedefs."
1554 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1555 && TypeQuals & Result.getCVRQualifiers()) {
1556 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1557 S.Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_duplicate_declspec)
1558 << "const";
1559 }
1560
1561 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1562 S.Diag(Loc: DS.getVolatileSpecLoc(), DiagID: diag::ext_duplicate_declspec)
1563 << "volatile";
1564 }
1565
1566 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1567 // produce a warning in this case.
1568 }
1569
1570 QualType Qualified = S.BuildQualifiedType(T: Result, Loc: DeclLoc, CVRA: TypeQuals, DS: &DS);
1571
1572 // If adding qualifiers fails, just use the unqualified type.
1573 if (Qualified.isNull())
1574 declarator.setInvalidType(true);
1575 else
1576 Result = Qualified;
1577 }
1578
1579 // Check for __ob_wrap and __ob_trap
1580 if (DS.isOverflowBehaviorSpecified() &&
1581 S.getLangOpts().OverflowBehaviorTypes) {
1582 if (!Result->isIntegerType()) {
1583 SourceLocation Loc = DS.getOverflowBehaviorLoc();
1584 StringRef SpecifierName =
1585 DeclSpec::getSpecifierName(S: DS.getOverflowBehaviorState());
1586 S.Diag(Loc, DiagID: diag::err_overflow_behavior_non_integer_type)
1587 << SpecifierName << Result.getAsString() << 1;
1588 } else {
1589 OverflowBehaviorType::OverflowBehaviorKind Kind =
1590 DS.isWrapSpecified()
1591 ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
1592 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
1593 Result = state.getOverflowBehaviorType(Kind, UnderlyingType: Result);
1594 }
1595 }
1596
1597 if (S.getLangOpts().HLSL)
1598 Result = S.HLSL().ProcessResourceTypeAttributes(Wrapped: Result);
1599
1600 assert(!Result.isNull() && "This function should not return a null type");
1601 return Result;
1602}
1603
1604static std::string getPrintableNameForEntity(DeclarationName Entity) {
1605 if (Entity)
1606 return Entity.getAsString();
1607
1608 return "type name";
1609}
1610
1611static bool isDependentOrGNUAutoType(QualType T) {
1612 if (T->isDependentType())
1613 return true;
1614
1615 const auto *AT = dyn_cast<AutoType>(Val&: T);
1616 return AT && AT->isGNUAutoType();
1617}
1618
1619QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1620 Qualifiers Qs, const DeclSpec *DS) {
1621 if (T.isNull())
1622 return QualType();
1623
1624 // Ignore any attempt to form a cv-qualified reference.
1625 if (T->isReferenceType()) {
1626 Qs.removeConst();
1627 Qs.removeVolatile();
1628 }
1629
1630 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1631 // object or incomplete types shall not be restrict-qualified."
1632 if (Qs.hasRestrict()) {
1633 unsigned DiagID = 0;
1634 QualType EltTy = Context.getBaseElementType(QT: T);
1635
1636 if (EltTy->isAnyPointerType() || EltTy->isReferenceType() ||
1637 EltTy->isMemberPointerType()) {
1638
1639 if (const auto *PTy = EltTy->getAs<MemberPointerType>())
1640 EltTy = PTy->getPointeeType();
1641 else
1642 EltTy = EltTy->getPointeeType();
1643
1644 // If we have a pointer or reference, the pointee must have an object
1645 // incomplete type.
1646 if (!EltTy->isIncompleteOrObjectType())
1647 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1648
1649 } else if (!isDependentOrGNUAutoType(T)) {
1650 // For an __auto_type variable, we may not have seen the initializer yet
1651 // and so have no idea whether the underlying type is a pointer type or
1652 // not.
1653 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1654 EltTy = T;
1655 }
1656
1657 Loc = DS ? DS->getRestrictSpecLoc() : Loc;
1658 if (DiagID) {
1659 Diag(Loc, DiagID) << EltTy;
1660 Qs.removeRestrict();
1661 } else {
1662 if (T->isArrayType())
1663 Diag(Loc, DiagID: getLangOpts().C23
1664 ? diag::warn_c23_compat_restrict_on_array_of_pointers
1665 : diag::ext_restrict_on_array_of_pointers_c23);
1666 }
1667 }
1668
1669 return Context.getQualifiedType(T, Qs);
1670}
1671
1672QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1673 unsigned CVRAU, const DeclSpec *DS) {
1674 if (T.isNull())
1675 return QualType();
1676
1677 // Ignore any attempt to form a cv-qualified reference.
1678 if (T->isReferenceType())
1679 CVRAU &=
1680 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1681
1682 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1683 // TQ_unaligned;
1684 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1685
1686 // C11 6.7.3/5:
1687 // If the same qualifier appears more than once in the same
1688 // specifier-qualifier-list, either directly or via one or more typedefs,
1689 // the behavior is the same as if it appeared only once.
1690 //
1691 // It's not specified what happens when the _Atomic qualifier is applied to
1692 // a type specified with the _Atomic specifier, but we assume that this
1693 // should be treated as if the _Atomic qualifier appeared multiple times.
1694 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1695 // C11 6.7.3/5:
1696 // If other qualifiers appear along with the _Atomic qualifier in a
1697 // specifier-qualifier-list, the resulting type is the so-qualified
1698 // atomic type.
1699 //
1700 // Don't need to worry about array types here, since _Atomic can't be
1701 // applied to such types.
1702 SplitQualType Split = T.getSplitUnqualifiedType();
1703 T = BuildAtomicType(T: QualType(Split.Ty, 0),
1704 Loc: DS ? DS->getAtomicSpecLoc() : Loc);
1705 if (T.isNull())
1706 return T;
1707 Split.Quals.addCVRQualifiers(mask: CVR);
1708 return BuildQualifiedType(T, Loc, Qs: Split.Quals);
1709 }
1710
1711 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1712 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1713 return BuildQualifiedType(T, Loc, Qs: Q, DS);
1714}
1715
1716QualType Sema::BuildParenType(QualType T) {
1717 return Context.getParenType(NamedType: T);
1718}
1719
1720/// Given that we're building a pointer or reference to the given
1721static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1722 SourceLocation loc,
1723 bool isReference) {
1724 // Bail out if retention is unrequired or already specified.
1725 if (!type->isObjCLifetimeType() ||
1726 type.getObjCLifetime() != Qualifiers::OCL_None)
1727 return type;
1728
1729 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1730
1731 // If the object type is const-qualified, we can safely use
1732 // __unsafe_unretained. This is safe (because there are no read
1733 // barriers), and it'll be safe to coerce anything but __weak* to
1734 // the resulting type.
1735 if (type.isConstQualified()) {
1736 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1737
1738 // Otherwise, check whether the static type does not require
1739 // retaining. This currently only triggers for Class (possibly
1740 // protocol-qualifed, and arrays thereof).
1741 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1742 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1743
1744 // If we are in an unevaluated context, like sizeof, skip adding a
1745 // qualification.
1746 } else if (S.isUnevaluatedContext()) {
1747 return type;
1748
1749 // If that failed, give an error and recover using __strong. __strong
1750 // is the option most likely to prevent spurious second-order diagnostics,
1751 // like when binding a reference to a field.
1752 } else {
1753 // These types can show up in private ivars in system headers, so
1754 // we need this to not be an error in those cases. Instead we
1755 // want to delay.
1756 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1757 S.DelayedDiagnostics.add(
1758 diag: sema::DelayedDiagnostic::makeForbiddenType(loc,
1759 diagnostic: diag::err_arc_indirect_no_ownership, type, argument: isReference));
1760 } else {
1761 S.Diag(Loc: loc, DiagID: diag::err_arc_indirect_no_ownership) << type << isReference;
1762 }
1763 implicitLifetime = Qualifiers::OCL_Strong;
1764 }
1765 assert(implicitLifetime && "didn't infer any lifetime!");
1766
1767 Qualifiers qs;
1768 qs.addObjCLifetime(type: implicitLifetime);
1769 return S.Context.getQualifiedType(T: type, Qs: qs);
1770}
1771
1772static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1773 std::string Quals = FnTy->getMethodQuals().getAsString();
1774
1775 switch (FnTy->getRefQualifier()) {
1776 case RQ_None:
1777 break;
1778
1779 case RQ_LValue:
1780 if (!Quals.empty())
1781 Quals += ' ';
1782 Quals += '&';
1783 break;
1784
1785 case RQ_RValue:
1786 if (!Quals.empty())
1787 Quals += ' ';
1788 Quals += "&&";
1789 break;
1790 }
1791
1792 return Quals;
1793}
1794
1795namespace {
1796/// Kinds of declarator that cannot contain a qualified function type.
1797///
1798/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1799/// a function type with a cv-qualifier or a ref-qualifier can only appear
1800/// at the topmost level of a type.
1801///
1802/// Parens and member pointers are permitted. We don't diagnose array and
1803/// function declarators, because they don't allow function types at all.
1804///
1805/// The values of this enum are used in diagnostics.
1806enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1807} // end anonymous namespace
1808
1809/// Check whether the type T is a qualified function type, and if it is,
1810/// diagnose that it cannot be contained within the given kind of declarator.
1811static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1812 QualifiedFunctionKind QFK) {
1813 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1814 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1815 if (!FPT ||
1816 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1817 return false;
1818
1819 S.Diag(Loc, DiagID: diag::err_compound_qualified_function_type)
1820 << QFK << isa<FunctionType>(Val: T.IgnoreParens()) << T
1821 << getFunctionQualifiersAsString(FnTy: FPT);
1822 return true;
1823}
1824
1825bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
1826 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1827 if (!FPT ||
1828 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1829 return false;
1830
1831 Diag(Loc, DiagID: diag::err_qualified_function_typeid)
1832 << T << getFunctionQualifiersAsString(FnTy: FPT);
1833 return true;
1834}
1835
1836// Helper to deduce addr space of a pointee type in OpenCL mode.
1837static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
1838 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
1839 !PointeeType->isSamplerT() &&
1840 !PointeeType.hasAddressSpace())
1841 PointeeType = S.getASTContext().getAddrSpaceQualType(
1842 T: PointeeType, AddressSpace: S.getASTContext().getDefaultOpenCLPointeeAddrSpace());
1843 return PointeeType;
1844}
1845
1846QualType Sema::BuildPointerType(QualType T,
1847 SourceLocation Loc, DeclarationName Entity) {
1848 if (T->isReferenceType()) {
1849 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1850 Diag(Loc, DiagID: diag::err_illegal_decl_pointer_to_reference)
1851 << getPrintableNameForEntity(Entity) << T;
1852 return QualType();
1853 }
1854
1855 if (T->isFunctionType() && getLangOpts().OpenCL &&
1856 !getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
1857 LO: getLangOpts())) {
1858 Diag(Loc, DiagID: diag::err_opencl_function_pointer) << /*pointer*/ 0;
1859 return QualType();
1860 }
1861
1862 if (getLangOpts().HLSL && Loc.isValid()) {
1863 Diag(Loc, DiagID: diag::err_hlsl_pointers_unsupported) << 0;
1864 return QualType();
1865 }
1866
1867 if (checkQualifiedFunction(S&: *this, T, Loc, QFK: QFK_Pointer))
1868 return QualType();
1869
1870 if (T->isObjCObjectType())
1871 return Context.getObjCObjectPointerType(OIT: T);
1872
1873 // In ARC, it is forbidden to build pointers to unqualified pointers.
1874 if (getLangOpts().ObjCAutoRefCount)
1875 T = inferARCLifetimeForPointee(S&: *this, type: T, loc: Loc, /*reference*/ isReference: false);
1876
1877 if (getLangOpts().OpenCL)
1878 T = deduceOpenCLPointeeAddrSpace(S&: *this, PointeeType: T);
1879
1880 // In WebAssembly, pointers to reference types and pointers to tables are
1881 // illegal.
1882 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
1883 if (T.isWebAssemblyReferenceType()) {
1884 Diag(Loc, DiagID: diag::err_wasm_reference_pr) << 0;
1885 return QualType();
1886 }
1887
1888 // We need to desugar the type here in case T is a ParenType.
1889 if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
1890 Diag(Loc, DiagID: diag::err_wasm_table_pr) << 0;
1891 return QualType();
1892 }
1893 }
1894
1895 // Build the pointer type.
1896 return Context.getPointerType(T);
1897}
1898
1899QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1900 SourceLocation Loc,
1901 DeclarationName Entity) {
1902 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1903 "Unresolved overloaded function type");
1904
1905 // C++0x [dcl.ref]p6:
1906 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1907 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1908 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1909 // the type "lvalue reference to T", while an attempt to create the type
1910 // "rvalue reference to cv TR" creates the type TR.
1911 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1912
1913 // C++ [dcl.ref]p4: There shall be no references to references.
1914 //
1915 // According to C++ DR 106, references to references are only
1916 // diagnosed when they are written directly (e.g., "int & &"),
1917 // but not when they happen via a typedef:
1918 //
1919 // typedef int& intref;
1920 // typedef intref& intref2;
1921 //
1922 // Parser::ParseDeclaratorInternal diagnoses the case where
1923 // references are written directly; here, we handle the
1924 // collapsing of references-to-references as described in C++0x.
1925 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1926
1927 // C++ [dcl.ref]p1:
1928 // A declarator that specifies the type "reference to cv void"
1929 // is ill-formed.
1930 if (T->isVoidType()) {
1931 Diag(Loc, DiagID: diag::err_reference_to_void);
1932 return QualType();
1933 }
1934
1935 if (getLangOpts().HLSL && Loc.isValid()) {
1936 Diag(Loc, DiagID: diag::err_hlsl_pointers_unsupported) << 1;
1937 return QualType();
1938 }
1939
1940 if (checkQualifiedFunction(S&: *this, T, Loc, QFK: QFK_Reference))
1941 return QualType();
1942
1943 if (T->isFunctionType() && getLangOpts().OpenCL &&
1944 !getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
1945 LO: getLangOpts())) {
1946 Diag(Loc, DiagID: diag::err_opencl_function_pointer) << /*reference*/ 1;
1947 return QualType();
1948 }
1949
1950 // In ARC, it is forbidden to build references to unqualified pointers.
1951 if (getLangOpts().ObjCAutoRefCount)
1952 T = inferARCLifetimeForPointee(S&: *this, type: T, loc: Loc, /*reference*/ isReference: true);
1953
1954 if (getLangOpts().OpenCL)
1955 T = deduceOpenCLPointeeAddrSpace(S&: *this, PointeeType: T);
1956
1957 // In WebAssembly, references to reference types and tables are illegal.
1958 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
1959 T.isWebAssemblyReferenceType()) {
1960 Diag(Loc, DiagID: diag::err_wasm_reference_pr) << 1;
1961 return QualType();
1962 }
1963 if (T->isWebAssemblyTableType()) {
1964 Diag(Loc, DiagID: diag::err_wasm_table_pr) << 1;
1965 return QualType();
1966 }
1967
1968 // Handle restrict on references.
1969 if (LValueRef)
1970 return Context.getLValueReferenceType(T, SpelledAsLValue);
1971 return Context.getRValueReferenceType(T);
1972}
1973
1974QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
1975 return Context.getReadPipeType(T);
1976}
1977
1978QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
1979 return Context.getWritePipeType(T);
1980}
1981
1982QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
1983 SourceLocation Loc) {
1984 if (BitWidth->isInstantiationDependent())
1985 return Context.getDependentBitIntType(Unsigned: IsUnsigned, BitsExpr: BitWidth);
1986
1987 llvm::APSInt Bits(32);
1988 ExprResult ICE = VerifyIntegerConstantExpression(
1989 E: BitWidth, Result: &Bits, /*FIXME*/ CanFold: AllowFoldKind::Allow);
1990
1991 if (ICE.isInvalid())
1992 return QualType();
1993
1994 size_t NumBits = Bits.getZExtValue();
1995 if (!IsUnsigned && NumBits < 2) {
1996 Diag(Loc, DiagID: diag::err_bit_int_bad_size) << 0;
1997 return QualType();
1998 }
1999
2000 if (IsUnsigned && NumBits < 1) {
2001 Diag(Loc, DiagID: diag::err_bit_int_bad_size) << 1;
2002 return QualType();
2003 }
2004
2005 const TargetInfo &TI = getASTContext().getTargetInfo();
2006 if (NumBits > TI.getMaxBitIntWidth()) {
2007 Diag(Loc, DiagID: diag::err_bit_int_max_size)
2008 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2009 return QualType();
2010 }
2011
2012 return Context.getBitIntType(Unsigned: IsUnsigned, NumBits);
2013}
2014
2015/// Check whether the specified array bound can be evaluated using the relevant
2016/// language rules. If so, returns the possibly-converted expression and sets
2017/// SizeVal to the size. If not, but the expression might be a VLA bound,
2018/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2019/// ExprError().
2020static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2021 llvm::APSInt &SizeVal, unsigned VLADiag,
2022 bool VLAIsError) {
2023 if (S.getLangOpts().CPlusPlus14 &&
2024 (VLAIsError ||
2025 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2026 // C++14 [dcl.array]p1:
2027 // The constant-expression shall be a converted constant expression of
2028 // type std::size_t.
2029 //
2030 // Don't apply this rule if we might be forming a VLA: in that case, we
2031 // allow non-constant expressions and constant-folding. We only need to use
2032 // the converted constant expression rules (to properly convert the source)
2033 // when the source expression is of class type.
2034 return S.CheckConvertedConstantExpression(
2035 From: ArraySize, T: S.Context.getSizeType(), Value&: SizeVal, CCE: CCEKind::ArrayBound);
2036 }
2037
2038 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2039 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2040 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2041 public:
2042 unsigned VLADiag;
2043 bool VLAIsError;
2044 bool IsVLA = false;
2045
2046 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2047 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2048
2049 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2050 QualType T) override {
2051 return S.Diag(Loc, DiagID: diag::err_array_size_non_int) << T;
2052 }
2053
2054 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2055 SourceLocation Loc) override {
2056 IsVLA = !VLAIsError;
2057 return S.Diag(Loc, DiagID: VLADiag);
2058 }
2059
2060 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2061 SourceLocation Loc) override {
2062 return S.Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
2063 }
2064 } Diagnoser(VLADiag, VLAIsError);
2065
2066 ExprResult R =
2067 S.VerifyIntegerConstantExpression(E: ArraySize, Result: &SizeVal, Diagnoser);
2068 if (Diagnoser.IsVLA)
2069 return ExprResult();
2070 return R;
2071}
2072
2073bool Sema::checkArrayElementAlignment(QualType EltTy, SourceLocation Loc) {
2074 EltTy = Context.getBaseElementType(QT: EltTy);
2075 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2076 EltTy->isUndeducedType())
2077 return true;
2078
2079 CharUnits Size = Context.getTypeSizeInChars(T: EltTy);
2080 CharUnits Alignment = Context.getTypeAlignInChars(T: EltTy);
2081
2082 if (Size.isMultipleOf(N: Alignment))
2083 return true;
2084
2085 Diag(Loc, DiagID: diag::err_array_element_alignment)
2086 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2087 return false;
2088}
2089
2090QualType Sema::BuildArrayType(QualType T, ArraySizeModifier ASM,
2091 Expr *ArraySize, unsigned Quals,
2092 SourceRange Brackets, DeclarationName Entity) {
2093
2094 SourceLocation Loc = Brackets.getBegin();
2095 if (getLangOpts().CPlusPlus) {
2096 // C++ [dcl.array]p1:
2097 // T is called the array element type; this type shall not be a reference
2098 // type, the (possibly cv-qualified) type void, a function type or an
2099 // abstract class type.
2100 //
2101 // C++ [dcl.array]p3:
2102 // When several "array of" specifications are adjacent, [...] only the
2103 // first of the constant expressions that specify the bounds of the arrays
2104 // may be omitted.
2105 //
2106 // Note: function types are handled in the common path with C.
2107 if (T->isReferenceType()) {
2108 Diag(Loc, DiagID: diag::err_illegal_decl_array_of_references)
2109 << getPrintableNameForEntity(Entity) << T;
2110 return QualType();
2111 }
2112
2113 if (T->isVoidType() || T->isIncompleteArrayType()) {
2114 Diag(Loc, DiagID: diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2115 return QualType();
2116 }
2117
2118 if (RequireNonAbstractType(Loc: Brackets.getBegin(), T,
2119 DiagID: diag::err_array_of_abstract_type))
2120 return QualType();
2121
2122 // Mentioning a member pointer type for an array type causes us to lock in
2123 // an inheritance model, even if it's inside an unused typedef.
2124 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2125 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2126 if (!MPTy->getQualifier().isDependent())
2127 (void)isCompleteType(Loc, T);
2128
2129 } else {
2130 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2131 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2132 if (!T.isWebAssemblyReferenceType() &&
2133 RequireCompleteSizedType(Loc, T,
2134 DiagID: diag::err_array_incomplete_or_sizeless_type))
2135 return QualType();
2136 }
2137
2138 // Multi-dimensional arrays of WebAssembly references are not allowed.
2139 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2140 const auto *ATy = dyn_cast<ArrayType>(Val&: T);
2141 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2142 Diag(Loc, DiagID: diag::err_wasm_reftype_multidimensional_array);
2143 return QualType();
2144 }
2145 }
2146
2147 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2148 Diag(Loc, DiagID: diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2149 return QualType();
2150 }
2151
2152 if (T->isFunctionType()) {
2153 Diag(Loc, DiagID: diag::err_illegal_decl_array_of_functions)
2154 << getPrintableNameForEntity(Entity) << T;
2155 return QualType();
2156 }
2157
2158 if (const auto *RD = T->getAsRecordDecl()) {
2159 // If the element type is a struct or union that contains a variadic
2160 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2161 if (RD->hasFlexibleArrayMember())
2162 Diag(Loc, DiagID: diag::ext_flexible_array_in_array) << T;
2163 } else if (T->isObjCObjectType()) {
2164 Diag(Loc, DiagID: diag::err_objc_array_of_interfaces) << T;
2165 return QualType();
2166 }
2167
2168 if (!checkArrayElementAlignment(EltTy: T, Loc))
2169 return QualType();
2170
2171 // Do placeholder conversions on the array size expression.
2172 if (ArraySize && ArraySize->hasPlaceholderType()) {
2173 ExprResult Result = CheckPlaceholderExpr(E: ArraySize);
2174 if (Result.isInvalid()) return QualType();
2175 ArraySize = Result.get();
2176 }
2177
2178 // Do lvalue-to-rvalue conversions on the array size expression.
2179 if (ArraySize && !ArraySize->isPRValue()) {
2180 ExprResult Result = DefaultLvalueConversion(E: ArraySize);
2181 if (Result.isInvalid())
2182 return QualType();
2183
2184 ArraySize = Result.get();
2185 }
2186
2187 // C99 6.7.5.2p1: The size expression shall have integer type.
2188 // C++11 allows contextual conversions to such types.
2189 if (!getLangOpts().CPlusPlus11 &&
2190 ArraySize && !ArraySize->isTypeDependent() &&
2191 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2192 Diag(Loc: ArraySize->getBeginLoc(), DiagID: diag::err_array_size_non_int)
2193 << ArraySize->getType() << ArraySize->getSourceRange();
2194 return QualType();
2195 }
2196
2197 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2198 if (!ArraySize)
2199 return false;
2200
2201 // If the array size expression is a conditional expression whose branches
2202 // are both integer constant expressions, one negative and one positive,
2203 // then it's assumed to be like an old-style static assertion. e.g.,
2204 // int old_style_assert[expr ? 1 : -1];
2205 // We will accept any integer constant expressions instead of assuming the
2206 // values 1 and -1 are always used.
2207 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2208 Val: ArraySize->IgnoreParenImpCasts())) {
2209 std::optional<llvm::APSInt> LHS =
2210 CondExpr->getLHS()->getIntegerConstantExpr(Ctx: Context);
2211 std::optional<llvm::APSInt> RHS =
2212 CondExpr->getRHS()->getIntegerConstantExpr(Ctx: Context);
2213 return LHS && RHS && LHS->isNegative() != RHS->isNegative();
2214 }
2215 return false;
2216 };
2217
2218 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2219 unsigned VLADiag;
2220 bool VLAIsError;
2221 if (getLangOpts().OpenCL) {
2222 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2223 VLADiag = diag::err_opencl_vla;
2224 VLAIsError = true;
2225 } else if (getLangOpts().C99) {
2226 VLADiag = diag::warn_vla_used;
2227 VLAIsError = false;
2228 } else if (isSFINAEContext()) {
2229 VLADiag = diag::err_vla_in_sfinae;
2230 VLAIsError = true;
2231 } else if (getLangOpts().OpenMP && OpenMP().isInOpenMPTaskUntiedContext()) {
2232 VLADiag = diag::err_openmp_vla_in_task_untied;
2233 VLAIsError = true;
2234 } else if (getLangOpts().CPlusPlus) {
2235 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context))
2236 VLADiag = getLangOpts().GNUMode
2237 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2238 : diag::ext_vla_cxx_static_assert;
2239 else
2240 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode
2241 : diag::ext_vla_cxx;
2242 VLAIsError = false;
2243 } else {
2244 VLADiag = diag::ext_vla;
2245 VLAIsError = false;
2246 }
2247
2248 llvm::APSInt ConstVal(Context.getTypeSize(T: Context.getSizeType()));
2249 if (!ArraySize) {
2250 if (ASM == ArraySizeModifier::Star) {
2251 Diag(Loc, DiagID: VLADiag);
2252 if (VLAIsError)
2253 return QualType();
2254
2255 T = Context.getVariableArrayType(EltTy: T, NumElts: nullptr, ASM, IndexTypeQuals: Quals);
2256 } else {
2257 T = Context.getIncompleteArrayType(EltTy: T, ASM, IndexTypeQuals: Quals);
2258 }
2259 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2260 T = Context.getDependentSizedArrayType(EltTy: T, NumElts: ArraySize, ASM, IndexTypeQuals: Quals);
2261 } else {
2262 ExprResult R =
2263 checkArraySize(S&: *this, ArraySize, SizeVal&: ConstVal, VLADiag, VLAIsError);
2264 if (R.isInvalid())
2265 return QualType();
2266
2267 if (!R.isUsable()) {
2268 // C99: an array with a non-ICE size is a VLA. We accept any expression
2269 // that we can fold to a non-zero positive value as a non-VLA as an
2270 // extension.
2271 T = Context.getVariableArrayType(EltTy: T, NumElts: ArraySize, ASM, IndexTypeQuals: Quals);
2272 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2273 !T->isConstantSizeType()) {
2274 // C99: an array with an element type that has a non-constant-size is a
2275 // VLA.
2276 // FIXME: Add a note to explain why this isn't a VLA.
2277 Diag(Loc, DiagID: VLADiag);
2278 if (VLAIsError)
2279 return QualType();
2280 T = Context.getVariableArrayType(EltTy: T, NumElts: ArraySize, ASM, IndexTypeQuals: Quals);
2281 } else {
2282 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2283 // have a value greater than zero.
2284 // In C++, this follows from narrowing conversions being disallowed.
2285 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2286 if (Entity)
2287 Diag(Loc: ArraySize->getBeginLoc(), DiagID: diag::err_decl_negative_array_size)
2288 << getPrintableNameForEntity(Entity)
2289 << ArraySize->getSourceRange();
2290 else
2291 Diag(Loc: ArraySize->getBeginLoc(),
2292 DiagID: diag::err_typecheck_negative_array_size)
2293 << ArraySize->getSourceRange();
2294 return QualType();
2295 }
2296 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2297 if (getLangOpts().OpenCL) {
2298 Diag(Loc: ArraySize->getBeginLoc(), DiagID: diag::err_typecheck_zero_array_size)
2299 << 3 << ArraySize->getSourceRange();
2300 return QualType();
2301 }
2302
2303 // GCC accepts zero sized static arrays. We allow them when
2304 // we're not in a SFINAE context.
2305 Diag(Loc: ArraySize->getBeginLoc(),
2306 DiagID: isSFINAEContext() ? diag::err_typecheck_zero_array_size
2307 : diag::ext_typecheck_zero_array_size)
2308 << 0 << ArraySize->getSourceRange();
2309 if (isSFINAEContext())
2310 return QualType();
2311 }
2312
2313 // Is the array too large?
2314 unsigned ActiveSizeBits =
2315 (!T->isDependentType() && !T->isVariablyModifiedType() &&
2316 !T->isIncompleteType() && !T->isUndeducedType())
2317 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: T, NumElements: ConstVal)
2318 : ConstVal.getActiveBits();
2319 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2320 Diag(Loc: ArraySize->getBeginLoc(), DiagID: diag::err_array_too_large)
2321 << toString(I: ConstVal, Radix: 10, Signed: ConstVal.isSigned(),
2322 /*formatAsCLiteral=*/false, /*UpperCase=*/false,
2323 /*InsertSeparators=*/true)
2324 << ArraySize->getSourceRange();
2325 return QualType();
2326 }
2327
2328 T = Context.getConstantArrayType(EltTy: T, ArySize: ConstVal, SizeExpr: ArraySize, ASM, IndexTypeQuals: Quals);
2329 }
2330 }
2331
2332 if (T->isVariableArrayType()) {
2333 if (!Context.getTargetInfo().isVLASupported()) {
2334 // CUDA device code and some other targets don't support VLAs.
2335 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2336 targetDiag(Loc,
2337 DiagID: IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2338 << (IsCUDADevice ? llvm::to_underlying(E: CUDA().CurrentTarget()) : 0);
2339 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2340 // VLAs are supported on this target, but we may need to do delayed
2341 // checking that the VLA is not being used within a coroutine.
2342 FSI->setHasVLA(Loc);
2343 }
2344 }
2345
2346 // If this is not C99, diagnose array size modifiers on non-VLAs.
2347 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2348 (ASM != ArraySizeModifier::Normal || Quals != 0)) {
2349 Diag(Loc, DiagID: getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2350 : diag::ext_c99_array_usage)
2351 << ASM;
2352 }
2353
2354 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2355 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2356 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2357 if (getLangOpts().OpenCL) {
2358 const QualType ArrType = Context.getBaseElementType(QT: T);
2359 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2360 ArrType->isSamplerT() || ArrType->isImageType()) {
2361 Diag(Loc, DiagID: diag::err_opencl_invalid_type_array) << ArrType;
2362 return QualType();
2363 }
2364 }
2365
2366 return T;
2367}
2368
2369static bool CheckBitIntElementType(Sema &S, SourceLocation AttrLoc,
2370 const BitIntType *BIT,
2371 bool ForMatrixType = false) {
2372 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2373 unsigned NumBits = BIT->getNumBits();
2374 if (!llvm::isPowerOf2_32(Value: NumBits))
2375 return S.Diag(Loc: AttrLoc, DiagID: diag::err_attribute_invalid_bitint_vector_type)
2376 << ForMatrixType;
2377 return false;
2378}
2379
2380QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2381 SourceLocation AttrLoc) {
2382 // The base type must be integer (not Boolean or enumeration) or float, and
2383 // can't already be a vector.
2384 if ((!CurType->isDependentType() &&
2385 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2386 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2387 !CurType->isBitIntType()) ||
2388 CurType->isArrayType()) {
2389 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_invalid_vector_type) << CurType;
2390 return QualType();
2391 }
2392
2393 if (const auto *BIT = CurType->getAs<BitIntType>();
2394 BIT && CheckBitIntElementType(S&: *this, AttrLoc, BIT))
2395 return QualType();
2396
2397 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2398 return Context.getDependentVectorType(VectorType: CurType, SizeExpr, AttrLoc,
2399 VecKind: VectorKind::Generic);
2400
2401 std::optional<llvm::APSInt> VecSize =
2402 SizeExpr->getIntegerConstantExpr(Ctx: Context);
2403 if (!VecSize) {
2404 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type)
2405 << "vector_size" << AANT_ArgumentIntegerConstant
2406 << SizeExpr->getSourceRange();
2407 return QualType();
2408 }
2409
2410 if (VecSize->isNegative()) {
2411 Diag(Loc: SizeExpr->getExprLoc(), DiagID: diag::err_attribute_vec_negative_size);
2412 return QualType();
2413 }
2414
2415 if (CurType->isDependentType())
2416 return Context.getDependentVectorType(VectorType: CurType, SizeExpr, AttrLoc,
2417 VecKind: VectorKind::Generic);
2418
2419 // vecSize is specified in bytes - convert to bits.
2420 if (!VecSize->isIntN(N: 61)) {
2421 // Bit size will overflow uint64.
2422 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_size_too_large)
2423 << SizeExpr->getSourceRange() << "vector";
2424 return QualType();
2425 }
2426 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2427 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(T: CurType));
2428
2429 if (VectorSizeBits == 0) {
2430 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_zero_size)
2431 << SizeExpr->getSourceRange() << "vector";
2432 return QualType();
2433 }
2434
2435 if (!TypeSize || VectorSizeBits % TypeSize) {
2436 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_invalid_size)
2437 << SizeExpr->getSourceRange();
2438 return QualType();
2439 }
2440
2441 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2442 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_size_too_large)
2443 << SizeExpr->getSourceRange() << "vector";
2444 return QualType();
2445 }
2446
2447 return Context.getVectorType(VectorType: CurType, NumElts: VectorSizeBits / TypeSize,
2448 VecKind: VectorKind::Generic);
2449}
2450
2451QualType Sema::BuildExtVectorType(QualType T, Expr *SizeExpr,
2452 SourceLocation AttrLoc) {
2453 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2454 // in conjunction with complex types (pointers, arrays, functions, etc.).
2455 //
2456 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2457 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2458 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2459 // of bool aren't allowed.
2460 //
2461 // We explicitly allow bool elements in ext_vector_type for C/C++.
2462 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2463 if ((!T->isDependentType() && !T->isIntegerType() &&
2464 !T->isRealFloatingType()) ||
2465 (IsNoBoolVecLang && T->isBooleanType())) {
2466 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_invalid_vector_type) << T;
2467 return QualType();
2468 }
2469
2470 if (const auto *BIT = T->getAs<BitIntType>();
2471 BIT && CheckBitIntElementType(S&: *this, AttrLoc, BIT))
2472 return QualType();
2473
2474 if (!SizeExpr->isTypeDependent() && !SizeExpr->isValueDependent()) {
2475 std::optional<llvm::APSInt> VecSize =
2476 SizeExpr->getIntegerConstantExpr(Ctx: Context);
2477 if (!VecSize) {
2478 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type)
2479 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2480 << SizeExpr->getSourceRange();
2481 return QualType();
2482 }
2483
2484 if (VecSize->isNegative()) {
2485 Diag(Loc: SizeExpr->getExprLoc(), DiagID: diag::err_attribute_vec_negative_size);
2486 return QualType();
2487 }
2488
2489 if (!VecSize->isIntN(N: 32)) {
2490 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_size_too_large)
2491 << SizeExpr->getSourceRange() << "vector";
2492 return QualType();
2493 }
2494 // Unlike gcc's vector_size attribute, the size is specified as the
2495 // number of elements, not the number of bytes.
2496 unsigned VectorSize = static_cast<unsigned>(VecSize->getZExtValue());
2497
2498 if (VectorSize == 0) {
2499 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_zero_size)
2500 << SizeExpr->getSourceRange() << "vector";
2501 return QualType();
2502 }
2503
2504 return Context.getExtVectorType(VectorType: T, NumElts: VectorSize);
2505 }
2506
2507 return Context.getDependentSizedExtVectorType(VectorType: T, SizeExpr, AttrLoc);
2508}
2509
2510QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2511 SourceLocation AttrLoc) {
2512 assert(Context.getLangOpts().MatrixTypes &&
2513 "Should never build a matrix type when it is disabled");
2514
2515 // Check element type, if it is not dependent.
2516 if (!ElementTy->isDependentType() &&
2517 !MatrixType::isValidElementType(T: ElementTy, LangOpts: getLangOpts())) {
2518 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_invalid_matrix_type) << ElementTy;
2519 return QualType();
2520 }
2521
2522 if (const auto *BIT = ElementTy->getAs<BitIntType>();
2523 BIT &&
2524 CheckBitIntElementType(S&: *this, AttrLoc, BIT, /*ForMatrixType=*/true))
2525 return QualType();
2526
2527 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2528 NumRows->isValueDependent() || NumCols->isValueDependent())
2529 return Context.getDependentSizedMatrixType(ElementType: ElementTy, RowExpr: NumRows, ColumnExpr: NumCols,
2530 AttrLoc);
2531
2532 std::optional<llvm::APSInt> ValueRows =
2533 NumRows->getIntegerConstantExpr(Ctx: Context);
2534 std::optional<llvm::APSInt> ValueColumns =
2535 NumCols->getIntegerConstantExpr(Ctx: Context);
2536
2537 auto const RowRange = NumRows->getSourceRange();
2538 auto const ColRange = NumCols->getSourceRange();
2539
2540 // Both are row and column expressions are invalid.
2541 if (!ValueRows && !ValueColumns) {
2542 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type)
2543 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2544 << ColRange;
2545 return QualType();
2546 }
2547
2548 // Only the row expression is invalid.
2549 if (!ValueRows) {
2550 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type)
2551 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2552 return QualType();
2553 }
2554
2555 // Only the column expression is invalid.
2556 if (!ValueColumns) {
2557 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type)
2558 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2559 return QualType();
2560 }
2561
2562 // Check the matrix dimensions.
2563 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2564 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2565 if (MatrixRows == 0 && MatrixColumns == 0) {
2566 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_zero_size)
2567 << "matrix" << RowRange << ColRange;
2568 return QualType();
2569 }
2570 if (MatrixRows == 0) {
2571 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_zero_size) << "matrix" << RowRange;
2572 return QualType();
2573 }
2574 if (MatrixColumns == 0) {
2575 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_zero_size) << "matrix" << ColRange;
2576 return QualType();
2577 }
2578 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension &&
2579 MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2580 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_size_too_large)
2581 << RowRange << ColRange << "matrix row and column";
2582 return QualType();
2583 }
2584 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension) {
2585 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_size_too_large)
2586 << RowRange << "matrix row";
2587 return QualType();
2588 }
2589 if (MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2590 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_size_too_large)
2591 << ColRange << "matrix column";
2592 return QualType();
2593 }
2594 return Context.getConstantMatrixType(ElementType: ElementTy, NumRows: MatrixRows, NumColumns: MatrixColumns);
2595}
2596
2597bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2598 if ((T->isArrayType() && !getLangOpts().allowArrayReturnTypes()) ||
2599 T->isFunctionType()) {
2600 Diag(Loc, DiagID: diag::err_func_returning_array_function)
2601 << T->isFunctionType() << T;
2602 return true;
2603 }
2604
2605 // Functions cannot return half FP.
2606 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2607 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2608 Diag(Loc, DiagID: diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2609 FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "*");
2610 return true;
2611 }
2612
2613 // Methods cannot return interface types. All ObjC objects are
2614 // passed by reference.
2615 if (T->isObjCObjectType()) {
2616 Diag(Loc, DiagID: diag::err_object_cannot_be_passed_returned_by_value)
2617 << 0 << T << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "*");
2618 return true;
2619 }
2620
2621 // __ptrauth is illegal on a function return type.
2622 if (T.getPointerAuth()) {
2623 Diag(Loc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 0;
2624 return true;
2625 }
2626
2627 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2628 T.hasNonTrivialToPrimitiveCopyCUnion())
2629 checkNonTrivialCUnion(QT: T, Loc, UseContext: NonTrivialCUnionContext::FunctionReturn,
2630 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
2631
2632 // C++2a [dcl.fct]p12:
2633 // A volatile-qualified return type is deprecated
2634 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2635 Diag(Loc, DiagID: diag::warn_deprecated_volatile_return) << T;
2636
2637 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2638 return true;
2639 return false;
2640}
2641
2642/// Check the extended parameter information. Most of the necessary
2643/// checking should occur when applying the parameter attribute; the
2644/// only other checks required are positional restrictions.
2645static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2646 const FunctionProtoType::ExtProtoInfo &EPI,
2647 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2648 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2649
2650 bool emittedError = false;
2651 auto actualCC = EPI.ExtInfo.getCC();
2652 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2653 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2654 bool isCompatible =
2655 (required == RequiredCC::OnlySwift)
2656 ? (actualCC == CC_Swift)
2657 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2658 if (isCompatible || emittedError)
2659 return;
2660 S.Diag(Loc: getParamLoc(paramIndex), DiagID: diag::err_swift_param_attr_not_swiftcall)
2661 << getParameterABISpelling(kind: EPI.ExtParameterInfos[paramIndex].getABI())
2662 << (required == RequiredCC::OnlySwift);
2663 emittedError = true;
2664 };
2665 for (size_t paramIndex = 0, numParams = paramTypes.size();
2666 paramIndex != numParams; ++paramIndex) {
2667 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2668 // Nothing interesting to check for orindary-ABI parameters.
2669 case ParameterABI::Ordinary:
2670 case ParameterABI::HLSLOut:
2671 case ParameterABI::HLSLInOut:
2672 continue;
2673
2674 // swift_indirect_result parameters must be a prefix of the function
2675 // arguments.
2676 case ParameterABI::SwiftIndirectResult:
2677 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2678 if (paramIndex != 0 &&
2679 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2680 != ParameterABI::SwiftIndirectResult) {
2681 S.Diag(Loc: getParamLoc(paramIndex),
2682 DiagID: diag::err_swift_indirect_result_not_first);
2683 }
2684 continue;
2685
2686 case ParameterABI::SwiftContext:
2687 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2688 continue;
2689
2690 // SwiftAsyncContext is not limited to swiftasynccall functions.
2691 case ParameterABI::SwiftAsyncContext:
2692 continue;
2693
2694 // swift_error parameters must be preceded by a swift_context parameter.
2695 case ParameterABI::SwiftErrorResult:
2696 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2697 if (paramIndex == 0 ||
2698 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2699 ParameterABI::SwiftContext) {
2700 S.Diag(Loc: getParamLoc(paramIndex),
2701 DiagID: diag::err_swift_error_result_not_after_swift_context);
2702 }
2703 continue;
2704 }
2705 llvm_unreachable("bad ABI kind");
2706 }
2707}
2708
2709QualType Sema::BuildFunctionType(QualType T,
2710 MutableArrayRef<QualType> ParamTypes,
2711 SourceLocation Loc, DeclarationName Entity,
2712 const FunctionProtoType::ExtProtoInfo &EPI) {
2713 bool Invalid = false;
2714
2715 Invalid |= CheckFunctionReturnType(T, Loc);
2716
2717 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2718 // FIXME: Loc is too inprecise here, should use proper locations for args.
2719 QualType ParamType = Context.getAdjustedParameterType(T: ParamTypes[Idx]);
2720 if (ParamType->isVoidType()) {
2721 Diag(Loc, DiagID: diag::err_param_with_void_type);
2722 Invalid = true;
2723 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2724 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2725 // Disallow half FP arguments.
2726 Diag(Loc, DiagID: diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2727 FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "*");
2728 Invalid = true;
2729 } else if (ParamType->isWebAssemblyTableType()) {
2730 Diag(Loc, DiagID: diag::err_wasm_table_as_function_parameter);
2731 Invalid = true;
2732 } else if (ParamType.getPointerAuth()) {
2733 // __ptrauth is illegal on a function return type.
2734 Diag(Loc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
2735 Invalid = true;
2736 }
2737
2738 // C++2a [dcl.fct]p4:
2739 // A parameter with volatile-qualified type is deprecated
2740 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2741 Diag(Loc, DiagID: diag::warn_deprecated_volatile_param) << ParamType;
2742
2743 ParamTypes[Idx] = ParamType;
2744 }
2745
2746 if (EPI.ExtParameterInfos) {
2747 checkExtParameterInfos(S&: *this, paramTypes: ParamTypes, EPI,
2748 getParamLoc: [=](unsigned i) { return Loc; });
2749 }
2750
2751 if (EPI.ExtInfo.getProducesResult()) {
2752 // This is just a warning, so we can't fail to build if we see it.
2753 ObjC().checkNSReturnsRetainedReturnType(loc: Loc, type: T);
2754 }
2755
2756 if (Invalid)
2757 return QualType();
2758
2759 return Context.getFunctionType(ResultTy: T, Args: ParamTypes, EPI);
2760}
2761
2762QualType Sema::BuildMemberPointerType(QualType T, const CXXScopeSpec &SS,
2763 CXXRecordDecl *Cls, SourceLocation Loc,
2764 DeclarationName Entity) {
2765 if (!Cls && !isDependentScopeSpecifier(SS)) {
2766 Cls = dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS));
2767 if (!Cls) {
2768 auto D =
2769 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_illegal_decl_mempointer_in_nonclass)
2770 << SS.getRange();
2771 if (const IdentifierInfo *II = Entity.getAsIdentifierInfo())
2772 D << II;
2773 else
2774 D << "member pointer";
2775 return QualType();
2776 }
2777 }
2778
2779 // Verify that we're not building a pointer to pointer to function with
2780 // exception specification.
2781 if (CheckDistantExceptionSpec(T)) {
2782 Diag(Loc, DiagID: diag::err_distant_exception_spec);
2783 return QualType();
2784 }
2785
2786 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2787 // with reference type, or "cv void."
2788 if (T->isReferenceType()) {
2789 Diag(Loc, DiagID: diag::err_illegal_decl_mempointer_to_reference)
2790 << getPrintableNameForEntity(Entity) << T;
2791 return QualType();
2792 }
2793
2794 if (T->isVoidType()) {
2795 Diag(Loc, DiagID: diag::err_illegal_decl_mempointer_to_void)
2796 << getPrintableNameForEntity(Entity);
2797 return QualType();
2798 }
2799
2800 if (T->isFunctionType() && getLangOpts().OpenCL &&
2801 !getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
2802 LO: getLangOpts())) {
2803 Diag(Loc, DiagID: diag::err_opencl_function_pointer) << /*pointer*/ 0;
2804 return QualType();
2805 }
2806
2807 if (getLangOpts().HLSL && Loc.isValid()) {
2808 Diag(Loc, DiagID: diag::err_hlsl_pointers_unsupported) << 0;
2809 return QualType();
2810 }
2811
2812 // Adjust the default free function calling convention to the default method
2813 // calling convention.
2814 bool IsCtorOrDtor =
2815 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2816 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2817 if (T->isFunctionType())
2818 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
2819
2820 return Context.getMemberPointerType(T, Qualifier: SS.getScopeRep(), Cls);
2821}
2822
2823QualType Sema::BuildBlockPointerType(QualType T,
2824 SourceLocation Loc,
2825 DeclarationName Entity) {
2826 if (!T->isFunctionType()) {
2827 Diag(Loc, DiagID: diag::err_nonfunction_block_type);
2828 return QualType();
2829 }
2830
2831 if (checkQualifiedFunction(S&: *this, T, Loc, QFK: QFK_BlockPointer))
2832 return QualType();
2833
2834 if (getLangOpts().OpenCL)
2835 T = deduceOpenCLPointeeAddrSpace(S&: *this, PointeeType: T);
2836
2837 return Context.getBlockPointerType(T);
2838}
2839
2840QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2841 QualType QT = Ty.get();
2842 if (QT.isNull()) {
2843 if (TInfo) *TInfo = nullptr;
2844 return QualType();
2845 }
2846
2847 TypeSourceInfo *TSI = nullptr;
2848 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(Val&: QT)) {
2849 QT = LIT->getType();
2850 TSI = LIT->getTypeSourceInfo();
2851 }
2852
2853 if (TInfo)
2854 *TInfo = TSI;
2855 return QT;
2856}
2857
2858static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2859 Qualifiers::ObjCLifetime ownership,
2860 unsigned chunkIndex);
2861
2862/// Given that this is the declaration of a parameter under ARC,
2863/// attempt to infer attributes and such for pointer-to-whatever
2864/// types.
2865static void inferARCWriteback(TypeProcessingState &state,
2866 QualType &declSpecType) {
2867 Sema &S = state.getSema();
2868 Declarator &declarator = state.getDeclarator();
2869
2870 // TODO: should we care about decl qualifiers?
2871
2872 // Check whether the declarator has the expected form. We walk
2873 // from the inside out in order to make the block logic work.
2874 unsigned outermostPointerIndex = 0;
2875 bool isBlockPointer = false;
2876 unsigned numPointers = 0;
2877 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2878 unsigned chunkIndex = i;
2879 DeclaratorChunk &chunk = declarator.getTypeObject(i: chunkIndex);
2880 switch (chunk.Kind) {
2881 case DeclaratorChunk::Paren:
2882 // Ignore parens.
2883 break;
2884
2885 case DeclaratorChunk::Reference:
2886 case DeclaratorChunk::Pointer:
2887 // Count the number of pointers. Treat references
2888 // interchangeably as pointers; if they're mis-ordered, normal
2889 // type building will discover that.
2890 outermostPointerIndex = chunkIndex;
2891 numPointers++;
2892 break;
2893
2894 case DeclaratorChunk::BlockPointer:
2895 // If we have a pointer to block pointer, that's an acceptable
2896 // indirect reference; anything else is not an application of
2897 // the rules.
2898 if (numPointers != 1) return;
2899 numPointers++;
2900 outermostPointerIndex = chunkIndex;
2901 isBlockPointer = true;
2902
2903 // We don't care about pointer structure in return values here.
2904 goto done;
2905
2906 case DeclaratorChunk::Array: // suppress if written (id[])?
2907 case DeclaratorChunk::Function:
2908 case DeclaratorChunk::MemberPointer:
2909 case DeclaratorChunk::Pipe:
2910 return;
2911 }
2912 }
2913 done:
2914
2915 // If we have *one* pointer, then we want to throw the qualifier on
2916 // the declaration-specifiers, which means that it needs to be a
2917 // retainable object type.
2918 if (numPointers == 1) {
2919 // If it's not a retainable object type, the rule doesn't apply.
2920 if (!declSpecType->isObjCRetainableType()) return;
2921
2922 // If it already has lifetime, don't do anything.
2923 if (declSpecType.getObjCLifetime()) return;
2924
2925 // Otherwise, modify the type in-place.
2926 Qualifiers qs;
2927
2928 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2929 qs.addObjCLifetime(type: Qualifiers::OCL_ExplicitNone);
2930 else
2931 qs.addObjCLifetime(type: Qualifiers::OCL_Autoreleasing);
2932 declSpecType = S.Context.getQualifiedType(T: declSpecType, Qs: qs);
2933
2934 // If we have *two* pointers, then we want to throw the qualifier on
2935 // the outermost pointer.
2936 } else if (numPointers == 2) {
2937 // If we don't have a block pointer, we need to check whether the
2938 // declaration-specifiers gave us something that will turn into a
2939 // retainable object pointer after we slap the first pointer on it.
2940 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2941 return;
2942
2943 // Look for an explicit lifetime attribute there.
2944 DeclaratorChunk &chunk = declarator.getTypeObject(i: outermostPointerIndex);
2945 if (chunk.Kind != DeclaratorChunk::Pointer &&
2946 chunk.Kind != DeclaratorChunk::BlockPointer)
2947 return;
2948 for (const ParsedAttr &AL : chunk.getAttrs())
2949 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2950 return;
2951
2952 transferARCOwnershipToDeclaratorChunk(state, ownership: Qualifiers::OCL_Autoreleasing,
2953 chunkIndex: outermostPointerIndex);
2954
2955 // Any other number of pointers/references does not trigger the rule.
2956 } else return;
2957
2958 // TODO: mark whether we did this inference?
2959}
2960
2961void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2962 SourceLocation FallbackLoc,
2963 SourceLocation ConstQualLoc,
2964 SourceLocation VolatileQualLoc,
2965 SourceLocation RestrictQualLoc,
2966 SourceLocation AtomicQualLoc,
2967 SourceLocation UnalignedQualLoc) {
2968 if (!Quals)
2969 return;
2970
2971 struct Qual {
2972 const char *Name;
2973 unsigned Mask;
2974 SourceLocation Loc;
2975 } const QualKinds[5] = {
2976 { .Name: "const", .Mask: DeclSpec::TQ_const, .Loc: ConstQualLoc },
2977 { .Name: "volatile", .Mask: DeclSpec::TQ_volatile, .Loc: VolatileQualLoc },
2978 { .Name: "restrict", .Mask: DeclSpec::TQ_restrict, .Loc: RestrictQualLoc },
2979 { .Name: "__unaligned", .Mask: DeclSpec::TQ_unaligned, .Loc: UnalignedQualLoc },
2980 { .Name: "_Atomic", .Mask: DeclSpec::TQ_atomic, .Loc: AtomicQualLoc }
2981 };
2982
2983 SmallString<32> QualStr;
2984 unsigned NumQuals = 0;
2985 SourceLocation Loc;
2986 FixItHint FixIts[5];
2987
2988 // Build a string naming the redundant qualifiers.
2989 for (auto &E : QualKinds) {
2990 if (Quals & E.Mask) {
2991 if (!QualStr.empty()) QualStr += ' ';
2992 QualStr += E.Name;
2993
2994 // If we have a location for the qualifier, offer a fixit.
2995 SourceLocation QualLoc = E.Loc;
2996 if (QualLoc.isValid()) {
2997 FixIts[NumQuals] = FixItHint::CreateRemoval(RemoveRange: QualLoc);
2998 if (Loc.isInvalid() ||
2999 getSourceManager().isBeforeInTranslationUnit(LHS: QualLoc, RHS: Loc))
3000 Loc = QualLoc;
3001 }
3002
3003 ++NumQuals;
3004 }
3005 }
3006
3007 Diag(Loc: Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3008 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3009}
3010
3011// Diagnose pointless type qualifiers on the return type of a function.
3012static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3013 Declarator &D,
3014 unsigned FunctionChunkIndex) {
3015 const DeclaratorChunk::FunctionTypeInfo &FTI =
3016 D.getTypeObject(i: FunctionChunkIndex).Fun;
3017 if (FTI.hasTrailingReturnType()) {
3018 S.diagnoseIgnoredQualifiers(DiagID: diag::warn_qual_return_type,
3019 Quals: RetTy.getLocalCVRQualifiers(),
3020 FallbackLoc: FTI.getTrailingReturnTypeLoc());
3021 return;
3022 }
3023
3024 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3025 End = D.getNumTypeObjects();
3026 OuterChunkIndex != End; ++OuterChunkIndex) {
3027 DeclaratorChunk &OuterChunk = D.getTypeObject(i: OuterChunkIndex);
3028 switch (OuterChunk.Kind) {
3029 case DeclaratorChunk::Paren:
3030 continue;
3031
3032 case DeclaratorChunk::Pointer: {
3033 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3034 S.diagnoseIgnoredQualifiers(
3035 DiagID: diag::warn_qual_return_type,
3036 Quals: PTI.TypeQuals,
3037 FallbackLoc: SourceLocation(),
3038 ConstQualLoc: PTI.ConstQualLoc,
3039 VolatileQualLoc: PTI.VolatileQualLoc,
3040 RestrictQualLoc: PTI.RestrictQualLoc,
3041 AtomicQualLoc: PTI.AtomicQualLoc,
3042 UnalignedQualLoc: PTI.UnalignedQualLoc);
3043 return;
3044 }
3045
3046 case DeclaratorChunk::Function:
3047 case DeclaratorChunk::BlockPointer:
3048 case DeclaratorChunk::Reference:
3049 case DeclaratorChunk::Array:
3050 case DeclaratorChunk::MemberPointer:
3051 case DeclaratorChunk::Pipe:
3052 // FIXME: We can't currently provide an accurate source location and a
3053 // fix-it hint for these.
3054 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3055 S.diagnoseIgnoredQualifiers(DiagID: diag::warn_qual_return_type,
3056 Quals: RetTy.getCVRQualifiers() | AtomicQual,
3057 FallbackLoc: D.getIdentifierLoc());
3058 return;
3059 }
3060
3061 llvm_unreachable("unknown declarator chunk kind");
3062 }
3063
3064 // If the qualifiers come from a conversion function type, don't diagnose
3065 // them -- they're not necessarily redundant, since such a conversion
3066 // operator can be explicitly called as "x.operator const int()".
3067 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3068 return;
3069
3070 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3071 // which are present there.
3072 S.diagnoseIgnoredQualifiers(DiagID: diag::warn_qual_return_type,
3073 Quals: D.getDeclSpec().getTypeQualifiers(),
3074 FallbackLoc: D.getIdentifierLoc(),
3075 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(),
3076 VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
3077 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
3078 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc(),
3079 UnalignedQualLoc: D.getDeclSpec().getUnalignedSpecLoc());
3080}
3081
3082static std::pair<QualType, TypeSourceInfo *>
3083InventTemplateParameter(TypeProcessingState &state, QualType T,
3084 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3085 InventedTemplateParameterInfo &Info) {
3086 Sema &S = state.getSema();
3087 Declarator &D = state.getDeclarator();
3088
3089 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3090 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3091 const bool IsParameterPack = D.hasEllipsis();
3092
3093 // If auto is mentioned in a lambda parameter or abbreviated function
3094 // template context, convert it to a template parameter type.
3095
3096 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3097 // template parameter type. Template parameters are temporarily added
3098 // to the TU until the associated TemplateDecl is created.
3099 TemplateTypeParmDecl *InventedTemplateParam =
3100 TemplateTypeParmDecl::Create(
3101 C: S.Context, DC: S.Context.getTranslationUnitDecl(),
3102 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3103 /*NameLoc=*/D.getIdentifierLoc(),
3104 D: TemplateParameterDepth, P: AutoParameterPosition,
3105 Id: S.InventAbbreviatedTemplateParameterTypeName(
3106 ParamName: D.getIdentifier(), Index: AutoParameterPosition), Typename: false,
3107 ParameterPack: IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3108 InventedTemplateParam->setImplicit();
3109 Info.TemplateParams.push_back(Elt: InventedTemplateParam);
3110
3111 // Attach type constraints to the new parameter.
3112 if (Auto->isConstrained()) {
3113 if (TrailingTSI) {
3114 // The 'auto' appears in a trailing return type we've already built;
3115 // extract its type constraints to attach to the template parameter.
3116 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3117 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3118 bool Invalid = false;
3119 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3120 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3121 S.DiagnoseUnexpandedParameterPack(Arg: AutoLoc.getArgLoc(i: Idx),
3122 UPPC: Sema::UPPC_TypeConstraint))
3123 Invalid = true;
3124 TAL.addArgument(Loc: AutoLoc.getArgLoc(i: Idx));
3125 }
3126
3127 if (!Invalid) {
3128 S.AttachTypeConstraint(
3129 NS: AutoLoc.getNestedNameSpecifierLoc(), NameInfo: AutoLoc.getConceptNameInfo(),
3130 NamedConcept: AutoLoc.getNamedConcept(), /*FoundDecl=*/AutoLoc.getFoundDecl(),
3131 TemplateArgs: AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3132 ConstrainedParameter: InventedTemplateParam, EllipsisLoc: D.getEllipsisLoc());
3133 }
3134 } else {
3135 // The 'auto' appears in the decl-specifiers; we've not finished forming
3136 // TypeSourceInfo for it yet.
3137 TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3138 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
3139 TemplateId->RAngleLoc);
3140 bool Invalid = false;
3141 if (TemplateId->LAngleLoc.isValid()) {
3142 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3143 TemplateId->NumArgs);
3144 S.translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgsInfo);
3145
3146 if (D.getEllipsisLoc().isInvalid()) {
3147 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3148 if (S.DiagnoseUnexpandedParameterPack(Arg,
3149 UPPC: Sema::UPPC_TypeConstraint)) {
3150 Invalid = true;
3151 break;
3152 }
3153 }
3154 }
3155 }
3156 if (!Invalid) {
3157 UsingShadowDecl *USD =
3158 TemplateId->Template.get().getAsUsingShadowDecl();
3159 TemplateDecl *CD = TemplateId->Template.get().getAsTemplateDecl();
3160 S.AttachTypeConstraint(
3161 NS: D.getDeclSpec().getTypeSpecScope().getWithLocInContext(Context&: S.Context),
3162 NameInfo: DeclarationNameInfo(DeclarationName(TemplateId->Name),
3163 TemplateId->TemplateNameLoc),
3164 NamedConcept: CD,
3165 /*FoundDecl=*/USD ? cast<NamedDecl>(Val: USD) : CD,
3166 TemplateArgs: TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3167 ConstrainedParameter: InventedTemplateParam, EllipsisLoc: D.getEllipsisLoc());
3168 }
3169 }
3170 }
3171
3172 // Replace the 'auto' in the function parameter with this invented
3173 // template type parameter.
3174 // FIXME: Retain some type sugar to indicate that this was written
3175 // as 'auto'?
3176 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3177 QualType NewT = state.ReplaceAutoType(TypeWithAuto: T, Replacement);
3178 TypeSourceInfo *NewTSI =
3179 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TypeWithAuto: TrailingTSI, Replacement)
3180 : nullptr;
3181 return {NewT, NewTSI};
3182}
3183
3184static TypeSourceInfo *
3185GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3186 QualType T, TypeSourceInfo *ReturnTypeInfo);
3187
3188static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3189 TypeSourceInfo *&ReturnTypeInfo) {
3190 Sema &SemaRef = state.getSema();
3191 Declarator &D = state.getDeclarator();
3192 QualType T;
3193 ReturnTypeInfo = nullptr;
3194
3195 // The TagDecl owned by the DeclSpec.
3196 TagDecl *OwnedTagDecl = nullptr;
3197
3198 switch (D.getName().getKind()) {
3199 case UnqualifiedIdKind::IK_ImplicitSelfParam:
3200 case UnqualifiedIdKind::IK_OperatorFunctionId:
3201 case UnqualifiedIdKind::IK_Identifier:
3202 case UnqualifiedIdKind::IK_LiteralOperatorId:
3203 case UnqualifiedIdKind::IK_TemplateId:
3204 T = ConvertDeclSpecToType(state);
3205
3206 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3207 OwnedTagDecl = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
3208 // Owned declaration is embedded in declarator.
3209 OwnedTagDecl->setEmbeddedInDeclarator(true);
3210 }
3211 break;
3212
3213 case UnqualifiedIdKind::IK_ConstructorName:
3214 case UnqualifiedIdKind::IK_ConstructorTemplateId:
3215 case UnqualifiedIdKind::IK_DestructorName:
3216 // Constructors and destructors don't have return types. Use
3217 // "void" instead.
3218 T = SemaRef.Context.VoidTy;
3219 processTypeAttrs(state, type&: T, TAL: TAL_DeclSpec,
3220 attrs: D.getMutableDeclSpec().getAttributes());
3221 break;
3222
3223 case UnqualifiedIdKind::IK_DeductionGuideName:
3224 // Deduction guides have a trailing return type and no type in their
3225 // decl-specifier sequence. Use a placeholder return type for now.
3226 T = SemaRef.Context.DependentTy;
3227 break;
3228
3229 case UnqualifiedIdKind::IK_ConversionFunctionId:
3230 // The result type of a conversion function is the type that it
3231 // converts to.
3232 T = SemaRef.GetTypeFromParser(Ty: D.getName().ConversionFunctionId,
3233 TInfo: &ReturnTypeInfo);
3234 break;
3235 }
3236
3237 // Note: We don't need to distribute declaration attributes (i.e.
3238 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3239 // and those don't get distributed.
3240 distributeTypeAttrsFromDeclarator(
3241 state, declSpecType&: T, CFT: SemaRef.CUDA().IdentifyTarget(Attrs: D.getAttributes()));
3242
3243 // Find the deduced type in this type. Look in the trailing return type if we
3244 // have one, otherwise in the DeclSpec type.
3245 // FIXME: The standard wording doesn't currently describe this.
3246 DeducedType *Deduced = T->getContainedDeducedType();
3247 bool DeducedIsTrailingReturnType = false;
3248 if (Deduced && isa<AutoType>(Val: Deduced) && D.hasTrailingReturnType()) {
3249 QualType T = SemaRef.GetTypeFromParser(Ty: D.getTrailingReturnType());
3250 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3251 DeducedIsTrailingReturnType = true;
3252 }
3253
3254 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3255 if (Deduced) {
3256 AutoType *Auto = dyn_cast<AutoType>(Val: Deduced);
3257 int Error = -1;
3258
3259 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3260 // class template argument deduction)?
3261 bool IsCXXAutoType =
3262 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3263 bool IsDeducedReturnType = false;
3264
3265 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3266 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3267 AutoRange = D.getName().getSourceRange();
3268
3269 switch (D.getContext()) {
3270 case DeclaratorContext::LambdaExpr:
3271 // Declared return type of a lambda-declarator is implicit and is always
3272 // 'auto'.
3273 break;
3274 case DeclaratorContext::ObjCParameter:
3275 case DeclaratorContext::ObjCResult:
3276 Error = 0;
3277 break;
3278 case DeclaratorContext::RequiresExpr:
3279 Error = 22;
3280 break;
3281 case DeclaratorContext::Prototype:
3282 case DeclaratorContext::LambdaExprParameter: {
3283 InventedTemplateParameterInfo *Info = nullptr;
3284 if (D.getContext() == DeclaratorContext::Prototype) {
3285 // With concepts we allow 'auto' in function parameters.
3286 if (!SemaRef.getLangOpts().CPlusPlus || !Auto ||
3287 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3288 Error = 0;
3289 break;
3290 }
3291
3292 if (!SemaRef.getLangOpts().CPlusPlus20)
3293 SemaRef.DiagCompat(Loc: AutoRange.getBegin(), CompatDiagId: diag_compat::auto_param);
3294
3295 if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3296 Error = 21;
3297 break;
3298 }
3299
3300 Info = &SemaRef.InventedParameterInfos.back();
3301 } else {
3302 // In C++14, generic lambdas allow 'auto' in their parameters.
3303 if (!SemaRef.getLangOpts().CPlusPlus14 && Auto &&
3304 Auto->getKeyword() == AutoTypeKeyword::Auto) {
3305 Error = 25; // auto not allowed in lambda parameter (before C++14)
3306 break;
3307 } else if (!Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) {
3308 Error = 16; // __auto_type or decltype(auto) not allowed in lambda
3309 // parameter
3310 break;
3311 }
3312 Info = SemaRef.getCurLambda();
3313 assert(Info && "No LambdaScopeInfo on the stack!");
3314 }
3315
3316 // We'll deal with inventing template parameters for 'auto' in trailing
3317 // return types when we pick up the trailing return type when processing
3318 // the function chunk.
3319 if (!DeducedIsTrailingReturnType)
3320 T = InventTemplateParameter(state, T, TrailingTSI: nullptr, Auto, Info&: *Info).first;
3321 break;
3322 }
3323 case DeclaratorContext::Member: {
3324 if (D.isStaticMember() || D.isFunctionDeclarator())
3325 break;
3326 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3327 if (isa<ObjCContainerDecl>(Val: SemaRef.CurContext)) {
3328 Error = 6; // Interface member.
3329 } else {
3330 switch (cast<TagDecl>(Val: SemaRef.CurContext)->getTagKind()) {
3331 case TagTypeKind::Enum:
3332 llvm_unreachable("unhandled tag kind");
3333 case TagTypeKind::Struct:
3334 Error = Cxx ? 1 : 2; /* Struct member */
3335 break;
3336 case TagTypeKind::Union:
3337 Error = Cxx ? 3 : 4; /* Union member */
3338 break;
3339 case TagTypeKind::Class:
3340 Error = 5; /* Class member */
3341 break;
3342 case TagTypeKind::Interface:
3343 Error = 6; /* Interface member */
3344 break;
3345 }
3346 }
3347 if (D.getDeclSpec().isFriendSpecified())
3348 Error = 20; // Friend type
3349 break;
3350 }
3351 case DeclaratorContext::CXXCatch:
3352 case DeclaratorContext::ObjCCatch:
3353 Error = 7; // Exception declaration
3354 break;
3355 case DeclaratorContext::TemplateParam:
3356 if (isa<DeducedTemplateSpecializationType>(Val: Deduced) &&
3357 !SemaRef.getLangOpts().CPlusPlus20)
3358 Error = 19; // Template parameter (until C++20)
3359 else if (!SemaRef.getLangOpts().CPlusPlus17)
3360 Error = 8; // Template parameter (until C++17)
3361 break;
3362 case DeclaratorContext::BlockLiteral:
3363 Error = 9; // Block literal
3364 break;
3365 case DeclaratorContext::TemplateArg:
3366 // Within a template argument list, a deduced template specialization
3367 // type will be reinterpreted as a template template argument.
3368 if (isa<DeducedTemplateSpecializationType>(Val: Deduced) &&
3369 !D.getNumTypeObjects() &&
3370 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3371 break;
3372 [[fallthrough]];
3373 case DeclaratorContext::TemplateTypeArg:
3374 Error = 10; // Template type argument
3375 break;
3376 case DeclaratorContext::AliasDecl:
3377 case DeclaratorContext::AliasTemplate:
3378 Error = 12; // Type alias
3379 break;
3380 case DeclaratorContext::TrailingReturn:
3381 case DeclaratorContext::TrailingReturnVar:
3382 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3383 Error = 13; // Function return type
3384 IsDeducedReturnType = true;
3385 break;
3386 case DeclaratorContext::ConversionId:
3387 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3388 Error = 14; // conversion-type-id
3389 IsDeducedReturnType = true;
3390 break;
3391 case DeclaratorContext::FunctionalCast:
3392 if (isa<DeducedTemplateSpecializationType>(Val: Deduced))
3393 break;
3394 if (SemaRef.getLangOpts().CPlusPlus23 && IsCXXAutoType &&
3395 !Auto->isDecltypeAuto())
3396 break; // auto(x)
3397 [[fallthrough]];
3398 case DeclaratorContext::TypeName:
3399 case DeclaratorContext::Association:
3400 Error = 15; // Generic
3401 break;
3402 case DeclaratorContext::File:
3403 case DeclaratorContext::Block:
3404 case DeclaratorContext::ForInit:
3405 case DeclaratorContext::SelectionInit:
3406 case DeclaratorContext::Condition:
3407 // FIXME: P0091R3 (erroneously) does not permit class template argument
3408 // deduction in conditions, for-init-statements, and other declarations
3409 // that are not simple-declarations.
3410 break;
3411 case DeclaratorContext::CXXNew:
3412 // FIXME: P0091R3 does not permit class template argument deduction here,
3413 // but we follow GCC and allow it anyway.
3414 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Val: Deduced))
3415 Error = 17; // 'new' type
3416 break;
3417 case DeclaratorContext::KNRTypeList:
3418 Error = 18; // K&R function parameter
3419 break;
3420 }
3421
3422 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3423 Error = 11;
3424
3425 // In Objective-C it is an error to use 'auto' on a function declarator
3426 // (and everywhere for '__auto_type').
3427 if (D.isFunctionDeclarator() &&
3428 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3429 Error = 13;
3430
3431 if (Error != -1) {
3432 unsigned Kind;
3433 if (Auto) {
3434 switch (Auto->getKeyword()) {
3435 case AutoTypeKeyword::Auto: Kind = 0; break;
3436 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3437 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3438 }
3439 } else {
3440 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3441 "unknown auto type");
3442 Kind = 3;
3443 }
3444
3445 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Val: Deduced);
3446 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3447
3448 SemaRef.Diag(Loc: AutoRange.getBegin(), DiagID: diag::err_auto_not_allowed)
3449 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(Name: TN)
3450 << QualType(Deduced, 0) << AutoRange;
3451 if (auto *TD = TN.getAsTemplateDecl())
3452 SemaRef.NoteTemplateLocation(Decl: *TD);
3453
3454 T = SemaRef.Context.IntTy;
3455 D.setInvalidType(true);
3456 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3457 // If there was a trailing return type, we already got
3458 // warn_cxx98_compat_trailing_return_type in the parser.
3459 // If there was a decltype(auto), we already got
3460 // warn_cxx11_compat_decltype_auto_type_specifier.
3461 unsigned DiagId = 0;
3462 if (D.getContext() == DeclaratorContext::LambdaExprParameter)
3463 DiagId = diag::warn_cxx11_compat_generic_lambda;
3464 else if (IsDeducedReturnType)
3465 DiagId = diag::warn_cxx11_compat_deduced_return_type;
3466 else if (Auto->getKeyword() == AutoTypeKeyword::Auto)
3467 DiagId = diag::warn_cxx98_compat_auto_type_specifier;
3468
3469 if (DiagId)
3470 SemaRef.Diag(Loc: AutoRange.getBegin(), DiagID: DiagId) << AutoRange;
3471 }
3472 }
3473
3474 if (SemaRef.getLangOpts().CPlusPlus &&
3475 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3476 // Check the contexts where C++ forbids the declaration of a new class
3477 // or enumeration in a type-specifier-seq.
3478 unsigned DiagID = 0;
3479 switch (D.getContext()) {
3480 case DeclaratorContext::TrailingReturn:
3481 case DeclaratorContext::TrailingReturnVar:
3482 // Class and enumeration definitions are syntactically not allowed in
3483 // trailing return types.
3484 llvm_unreachable("parser should not have allowed this");
3485 break;
3486 case DeclaratorContext::File:
3487 case DeclaratorContext::Member:
3488 case DeclaratorContext::Block:
3489 case DeclaratorContext::ForInit:
3490 case DeclaratorContext::SelectionInit:
3491 case DeclaratorContext::BlockLiteral:
3492 case DeclaratorContext::LambdaExpr:
3493 // C++11 [dcl.type]p3:
3494 // A type-specifier-seq shall not define a class or enumeration unless
3495 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3496 // the declaration of a template-declaration.
3497 case DeclaratorContext::AliasDecl:
3498 break;
3499 case DeclaratorContext::AliasTemplate:
3500 DiagID = diag::err_type_defined_in_alias_template;
3501 break;
3502 case DeclaratorContext::TypeName:
3503 case DeclaratorContext::FunctionalCast:
3504 case DeclaratorContext::ConversionId:
3505 case DeclaratorContext::TemplateParam:
3506 case DeclaratorContext::CXXNew:
3507 case DeclaratorContext::CXXCatch:
3508 case DeclaratorContext::ObjCCatch:
3509 case DeclaratorContext::TemplateArg:
3510 case DeclaratorContext::TemplateTypeArg:
3511 case DeclaratorContext::Association:
3512 DiagID = diag::err_type_defined_in_type_specifier;
3513 break;
3514 case DeclaratorContext::Prototype:
3515 case DeclaratorContext::LambdaExprParameter:
3516 case DeclaratorContext::ObjCParameter:
3517 case DeclaratorContext::ObjCResult:
3518 case DeclaratorContext::KNRTypeList:
3519 case DeclaratorContext::RequiresExpr:
3520 // C++ [dcl.fct]p6:
3521 // Types shall not be defined in return or parameter types.
3522 DiagID = diag::err_type_defined_in_param_type;
3523 break;
3524 case DeclaratorContext::Condition:
3525 // C++ 6.4p2:
3526 // The type-specifier-seq shall not contain typedef and shall not declare
3527 // a new class or enumeration.
3528 DiagID = diag::err_type_defined_in_condition;
3529 break;
3530 }
3531
3532 if (DiagID != 0) {
3533 SemaRef.Diag(Loc: OwnedTagDecl->getLocation(), DiagID)
3534 << SemaRef.Context.getCanonicalTagType(TD: OwnedTagDecl);
3535 D.setInvalidType(true);
3536 }
3537 }
3538
3539 assert(!T.isNull() && "This function should not return a null type");
3540 return T;
3541}
3542
3543/// Produce an appropriate diagnostic for an ambiguity between a function
3544/// declarator and a C++ direct-initializer.
3545static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3546 DeclaratorChunk &DeclType, QualType RT) {
3547 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3548 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3549
3550 // If the return type is void there is no ambiguity.
3551 if (RT->isVoidType())
3552 return;
3553
3554 // An initializer for a non-class type can have at most one argument.
3555 if (!RT->isRecordType() && FTI.NumParams > 1)
3556 return;
3557
3558 // An initializer for a reference must have exactly one argument.
3559 if (RT->isReferenceType() && FTI.NumParams != 1)
3560 return;
3561
3562 // Only warn if this declarator is declaring a function at block scope, and
3563 // doesn't have a storage class (such as 'extern') specified.
3564 if (!D.isFunctionDeclarator() ||
3565 D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration ||
3566 !S.CurContext->isFunctionOrMethod() ||
3567 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified)
3568 return;
3569
3570 // Inside a condition, a direct initializer is not permitted. We allow one to
3571 // be parsed in order to give better diagnostics in condition parsing.
3572 if (D.getContext() == DeclaratorContext::Condition)
3573 return;
3574
3575 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3576
3577 S.Diag(Loc: DeclType.Loc,
3578 DiagID: FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3579 : diag::warn_empty_parens_are_function_decl)
3580 << ParenRange;
3581
3582 // If the declaration looks like:
3583 // T var1,
3584 // f();
3585 // and name lookup finds a function named 'f', then the ',' was
3586 // probably intended to be a ';'.
3587 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3588 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3589 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3590 if (Comma.getFileID() != Name.getFileID() ||
3591 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3592 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3593 Sema::LookupOrdinaryName);
3594 if (S.LookupName(R&: Result, S: S.getCurScope()))
3595 S.Diag(Loc: D.getCommaLoc(), DiagID: diag::note_empty_parens_function_call)
3596 << FixItHint::CreateReplacement(RemoveRange: D.getCommaLoc(), Code: ";")
3597 << D.getIdentifier();
3598 Result.suppressDiagnostics();
3599 }
3600 }
3601
3602 if (FTI.NumParams > 0) {
3603 // For a declaration with parameters, eg. "T var(T());", suggest adding
3604 // parens around the first parameter to turn the declaration into a
3605 // variable declaration.
3606 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3607 SourceLocation B = Range.getBegin();
3608 SourceLocation E = S.getLocForEndOfToken(Loc: Range.getEnd());
3609 // FIXME: Maybe we should suggest adding braces instead of parens
3610 // in C++11 for classes that don't have an initializer_list constructor.
3611 S.Diag(Loc: B, DiagID: diag::note_additional_parens_for_variable_declaration)
3612 << FixItHint::CreateInsertion(InsertionLoc: B, Code: "(")
3613 << FixItHint::CreateInsertion(InsertionLoc: E, Code: ")");
3614 } else {
3615 // For a declaration without parameters, eg. "T var();", suggest replacing
3616 // the parens with an initializer to turn the declaration into a variable
3617 // declaration.
3618 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3619
3620 // Empty parens mean value-initialization, and no parens mean
3621 // default initialization. These are equivalent if the default
3622 // constructor is user-provided or if zero-initialization is a
3623 // no-op.
3624 if (RD && RD->hasDefinition() &&
3625 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3626 S.Diag(Loc: DeclType.Loc, DiagID: diag::note_empty_parens_default_ctor)
3627 << FixItHint::CreateRemoval(RemoveRange: ParenRange);
3628 else {
3629 std::string Init =
3630 S.getFixItZeroInitializerForType(T: RT, Loc: ParenRange.getBegin());
3631 if (Init.empty() && S.LangOpts.CPlusPlus11)
3632 Init = "{}";
3633 if (!Init.empty())
3634 S.Diag(Loc: DeclType.Loc, DiagID: diag::note_empty_parens_zero_initialize)
3635 << FixItHint::CreateReplacement(RemoveRange: ParenRange, Code: Init);
3636 }
3637 }
3638}
3639
3640/// Produce an appropriate diagnostic for a declarator with top-level
3641/// parentheses.
3642static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3643 DeclaratorChunk &Paren = D.getTypeObject(i: D.getNumTypeObjects() - 1);
3644 assert(Paren.Kind == DeclaratorChunk::Paren &&
3645 "do not have redundant top-level parentheses");
3646
3647 // This is a syntactic check; we're not interested in cases that arise
3648 // during template instantiation.
3649 if (S.inTemplateInstantiation())
3650 return;
3651
3652 // Check whether this could be intended to be a construction of a temporary
3653 // object in C++ via a function-style cast.
3654 bool CouldBeTemporaryObject =
3655 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3656 !D.isInvalidType() && D.getIdentifier() &&
3657 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3658 (T->isRecordType() || T->isDependentType()) &&
3659 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3660
3661 bool StartsWithDeclaratorId = true;
3662 for (auto &C : D.type_objects()) {
3663 switch (C.Kind) {
3664 case DeclaratorChunk::Paren:
3665 if (&C == &Paren)
3666 continue;
3667 [[fallthrough]];
3668 case DeclaratorChunk::Pointer:
3669 StartsWithDeclaratorId = false;
3670 continue;
3671
3672 case DeclaratorChunk::Array:
3673 if (!C.Arr.NumElts)
3674 CouldBeTemporaryObject = false;
3675 continue;
3676
3677 case DeclaratorChunk::Reference:
3678 // FIXME: Suppress the warning here if there is no initializer; we're
3679 // going to give an error anyway.
3680 // We assume that something like 'T (&x) = y;' is highly likely to not
3681 // be intended to be a temporary object.
3682 CouldBeTemporaryObject = false;
3683 StartsWithDeclaratorId = false;
3684 continue;
3685
3686 case DeclaratorChunk::Function:
3687 // In a new-type-id, function chunks require parentheses.
3688 if (D.getContext() == DeclaratorContext::CXXNew)
3689 return;
3690 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3691 // redundant-parens warning, but we don't know whether the function
3692 // chunk was syntactically valid as an expression here.
3693 CouldBeTemporaryObject = false;
3694 continue;
3695
3696 case DeclaratorChunk::BlockPointer:
3697 case DeclaratorChunk::MemberPointer:
3698 case DeclaratorChunk::Pipe:
3699 // These cannot appear in expressions.
3700 CouldBeTemporaryObject = false;
3701 StartsWithDeclaratorId = false;
3702 continue;
3703 }
3704 }
3705
3706 // FIXME: If there is an initializer, assume that this is not intended to be
3707 // a construction of a temporary object.
3708
3709 // Check whether the name has already been declared; if not, this is not a
3710 // function-style cast.
3711 if (CouldBeTemporaryObject) {
3712 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3713 Sema::LookupOrdinaryName);
3714 if (!S.LookupName(R&: Result, S: S.getCurScope()))
3715 CouldBeTemporaryObject = false;
3716 Result.suppressDiagnostics();
3717 }
3718
3719 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3720
3721 if (!CouldBeTemporaryObject) {
3722 // If we have A (::B), the parentheses affect the meaning of the program.
3723 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3724 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3725 // formally unambiguous.
3726 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3727 NestedNameSpecifier NNS = D.getCXXScopeSpec().getScopeRep();
3728 for (;;) {
3729 switch (NNS.getKind()) {
3730 case NestedNameSpecifier::Kind::Global:
3731 return;
3732 case NestedNameSpecifier::Kind::Type:
3733 NNS = NNS.getAsType()->getPrefix();
3734 continue;
3735 case NestedNameSpecifier::Kind::Namespace:
3736 NNS = NNS.getAsNamespaceAndPrefix().Prefix;
3737 continue;
3738 default:
3739 goto out;
3740 }
3741 }
3742 out:;
3743 }
3744
3745 S.Diag(Loc: Paren.Loc, DiagID: diag::warn_redundant_parens_around_declarator)
3746 << ParenRange << FixItHint::CreateRemoval(RemoveRange: Paren.Loc)
3747 << FixItHint::CreateRemoval(RemoveRange: Paren.EndLoc);
3748 return;
3749 }
3750
3751 S.Diag(Loc: Paren.Loc, DiagID: diag::warn_parens_disambiguated_as_variable_declaration)
3752 << ParenRange << D.getIdentifier();
3753 auto *RD = T->getAsCXXRecordDecl();
3754 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3755 S.Diag(Loc: Paren.Loc, DiagID: diag::note_raii_guard_add_name)
3756 << FixItHint::CreateInsertion(InsertionLoc: Paren.Loc, Code: " varname") << T
3757 << D.getIdentifier();
3758 // FIXME: A cast to void is probably a better suggestion in cases where it's
3759 // valid (when there is no initializer and we're not in a condition).
3760 S.Diag(Loc: D.getBeginLoc(), DiagID: diag::note_function_style_cast_add_parentheses)
3761 << FixItHint::CreateInsertion(InsertionLoc: D.getBeginLoc(), Code: "(")
3762 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: D.getEndLoc()), Code: ")");
3763 S.Diag(Loc: Paren.Loc, DiagID: diag::note_remove_parens_for_variable_declaration)
3764 << FixItHint::CreateRemoval(RemoveRange: Paren.Loc)
3765 << FixItHint::CreateRemoval(RemoveRange: Paren.EndLoc);
3766}
3767
3768/// Helper for figuring out the default CC for a function declarator type. If
3769/// this is the outermost chunk, then we can determine the CC from the
3770/// declarator context. If not, then this could be either a member function
3771/// type or normal function type.
3772static CallingConv getCCForDeclaratorChunk(
3773 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3774 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3775 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3776
3777 // Check for an explicit CC attribute.
3778 for (const ParsedAttr &AL : AttrList) {
3779 switch (AL.getKind()) {
3780 CALLING_CONV_ATTRS_CASELIST : {
3781 // Ignore attributes that don't validate or can't apply to the
3782 // function type. We'll diagnose the failure to apply them in
3783 // handleFunctionTypeAttr.
3784 CallingConv CC;
3785 if (!S.CheckCallingConvAttr(attr: AL, CC, /*FunctionDecl=*/FD: nullptr,
3786 CFT: S.CUDA().IdentifyTarget(Attrs: D.getAttributes())) &&
3787 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3788 return CC;
3789 }
3790 break;
3791 }
3792
3793 default:
3794 break;
3795 }
3796 }
3797
3798 bool IsCXXInstanceMethod = false;
3799
3800 if (S.getLangOpts().CPlusPlus) {
3801 // Look inwards through parentheses to see if this chunk will form a
3802 // member pointer type or if we're the declarator. Any type attributes
3803 // between here and there will override the CC we choose here.
3804 unsigned I = ChunkIndex;
3805 bool FoundNonParen = false;
3806 while (I && !FoundNonParen) {
3807 --I;
3808 if (D.getTypeObject(i: I).Kind != DeclaratorChunk::Paren)
3809 FoundNonParen = true;
3810 }
3811
3812 if (FoundNonParen) {
3813 // If we're not the declarator, we're a regular function type unless we're
3814 // in a member pointer.
3815 IsCXXInstanceMethod =
3816 D.getTypeObject(i: I).Kind == DeclaratorChunk::MemberPointer;
3817 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3818 // This can only be a call operator for a lambda, which is an instance
3819 // method, unless explicitly specified as 'static'.
3820 IsCXXInstanceMethod =
3821 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static;
3822 } else {
3823 // We're the innermost decl chunk, so must be a function declarator.
3824 assert(D.isFunctionDeclarator());
3825
3826 // If we're inside a record, we're declaring a method, but it could be
3827 // explicitly or implicitly static.
3828 IsCXXInstanceMethod =
3829 D.isFirstDeclarationOfMember() &&
3830 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3831 !D.isStaticMember();
3832 }
3833 }
3834
3835 CallingConv CC = S.Context.getDefaultCallingConvention(IsVariadic: FTI.isVariadic,
3836 IsCXXMethod: IsCXXInstanceMethod);
3837
3838 if (S.getLangOpts().CUDA) {
3839 // If we're compiling CUDA/HIP code and targeting HIPSPV we need to make
3840 // sure the kernels will be marked with the right calling convention so that
3841 // they will be visible by the APIs that ingest SPIR-V. We do not do this
3842 // when targeting AMDGCNSPIRV, as it does not rely on OpenCL.
3843 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
3844 if (Triple.isSPIRV() && Triple.getVendor() != llvm::Triple::AMD) {
3845 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3846 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
3847 CC = CC_DeviceKernel;
3848 break;
3849 }
3850 }
3851 }
3852 }
3853
3854 for (const ParsedAttr &AL : llvm::concat<ParsedAttr>(
3855 Ranges: D.getDeclSpec().getAttributes(), Ranges&: D.getAttributes(),
3856 Ranges: D.getDeclarationAttributes())) {
3857 if (AL.getKind() == ParsedAttr::AT_DeviceKernel) {
3858 CC = CC_DeviceKernel;
3859 break;
3860 }
3861 }
3862 return CC;
3863}
3864
3865namespace {
3866 /// A simple notion of pointer kinds, which matches up with the various
3867 /// pointer declarators.
3868 enum class SimplePointerKind {
3869 Pointer,
3870 BlockPointer,
3871 MemberPointer,
3872 Array,
3873 };
3874} // end anonymous namespace
3875
3876IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3877 switch (nullability) {
3878 case NullabilityKind::NonNull:
3879 if (!Ident__Nonnull)
3880 Ident__Nonnull = PP.getIdentifierInfo(Name: "_Nonnull");
3881 return Ident__Nonnull;
3882
3883 case NullabilityKind::Nullable:
3884 if (!Ident__Nullable)
3885 Ident__Nullable = PP.getIdentifierInfo(Name: "_Nullable");
3886 return Ident__Nullable;
3887
3888 case NullabilityKind::NullableResult:
3889 if (!Ident__Nullable_result)
3890 Ident__Nullable_result = PP.getIdentifierInfo(Name: "_Nullable_result");
3891 return Ident__Nullable_result;
3892
3893 case NullabilityKind::Unspecified:
3894 if (!Ident__Null_unspecified)
3895 Ident__Null_unspecified = PP.getIdentifierInfo(Name: "_Null_unspecified");
3896 return Ident__Null_unspecified;
3897 }
3898 llvm_unreachable("Unknown nullability kind.");
3899}
3900
3901/// Check whether there is a nullability attribute of any kind in the given
3902/// attribute list.
3903static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3904 for (const ParsedAttr &AL : attrs) {
3905 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3906 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3907 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
3908 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3909 return true;
3910 }
3911
3912 return false;
3913}
3914
3915namespace {
3916 /// Describes the kind of a pointer a declarator describes.
3917 enum class PointerDeclaratorKind {
3918 // Not a pointer.
3919 NonPointer,
3920 // Single-level pointer.
3921 SingleLevelPointer,
3922 // Multi-level pointer (of any pointer kind).
3923 MultiLevelPointer,
3924 // CFFooRef*
3925 MaybePointerToCFRef,
3926 // CFErrorRef*
3927 CFErrorRefPointer,
3928 // NSError**
3929 NSErrorPointerPointer,
3930 };
3931
3932 /// Describes a declarator chunk wrapping a pointer that marks inference as
3933 /// unexpected.
3934 // These values must be kept in sync with diagnostics.
3935 enum class PointerWrappingDeclaratorKind {
3936 /// Pointer is top-level.
3937 None = -1,
3938 /// Pointer is an array element.
3939 Array = 0,
3940 /// Pointer is the referent type of a C++ reference.
3941 Reference = 1
3942 };
3943} // end anonymous namespace
3944
3945/// Classify the given declarator, whose type-specified is \c type, based on
3946/// what kind of pointer it refers to.
3947///
3948/// This is used to determine the default nullability.
3949static PointerDeclaratorKind
3950classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
3951 PointerWrappingDeclaratorKind &wrappingKind) {
3952 unsigned numNormalPointers = 0;
3953
3954 // For any dependent type, we consider it a non-pointer.
3955 if (type->isDependentType())
3956 return PointerDeclaratorKind::NonPointer;
3957
3958 // Look through the declarator chunks to identify pointers.
3959 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3960 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3961 switch (chunk.Kind) {
3962 case DeclaratorChunk::Array:
3963 if (numNormalPointers == 0)
3964 wrappingKind = PointerWrappingDeclaratorKind::Array;
3965 break;
3966
3967 case DeclaratorChunk::Function:
3968 case DeclaratorChunk::Pipe:
3969 break;
3970
3971 case DeclaratorChunk::BlockPointer:
3972 case DeclaratorChunk::MemberPointer:
3973 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3974 : PointerDeclaratorKind::SingleLevelPointer;
3975
3976 case DeclaratorChunk::Paren:
3977 break;
3978
3979 case DeclaratorChunk::Reference:
3980 if (numNormalPointers == 0)
3981 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3982 break;
3983
3984 case DeclaratorChunk::Pointer:
3985 ++numNormalPointers;
3986 if (numNormalPointers > 2)
3987 return PointerDeclaratorKind::MultiLevelPointer;
3988 break;
3989 }
3990 }
3991
3992 // Then, dig into the type specifier itself.
3993 unsigned numTypeSpecifierPointers = 0;
3994 do {
3995 // Decompose normal pointers.
3996 if (auto ptrType = type->getAs<PointerType>()) {
3997 ++numNormalPointers;
3998
3999 if (numNormalPointers > 2)
4000 return PointerDeclaratorKind::MultiLevelPointer;
4001
4002 type = ptrType->getPointeeType();
4003 ++numTypeSpecifierPointers;
4004 continue;
4005 }
4006
4007 // Decompose block pointers.
4008 if (type->getAs<BlockPointerType>()) {
4009 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4010 : PointerDeclaratorKind::SingleLevelPointer;
4011 }
4012
4013 // Decompose member pointers.
4014 if (type->getAs<MemberPointerType>()) {
4015 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4016 : PointerDeclaratorKind::SingleLevelPointer;
4017 }
4018
4019 // Look at Objective-C object pointers.
4020 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4021 ++numNormalPointers;
4022 ++numTypeSpecifierPointers;
4023
4024 // If this is NSError**, report that.
4025 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4026 if (objcClassDecl->getIdentifier() == S.ObjC().getNSErrorIdent() &&
4027 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4028 return PointerDeclaratorKind::NSErrorPointerPointer;
4029 }
4030 }
4031
4032 break;
4033 }
4034
4035 // Look at Objective-C class types.
4036 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4037 if (objcClass->getInterface()->getIdentifier() ==
4038 S.ObjC().getNSErrorIdent()) {
4039 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4040 return PointerDeclaratorKind::NSErrorPointerPointer;
4041 }
4042
4043 break;
4044 }
4045
4046 // If at this point we haven't seen a pointer, we won't see one.
4047 if (numNormalPointers == 0)
4048 return PointerDeclaratorKind::NonPointer;
4049
4050 if (auto *recordDecl = type->getAsRecordDecl()) {
4051 // If this is CFErrorRef*, report it as such.
4052 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4053 S.ObjC().isCFError(D: recordDecl)) {
4054 return PointerDeclaratorKind::CFErrorRefPointer;
4055 }
4056 break;
4057 }
4058
4059 break;
4060 } while (true);
4061
4062 switch (numNormalPointers) {
4063 case 0:
4064 return PointerDeclaratorKind::NonPointer;
4065
4066 case 1:
4067 return PointerDeclaratorKind::SingleLevelPointer;
4068
4069 case 2:
4070 return PointerDeclaratorKind::MaybePointerToCFRef;
4071
4072 default:
4073 return PointerDeclaratorKind::MultiLevelPointer;
4074 }
4075}
4076
4077static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4078 SourceLocation loc) {
4079 // If we're anywhere in a function, method, or closure context, don't perform
4080 // completeness checks.
4081 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4082 if (ctx->isFunctionOrMethod())
4083 return FileID();
4084
4085 if (ctx->isFileContext())
4086 break;
4087 }
4088
4089 // We only care about the expansion location.
4090 loc = S.SourceMgr.getExpansionLoc(Loc: loc);
4091 FileID file = S.SourceMgr.getFileID(SpellingLoc: loc);
4092 if (file.isInvalid())
4093 return FileID();
4094
4095 // Retrieve file information.
4096 bool invalid = false;
4097 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(FID: file, Invalid: &invalid);
4098 if (invalid || !sloc.isFile())
4099 return FileID();
4100
4101 // We don't want to perform completeness checks on the main file or in
4102 // system headers.
4103 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4104 if (fileInfo.getIncludeLoc().isInvalid())
4105 return FileID();
4106 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4107 S.Diags.getSuppressSystemWarnings()) {
4108 return FileID();
4109 }
4110
4111 return file;
4112}
4113
4114/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4115/// taking into account whitespace before and after.
4116template <typename DiagBuilderT>
4117static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4118 SourceLocation PointerLoc,
4119 NullabilityKind Nullability) {
4120 assert(PointerLoc.isValid());
4121 if (PointerLoc.isMacroID())
4122 return;
4123
4124 SourceLocation FixItLoc = S.getLocForEndOfToken(Loc: PointerLoc);
4125 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4126 return;
4127
4128 const char *NextChar = S.SourceMgr.getCharacterData(SL: FixItLoc);
4129 if (!NextChar)
4130 return;
4131
4132 SmallString<32> InsertionTextBuf{" "};
4133 InsertionTextBuf += getNullabilitySpelling(kind: Nullability);
4134 InsertionTextBuf += " ";
4135 StringRef InsertionText = InsertionTextBuf.str();
4136
4137 if (isWhitespace(c: *NextChar)) {
4138 InsertionText = InsertionText.drop_back();
4139 } else if (NextChar[-1] == '[') {
4140 if (NextChar[0] == ']')
4141 InsertionText = InsertionText.drop_back().drop_front();
4142 else
4143 InsertionText = InsertionText.drop_front();
4144 } else if (!isAsciiIdentifierContinue(c: NextChar[0], /*allow dollar*/ AllowDollar: true) &&
4145 !isAsciiIdentifierContinue(c: NextChar[-1], /*allow dollar*/ AllowDollar: true)) {
4146 InsertionText = InsertionText.drop_back().drop_front();
4147 }
4148
4149 Diag << FixItHint::CreateInsertion(InsertionLoc: FixItLoc, Code: InsertionText);
4150}
4151
4152static void emitNullabilityConsistencyWarning(Sema &S,
4153 SimplePointerKind PointerKind,
4154 SourceLocation PointerLoc,
4155 SourceLocation PointerEndLoc) {
4156 assert(PointerLoc.isValid());
4157
4158 if (PointerKind == SimplePointerKind::Array) {
4159 S.Diag(Loc: PointerLoc, DiagID: diag::warn_nullability_missing_array);
4160 } else {
4161 S.Diag(Loc: PointerLoc, DiagID: diag::warn_nullability_missing)
4162 << static_cast<unsigned>(PointerKind);
4163 }
4164
4165 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4166 if (FixItLoc.isMacroID())
4167 return;
4168
4169 auto addFixIt = [&](NullabilityKind Nullability) {
4170 auto Diag = S.Diag(Loc: FixItLoc, DiagID: diag::note_nullability_fix_it);
4171 Diag << static_cast<unsigned>(Nullability);
4172 Diag << static_cast<unsigned>(PointerKind);
4173 fixItNullability(S, Diag, PointerLoc: FixItLoc, Nullability);
4174 };
4175 addFixIt(NullabilityKind::Nullable);
4176 addFixIt(NullabilityKind::NonNull);
4177}
4178
4179/// Complains about missing nullability if the file containing \p pointerLoc
4180/// has other uses of nullability (either the keywords or the \c assume_nonnull
4181/// pragma).
4182///
4183/// If the file has \e not seen other uses of nullability, this particular
4184/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4185static void
4186checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4187 SourceLocation pointerLoc,
4188 SourceLocation pointerEndLoc = SourceLocation()) {
4189 // Determine which file we're performing consistency checking for.
4190 FileID file = getNullabilityCompletenessCheckFileID(S, loc: pointerLoc);
4191 if (file.isInvalid())
4192 return;
4193
4194 // If we haven't seen any type nullability in this file, we won't warn now
4195 // about anything.
4196 FileNullability &fileNullability = S.NullabilityMap[file];
4197 if (!fileNullability.SawTypeNullability) {
4198 // If this is the first pointer declarator in the file, and the appropriate
4199 // warning is on, record it in case we need to diagnose it retroactively.
4200 diag::kind diagKind;
4201 if (pointerKind == SimplePointerKind::Array)
4202 diagKind = diag::warn_nullability_missing_array;
4203 else
4204 diagKind = diag::warn_nullability_missing;
4205
4206 if (fileNullability.PointerLoc.isInvalid() &&
4207 !S.Context.getDiagnostics().isIgnored(DiagID: diagKind, Loc: pointerLoc)) {
4208 fileNullability.PointerLoc = pointerLoc;
4209 fileNullability.PointerEndLoc = pointerEndLoc;
4210 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4211 }
4212
4213 return;
4214 }
4215
4216 // Complain about missing nullability.
4217 emitNullabilityConsistencyWarning(S, PointerKind: pointerKind, PointerLoc: pointerLoc, PointerEndLoc: pointerEndLoc);
4218}
4219
4220/// Marks that a nullability feature has been used in the file containing
4221/// \p loc.
4222///
4223/// If this file already had pointer types in it that were missing nullability,
4224/// the first such instance is retroactively diagnosed.
4225///
4226/// \sa checkNullabilityConsistency
4227static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4228 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4229 if (file.isInvalid())
4230 return;
4231
4232 FileNullability &fileNullability = S.NullabilityMap[file];
4233 if (fileNullability.SawTypeNullability)
4234 return;
4235 fileNullability.SawTypeNullability = true;
4236
4237 // If we haven't seen any type nullability before, now we have. Retroactively
4238 // diagnose the first unannotated pointer, if there was one.
4239 if (fileNullability.PointerLoc.isInvalid())
4240 return;
4241
4242 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4243 emitNullabilityConsistencyWarning(S, PointerKind: kind, PointerLoc: fileNullability.PointerLoc,
4244 PointerEndLoc: fileNullability.PointerEndLoc);
4245}
4246
4247/// Returns true if any of the declarator chunks before \p endIndex include a
4248/// level of indirection: array, pointer, reference, or pointer-to-member.
4249///
4250/// Because declarator chunks are stored in outer-to-inner order, testing
4251/// every chunk before \p endIndex is testing all chunks that embed the current
4252/// chunk as part of their type.
4253///
4254/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4255/// end index, in which case all chunks are tested.
4256static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4257 unsigned i = endIndex;
4258 while (i != 0) {
4259 // Walk outwards along the declarator chunks.
4260 --i;
4261 const DeclaratorChunk &DC = D.getTypeObject(i);
4262 switch (DC.Kind) {
4263 case DeclaratorChunk::Paren:
4264 break;
4265 case DeclaratorChunk::Array:
4266 case DeclaratorChunk::Pointer:
4267 case DeclaratorChunk::Reference:
4268 case DeclaratorChunk::MemberPointer:
4269 return true;
4270 case DeclaratorChunk::Function:
4271 case DeclaratorChunk::BlockPointer:
4272 case DeclaratorChunk::Pipe:
4273 // These are invalid anyway, so just ignore.
4274 break;
4275 }
4276 }
4277 return false;
4278}
4279
4280static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4281 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4282 Chunk.Kind == DeclaratorChunk::Array);
4283}
4284
4285template<typename AttrT>
4286static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4287 AL.setUsedAsTypeAttr();
4288 return ::new (Ctx) AttrT(Ctx, AL);
4289}
4290
4291static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4292 NullabilityKind NK) {
4293 switch (NK) {
4294 case NullabilityKind::NonNull:
4295 return createSimpleAttr<TypeNonNullAttr>(Ctx, AL&: Attr);
4296
4297 case NullabilityKind::Nullable:
4298 return createSimpleAttr<TypeNullableAttr>(Ctx, AL&: Attr);
4299
4300 case NullabilityKind::NullableResult:
4301 return createSimpleAttr<TypeNullableResultAttr>(Ctx, AL&: Attr);
4302
4303 case NullabilityKind::Unspecified:
4304 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, AL&: Attr);
4305 }
4306 llvm_unreachable("unknown NullabilityKind");
4307}
4308
4309// Diagnose whether this is a case with the multiple addr spaces.
4310// Returns true if this is an invalid case.
4311// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4312// by qualifiers for two or more different address spaces."
4313static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4314 LangAS ASNew,
4315 SourceLocation AttrLoc) {
4316 if (ASOld != LangAS::Default) {
4317 if (ASOld != ASNew) {
4318 S.Diag(Loc: AttrLoc, DiagID: diag::err_attribute_address_multiple_qualifiers);
4319 return true;
4320 }
4321 // Emit a warning if they are identical; it's likely unintended.
4322 S.Diag(Loc: AttrLoc,
4323 DiagID: diag::warn_attribute_address_multiple_identical_qualifiers);
4324 }
4325 return false;
4326}
4327
4328// Whether this is a type broadly expected to have nullability attached.
4329// These types are affected by `#pragma assume_nonnull`, and missing nullability
4330// will be diagnosed with -Wnullability-completeness.
4331static bool shouldHaveNullability(QualType T) {
4332 return T->canHaveNullability(/*ResultIfUnknown=*/false) &&
4333 // For now, do not infer/require nullability on C++ smart pointers.
4334 // It's unclear whether the pragma's behavior is useful for C++.
4335 // e.g. treating type-aliases and template-type-parameters differently
4336 // from types of declarations can be surprising.
4337 !isa<RecordType, TemplateSpecializationType>(
4338 Val: T->getCanonicalTypeInternal());
4339}
4340
4341static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4342 QualType declSpecType,
4343 TypeSourceInfo *TInfo) {
4344 // The TypeSourceInfo that this function returns will not be a null type.
4345 // If there is an error, this function will fill in a dummy type as fallback.
4346 QualType T = declSpecType;
4347 Declarator &D = state.getDeclarator();
4348 Sema &S = state.getSema();
4349 ASTContext &Context = S.Context;
4350 const LangOptions &LangOpts = S.getLangOpts();
4351
4352 // The name we're declaring, if any.
4353 DeclarationName Name;
4354 if (D.getIdentifier())
4355 Name = D.getIdentifier();
4356
4357 // Does this declaration declare a typedef-name?
4358 bool IsTypedefName =
4359 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4360 D.getContext() == DeclaratorContext::AliasDecl ||
4361 D.getContext() == DeclaratorContext::AliasTemplate;
4362
4363 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4364 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4365 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4366 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4367
4368 // If T is 'decltype(auto)', the only declarators we can have are parens
4369 // and at most one function declarator if this is a function declaration.
4370 // If T is a deduced class template specialization type, only parentheses
4371 // are allowed.
4372 if (auto *DT = T->getAs<DeducedType>()) {
4373 const AutoType *AT = T->getAs<AutoType>();
4374 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(Val: DT);
4375 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4376 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4377 unsigned Index = E - I - 1;
4378 DeclaratorChunk &DeclChunk = D.getTypeObject(i: Index);
4379 unsigned DiagId = IsClassTemplateDeduction
4380 ? diag::err_deduced_class_template_compound_type
4381 : diag::err_decltype_auto_compound_type;
4382 unsigned DiagKind = 0;
4383 switch (DeclChunk.Kind) {
4384 case DeclaratorChunk::Paren:
4385 continue;
4386 case DeclaratorChunk::Function: {
4387 if (IsClassTemplateDeduction) {
4388 DiagKind = 3;
4389 break;
4390 }
4391 unsigned FnIndex;
4392 if (D.isFunctionDeclarationContext() &&
4393 D.isFunctionDeclarator(idx&: FnIndex) && FnIndex == Index)
4394 continue;
4395 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4396 break;
4397 }
4398 case DeclaratorChunk::Pointer:
4399 case DeclaratorChunk::BlockPointer:
4400 case DeclaratorChunk::MemberPointer:
4401 DiagKind = 0;
4402 break;
4403 case DeclaratorChunk::Reference:
4404 DiagKind = 1;
4405 break;
4406 case DeclaratorChunk::Array:
4407 DiagKind = 2;
4408 break;
4409 case DeclaratorChunk::Pipe:
4410 break;
4411 }
4412
4413 S.Diag(Loc: DeclChunk.Loc, DiagID: DiagId) << DiagKind;
4414 D.setInvalidType(true);
4415 break;
4416 }
4417 }
4418 }
4419
4420 // Determine whether we should infer _Nonnull on pointer types.
4421 NullabilityKindOrNone inferNullability = std::nullopt;
4422 bool inferNullabilityCS = false;
4423 bool inferNullabilityInnerOnly = false;
4424 bool inferNullabilityInnerOnlyComplete = false;
4425
4426 // Are we in an assume-nonnull region?
4427 bool inAssumeNonNullRegion = false;
4428 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4429 if (assumeNonNullLoc.isValid()) {
4430 inAssumeNonNullRegion = true;
4431 recordNullabilitySeen(S, loc: assumeNonNullLoc);
4432 }
4433
4434 // Whether to complain about missing nullability specifiers or not.
4435 enum {
4436 /// Never complain.
4437 CAMN_No,
4438 /// Complain on the inner pointers (but not the outermost
4439 /// pointer).
4440 CAMN_InnerPointers,
4441 /// Complain about any pointers that don't have nullability
4442 /// specified or inferred.
4443 CAMN_Yes
4444 } complainAboutMissingNullability = CAMN_No;
4445 unsigned NumPointersRemaining = 0;
4446 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4447
4448 if (IsTypedefName) {
4449 // For typedefs, we do not infer any nullability (the default),
4450 // and we only complain about missing nullability specifiers on
4451 // inner pointers.
4452 complainAboutMissingNullability = CAMN_InnerPointers;
4453
4454 if (shouldHaveNullability(T) && !T->getNullability()) {
4455 // Note that we allow but don't require nullability on dependent types.
4456 ++NumPointersRemaining;
4457 }
4458
4459 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4460 DeclaratorChunk &chunk = D.getTypeObject(i);
4461 switch (chunk.Kind) {
4462 case DeclaratorChunk::Array:
4463 case DeclaratorChunk::Function:
4464 case DeclaratorChunk::Pipe:
4465 break;
4466
4467 case DeclaratorChunk::BlockPointer:
4468 case DeclaratorChunk::MemberPointer:
4469 ++NumPointersRemaining;
4470 break;
4471
4472 case DeclaratorChunk::Paren:
4473 case DeclaratorChunk::Reference:
4474 continue;
4475
4476 case DeclaratorChunk::Pointer:
4477 ++NumPointersRemaining;
4478 continue;
4479 }
4480 }
4481 } else {
4482 bool isFunctionOrMethod = false;
4483 switch (auto context = state.getDeclarator().getContext()) {
4484 case DeclaratorContext::ObjCParameter:
4485 case DeclaratorContext::ObjCResult:
4486 case DeclaratorContext::Prototype:
4487 case DeclaratorContext::TrailingReturn:
4488 case DeclaratorContext::TrailingReturnVar:
4489 isFunctionOrMethod = true;
4490 [[fallthrough]];
4491
4492 case DeclaratorContext::Member:
4493 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4494 complainAboutMissingNullability = CAMN_No;
4495 break;
4496 }
4497
4498 // Weak properties are inferred to be nullable.
4499 if (state.getDeclarator().isObjCWeakProperty()) {
4500 // Weak properties cannot be nonnull, and should not complain about
4501 // missing nullable attributes during completeness checks.
4502 complainAboutMissingNullability = CAMN_No;
4503 if (inAssumeNonNullRegion) {
4504 inferNullability = NullabilityKind::Nullable;
4505 }
4506 break;
4507 }
4508
4509 [[fallthrough]];
4510
4511 case DeclaratorContext::File:
4512 case DeclaratorContext::KNRTypeList: {
4513 complainAboutMissingNullability = CAMN_Yes;
4514
4515 // Nullability inference depends on the type and declarator.
4516 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4517 switch (classifyPointerDeclarator(S, type: T, declarator&: D, wrappingKind)) {
4518 case PointerDeclaratorKind::NonPointer:
4519 case PointerDeclaratorKind::MultiLevelPointer:
4520 // Cannot infer nullability.
4521 break;
4522
4523 case PointerDeclaratorKind::SingleLevelPointer:
4524 // Infer _Nonnull if we are in an assumes-nonnull region.
4525 if (inAssumeNonNullRegion) {
4526 complainAboutInferringWithinChunk = wrappingKind;
4527 inferNullability = NullabilityKind::NonNull;
4528 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4529 context == DeclaratorContext::ObjCResult);
4530 }
4531 break;
4532
4533 case PointerDeclaratorKind::CFErrorRefPointer:
4534 case PointerDeclaratorKind::NSErrorPointerPointer:
4535 // Within a function or method signature, infer _Nullable at both
4536 // levels.
4537 if (isFunctionOrMethod && inAssumeNonNullRegion)
4538 inferNullability = NullabilityKind::Nullable;
4539 break;
4540
4541 case PointerDeclaratorKind::MaybePointerToCFRef:
4542 if (isFunctionOrMethod) {
4543 // On pointer-to-pointer parameters marked cf_returns_retained or
4544 // cf_returns_not_retained, if the outer pointer is explicit then
4545 // infer the inner pointer as _Nullable.
4546 auto hasCFReturnsAttr =
4547 [](const ParsedAttributesView &AttrList) -> bool {
4548 return AttrList.hasAttribute(K: ParsedAttr::AT_CFReturnsRetained) ||
4549 AttrList.hasAttribute(K: ParsedAttr::AT_CFReturnsNotRetained);
4550 };
4551 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4552 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4553 hasCFReturnsAttr(D.getAttributes()) ||
4554 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4555 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4556 inferNullability = NullabilityKind::Nullable;
4557 inferNullabilityInnerOnly = true;
4558 }
4559 }
4560 }
4561 break;
4562 }
4563 break;
4564 }
4565
4566 case DeclaratorContext::ConversionId:
4567 complainAboutMissingNullability = CAMN_Yes;
4568 break;
4569
4570 case DeclaratorContext::AliasDecl:
4571 case DeclaratorContext::AliasTemplate:
4572 case DeclaratorContext::Block:
4573 case DeclaratorContext::BlockLiteral:
4574 case DeclaratorContext::Condition:
4575 case DeclaratorContext::CXXCatch:
4576 case DeclaratorContext::CXXNew:
4577 case DeclaratorContext::ForInit:
4578 case DeclaratorContext::SelectionInit:
4579 case DeclaratorContext::LambdaExpr:
4580 case DeclaratorContext::LambdaExprParameter:
4581 case DeclaratorContext::ObjCCatch:
4582 case DeclaratorContext::TemplateParam:
4583 case DeclaratorContext::TemplateArg:
4584 case DeclaratorContext::TemplateTypeArg:
4585 case DeclaratorContext::TypeName:
4586 case DeclaratorContext::FunctionalCast:
4587 case DeclaratorContext::RequiresExpr:
4588 case DeclaratorContext::Association:
4589 // Don't infer in these contexts.
4590 break;
4591 }
4592 }
4593
4594 // Local function that returns true if its argument looks like a va_list.
4595 auto isVaList = [&S](QualType T) -> bool {
4596 auto *typedefTy = T->getAs<TypedefType>();
4597 if (!typedefTy)
4598 return false;
4599 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4600 do {
4601 if (typedefTy->getDecl() == vaListTypedef)
4602 return true;
4603 if (auto *name = typedefTy->getDecl()->getIdentifier())
4604 if (name->isStr(Str: "va_list"))
4605 return true;
4606 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4607 } while (typedefTy);
4608 return false;
4609 };
4610
4611 // Local function that checks the nullability for a given pointer declarator.
4612 // Returns true if _Nonnull was inferred.
4613 auto inferPointerNullability =
4614 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4615 SourceLocation pointerEndLoc,
4616 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4617 // We've seen a pointer.
4618 if (NumPointersRemaining > 0)
4619 --NumPointersRemaining;
4620
4621 // If a nullability attribute is present, there's nothing to do.
4622 if (hasNullabilityAttr(attrs))
4623 return nullptr;
4624
4625 // If we're supposed to infer nullability, do so now.
4626 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4627 ParsedAttr::Form form =
4628 inferNullabilityCS
4629 ? ParsedAttr::Form::ContextSensitiveKeyword()
4630 : ParsedAttr::Form::Keyword(IsAlignas: false /*IsAlignAs*/,
4631 IsRegularKeywordAttribute: false /*IsRegularKeywordAttribute*/);
4632 ParsedAttr *nullabilityAttr = Pool.create(
4633 attrName: S.getNullabilityKeyword(nullability: *inferNullability), attrRange: SourceRange(pointerLoc),
4634 scope: AttributeScopeInfo(), args: nullptr, numArgs: 0, form);
4635
4636 attrs.addAtEnd(newAttr: nullabilityAttr);
4637
4638 if (inferNullabilityCS) {
4639 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4640 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4641 }
4642
4643 if (pointerLoc.isValid() &&
4644 complainAboutInferringWithinChunk !=
4645 PointerWrappingDeclaratorKind::None) {
4646 auto Diag =
4647 S.Diag(Loc: pointerLoc, DiagID: diag::warn_nullability_inferred_on_nested_type);
4648 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4649 fixItNullability(S, Diag, PointerLoc: pointerLoc, Nullability: NullabilityKind::NonNull);
4650 }
4651
4652 if (inferNullabilityInnerOnly)
4653 inferNullabilityInnerOnlyComplete = true;
4654 return nullabilityAttr;
4655 }
4656
4657 // If we're supposed to complain about missing nullability, do so
4658 // now if it's truly missing.
4659 switch (complainAboutMissingNullability) {
4660 case CAMN_No:
4661 break;
4662
4663 case CAMN_InnerPointers:
4664 if (NumPointersRemaining == 0)
4665 break;
4666 [[fallthrough]];
4667
4668 case CAMN_Yes:
4669 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4670 }
4671 return nullptr;
4672 };
4673
4674 // If the type itself could have nullability but does not, infer pointer
4675 // nullability and perform consistency checking.
4676 if (S.CodeSynthesisContexts.empty()) {
4677 if (shouldHaveNullability(T) && !T->getNullability()) {
4678 if (isVaList(T)) {
4679 // Record that we've seen a pointer, but do nothing else.
4680 if (NumPointersRemaining > 0)
4681 --NumPointersRemaining;
4682 } else {
4683 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4684 if (T->isBlockPointerType())
4685 pointerKind = SimplePointerKind::BlockPointer;
4686 else if (T->isMemberPointerType())
4687 pointerKind = SimplePointerKind::MemberPointer;
4688
4689 if (auto *attr = inferPointerNullability(
4690 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4691 D.getDeclSpec().getEndLoc(),
4692 D.getMutableDeclSpec().getAttributes(),
4693 D.getMutableDeclSpec().getAttributePool())) {
4694 T = state.getAttributedType(
4695 A: createNullabilityAttr(Ctx&: Context, Attr&: *attr, NK: *inferNullability), ModifiedType: T, EquivType: T);
4696 }
4697 }
4698 }
4699
4700 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
4701 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
4702 !hasOuterPointerLikeChunk(D, endIndex: D.getNumTypeObjects())) {
4703 checkNullabilityConsistency(S, pointerKind: SimplePointerKind::Array,
4704 pointerLoc: D.getDeclSpec().getTypeSpecTypeLoc());
4705 }
4706 }
4707
4708 bool ExpectNoDerefChunk =
4709 state.getCurrentAttributes().hasAttribute(K: ParsedAttr::AT_NoDeref);
4710
4711 // Walk the DeclTypeInfo, building the recursive type as we go.
4712 // DeclTypeInfos are ordered from the identifier out, which is
4713 // opposite of what we want :).
4714
4715 // Track if the produced type matches the structure of the declarator.
4716 // This is used later to decide if we can fill `TypeLoc` from
4717 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
4718 // an error by replacing the type with `int`.
4719 bool AreDeclaratorChunksValid = true;
4720 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4721 unsigned chunkIndex = e - i - 1;
4722 state.setCurrentChunkIndex(chunkIndex);
4723 DeclaratorChunk &DeclType = D.getTypeObject(i: chunkIndex);
4724 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4725 switch (DeclType.Kind) {
4726 case DeclaratorChunk::Paren:
4727 if (i == 0)
4728 warnAboutRedundantParens(S, D, T);
4729 T = S.BuildParenType(T);
4730 break;
4731 case DeclaratorChunk::BlockPointer:
4732 // If blocks are disabled, emit an error.
4733 if (!LangOpts.Blocks)
4734 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL;
4735
4736 // Handle pointer nullability.
4737 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4738 DeclType.EndLoc, DeclType.getAttrs(),
4739 state.getDeclarator().getAttributePool());
4740
4741 T = S.BuildBlockPointerType(T, Loc: D.getIdentifierLoc(), Entity: Name);
4742 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4743 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4744 // qualified with const.
4745 if (LangOpts.OpenCL)
4746 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4747 T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: DeclType.Cls.TypeQuals);
4748 }
4749 break;
4750 case DeclaratorChunk::Pointer:
4751 // Verify that we're not building a pointer to pointer to function with
4752 // exception specification.
4753 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4754 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_distant_exception_spec);
4755 D.setInvalidType(true);
4756 // Build the type anyway.
4757 }
4758
4759 // Handle pointer nullability
4760 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4761 DeclType.EndLoc, DeclType.getAttrs(),
4762 state.getDeclarator().getAttributePool());
4763
4764 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4765 T = Context.getObjCObjectPointerType(OIT: T);
4766 if (DeclType.Ptr.TypeQuals)
4767 T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: DeclType.Ptr.TypeQuals);
4768 break;
4769 }
4770
4771 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4772 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4773 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4774 if (LangOpts.OpenCL) {
4775 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4776 T->isBlockPointerType()) {
4777 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_opencl_pointer_to_type) << T;
4778 D.setInvalidType(true);
4779 }
4780 }
4781
4782 T = S.BuildPointerType(T, Loc: DeclType.Loc, Entity: Name);
4783 if (DeclType.Ptr.TypeQuals)
4784 T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: DeclType.Ptr.TypeQuals);
4785 if (DeclType.Ptr.OverflowBehaviorLoc.isValid()) {
4786 auto OBState = DeclType.Ptr.OverflowBehaviorIsWrap
4787 ? DeclSpec::OverflowBehaviorState::Wrap
4788 : DeclSpec::OverflowBehaviorState::Trap;
4789 S.Diag(Loc: DeclType.Ptr.OverflowBehaviorLoc,
4790 DiagID: diag::err_overflow_behavior_non_integer_type)
4791 << DeclSpec::getSpecifierName(S: OBState) << T.getAsString() << 1;
4792 D.setInvalidType(true);
4793 }
4794 break;
4795 case DeclaratorChunk::Reference: {
4796 // Verify that we're not building a reference to pointer to function with
4797 // exception specification.
4798 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4799 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_distant_exception_spec);
4800 D.setInvalidType(true);
4801 // Build the type anyway.
4802 }
4803 T = S.BuildReferenceType(T, SpelledAsLValue: DeclType.Ref.LValueRef, Loc: DeclType.Loc, Entity: Name);
4804
4805 if (DeclType.Ref.HasRestrict)
4806 T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: Qualifiers::Restrict);
4807 break;
4808 }
4809 case DeclaratorChunk::Array: {
4810 // Verify that we're not building an array of pointers to function with
4811 // exception specification.
4812 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4813 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_distant_exception_spec);
4814 D.setInvalidType(true);
4815 // Build the type anyway.
4816 }
4817 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4818 Expr *ArraySize = ATI.NumElts;
4819 ArraySizeModifier ASM;
4820
4821 // Microsoft property fields can have multiple sizeless array chunks
4822 // (i.e. int x[][][]). Skip all of these except one to avoid creating
4823 // bad incomplete array types.
4824 if (chunkIndex != 0 && !ArraySize &&
4825 D.getDeclSpec().getAttributes().hasMSPropertyAttr()) {
4826 // This is a sizeless chunk. If the next is also, skip this one.
4827 DeclaratorChunk &NextDeclType = D.getTypeObject(i: chunkIndex - 1);
4828 if (NextDeclType.Kind == DeclaratorChunk::Array &&
4829 !NextDeclType.Arr.NumElts)
4830 break;
4831 }
4832
4833 if (ATI.isStar)
4834 ASM = ArraySizeModifier::Star;
4835 else if (ATI.hasStatic)
4836 ASM = ArraySizeModifier::Static;
4837 else
4838 ASM = ArraySizeModifier::Normal;
4839 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) {
4840 // FIXME: This check isn't quite right: it allows star in prototypes
4841 // for function definitions, and disallows some edge cases detailed
4842 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4843 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_array_star_outside_prototype);
4844 ASM = ArraySizeModifier::Normal;
4845 D.setInvalidType(true);
4846 }
4847
4848 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4849 // shall appear only in a declaration of a function parameter with an
4850 // array type, ...
4851 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) {
4852 if (!(D.isPrototypeContext() ||
4853 D.getContext() == DeclaratorContext::KNRTypeList)) {
4854 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_array_static_outside_prototype)
4855 << (ASM == ArraySizeModifier::Static ? "'static'"
4856 : "type qualifier");
4857 // Remove the 'static' and the type qualifiers.
4858 if (ASM == ArraySizeModifier::Static)
4859 ASM = ArraySizeModifier::Normal;
4860 ATI.TypeQuals = 0;
4861 D.setInvalidType(true);
4862 }
4863
4864 // C99 6.7.5.2p1: ... and then only in the outermost array type
4865 // derivation.
4866 if (hasOuterPointerLikeChunk(D, endIndex: chunkIndex)) {
4867 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_array_static_not_outermost)
4868 << (ASM == ArraySizeModifier::Static ? "'static'"
4869 : "type qualifier");
4870 if (ASM == ArraySizeModifier::Static)
4871 ASM = ArraySizeModifier::Normal;
4872 ATI.TypeQuals = 0;
4873 D.setInvalidType(true);
4874 }
4875 }
4876
4877 // Array parameters can be marked nullable as well, although it's not
4878 // necessary if they're marked 'static'.
4879 if (complainAboutMissingNullability == CAMN_Yes &&
4880 !hasNullabilityAttr(attrs: DeclType.getAttrs()) &&
4881 ASM != ArraySizeModifier::Static && D.isPrototypeContext() &&
4882 !hasOuterPointerLikeChunk(D, endIndex: chunkIndex)) {
4883 checkNullabilityConsistency(S, pointerKind: SimplePointerKind::Array, pointerLoc: DeclType.Loc);
4884 }
4885
4886 T = S.BuildArrayType(T, ASM, ArraySize, Quals: ATI.TypeQuals,
4887 Brackets: SourceRange(DeclType.Loc, DeclType.EndLoc), Entity: Name);
4888 break;
4889 }
4890 case DeclaratorChunk::Function: {
4891 // If the function declarator has a prototype (i.e. it is not () and
4892 // does not have a K&R-style identifier list), then the arguments are part
4893 // of the type, otherwise the argument list is ().
4894 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4895 IsQualifiedFunction =
4896 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
4897
4898 auto IsClassType = [&](CXXScopeSpec &SS) {
4899 // If there already was an problem with the scope, don’t issue another
4900 // error about the explicit object parameter.
4901 return SS.isInvalid() ||
4902 isa_and_present<CXXRecordDecl>(Val: S.computeDeclContext(SS));
4903 };
4904
4905 // C++23 [dcl.fct]p6:
4906 //
4907 // An explicit-object-parameter-declaration is a parameter-declaration
4908 // with a this specifier. An explicit-object-parameter-declaration shall
4909 // appear only as the first parameter-declaration of a
4910 // parameter-declaration-list of one of:
4911 //
4912 // - a declaration of a member function or member function template
4913 // ([class.mem]), or
4914 //
4915 // - an explicit instantiation ([temp.explicit]) or explicit
4916 // specialization ([temp.expl.spec]) of a templated member function,
4917 // or
4918 //
4919 // - a lambda-declarator [expr.prim.lambda].
4920 DeclaratorContext C = D.getContext();
4921 ParmVarDecl *First =
4922 FTI.NumParams ? dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param)
4923 : nullptr;
4924
4925 bool IsFunctionDecl = D.getInnermostNonParenChunk() == &DeclType;
4926 if (First && First->isExplicitObjectParameter() &&
4927 C != DeclaratorContext::LambdaExpr &&
4928
4929 // Either not a member or nested declarator in a member.
4930 //
4931 // Note that e.g. 'static' or 'friend' declarations are accepted
4932 // here; we diagnose them later when we build the member function
4933 // because it's easier that way.
4934 (C != DeclaratorContext::Member || !IsFunctionDecl) &&
4935
4936 // Allow out-of-line definitions of member functions.
4937 !IsClassType(D.getCXXScopeSpec())) {
4938 if (IsFunctionDecl)
4939 S.Diag(Loc: First->getBeginLoc(),
4940 DiagID: diag::err_explicit_object_parameter_nonmember)
4941 << /*non-member*/ 2 << /*function*/ 0 << First->getSourceRange();
4942 else
4943 S.Diag(Loc: First->getBeginLoc(),
4944 DiagID: diag::err_explicit_object_parameter_invalid)
4945 << First->getSourceRange();
4946
4947 // Do let non-member function have explicit parameters
4948 // to not break assumptions elsewhere in the code.
4949 First->setExplicitObjectParameterLoc(SourceLocation());
4950 D.setInvalidType();
4951 AreDeclaratorChunksValid = false;
4952 }
4953
4954 // Check for auto functions and trailing return type and adjust the
4955 // return type accordingly.
4956 if (!D.isInvalidType()) {
4957 // trailing-return-type is only required if we're declaring a function,
4958 // and not, for instance, a pointer to a function.
4959 if (D.getDeclSpec().hasAutoTypeSpec() &&
4960 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4961 if (!S.getLangOpts().CPlusPlus14) {
4962 S.Diag(Loc: D.getDeclSpec().getTypeSpecTypeLoc(),
4963 DiagID: D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4964 ? diag::err_auto_missing_trailing_return
4965 : diag::err_deduced_return_type);
4966 T = Context.IntTy;
4967 D.setInvalidType(true);
4968 AreDeclaratorChunksValid = false;
4969 } else {
4970 S.Diag(Loc: D.getDeclSpec().getTypeSpecTypeLoc(),
4971 DiagID: diag::warn_cxx11_compat_deduced_return_type);
4972 }
4973 } else if (FTI.hasTrailingReturnType()) {
4974 // T must be exactly 'auto' at this point. See CWG issue 681.
4975 if (isa<ParenType>(Val: T)) {
4976 S.Diag(Loc: D.getBeginLoc(), DiagID: diag::err_trailing_return_in_parens)
4977 << T << D.getSourceRange();
4978 D.setInvalidType(true);
4979 // FIXME: recover and fill decls in `TypeLoc`s.
4980 AreDeclaratorChunksValid = false;
4981 } else if (D.getName().getKind() ==
4982 UnqualifiedIdKind::IK_DeductionGuideName) {
4983 if (T != Context.DependentTy) {
4984 S.Diag(Loc: D.getDeclSpec().getBeginLoc(),
4985 DiagID: diag::err_deduction_guide_with_complex_decl)
4986 << D.getSourceRange();
4987 D.setInvalidType(true);
4988 // FIXME: recover and fill decls in `TypeLoc`s.
4989 AreDeclaratorChunksValid = false;
4990 }
4991 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
4992 (T.hasQualifiers() || !isa<AutoType>(Val: T) ||
4993 cast<AutoType>(Val&: T)->getKeyword() !=
4994 AutoTypeKeyword::Auto ||
4995 cast<AutoType>(Val&: T)->isConstrained())) {
4996 // Attach a valid source location for diagnostics on functions with
4997 // trailing return types missing 'auto'. Attempt to get the location
4998 // from the declared type; if invalid, fall back to the trailing
4999 // return type's location.
5000 SourceLocation Loc = D.getDeclSpec().getTypeSpecTypeLoc();
5001 SourceRange SR = D.getDeclSpec().getSourceRange();
5002 if (Loc.isInvalid()) {
5003 Loc = FTI.getTrailingReturnTypeLoc();
5004 SR = D.getSourceRange();
5005 }
5006 S.Diag(Loc, DiagID: diag::err_trailing_return_without_auto) << T << SR;
5007 D.setInvalidType(true);
5008 // FIXME: recover and fill decls in `TypeLoc`s.
5009 AreDeclaratorChunksValid = false;
5010 }
5011 T = S.GetTypeFromParser(Ty: FTI.getTrailingReturnType(), TInfo: &TInfo);
5012 if (T.isNull()) {
5013 // An error occurred parsing the trailing return type.
5014 T = Context.IntTy;
5015 D.setInvalidType(true);
5016 } else if (AutoType *Auto = T->getContainedAutoType()) {
5017 // If the trailing return type contains an `auto`, we may need to
5018 // invent a template parameter for it, for cases like
5019 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5020 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5021 if (D.getContext() == DeclaratorContext::Prototype)
5022 InventedParamInfo = &S.InventedParameterInfos.back();
5023 else if (D.getContext() == DeclaratorContext::LambdaExprParameter)
5024 InventedParamInfo = S.getCurLambda();
5025 if (InventedParamInfo) {
5026 std::tie(args&: T, args&: TInfo) = InventTemplateParameter(
5027 state, T, TrailingTSI: TInfo, Auto, Info&: *InventedParamInfo);
5028 }
5029 }
5030 } else {
5031 // This function type is not the type of the entity being declared,
5032 // so checking the 'auto' is not the responsibility of this chunk.
5033 }
5034 }
5035
5036 // C99 6.7.5.3p1: The return type may not be a function or array type.
5037 // For conversion functions, we'll diagnose this particular error later.
5038 if (!D.isInvalidType() &&
5039 ((T->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
5040 T->isFunctionType()) &&
5041 (D.getName().getKind() !=
5042 UnqualifiedIdKind::IK_ConversionFunctionId)) {
5043 unsigned diagID = diag::err_func_returning_array_function;
5044 // Last processing chunk in block context means this function chunk
5045 // represents the block.
5046 if (chunkIndex == 0 &&
5047 D.getContext() == DeclaratorContext::BlockLiteral)
5048 diagID = diag::err_block_returning_array_function;
5049 S.Diag(Loc: DeclType.Loc, DiagID: diagID) << T->isFunctionType() << T;
5050 T = Context.IntTy;
5051 D.setInvalidType(true);
5052 AreDeclaratorChunksValid = false;
5053 }
5054
5055 // Do not allow returning half FP value.
5056 // FIXME: This really should be in BuildFunctionType.
5057 if (T->isHalfType()) {
5058 if (S.getLangOpts().OpenCL) {
5059 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
5060 LO: S.getLangOpts())) {
5061 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_opencl_invalid_return)
5062 << T << 0 /*pointer hint*/;
5063 D.setInvalidType(true);
5064 }
5065 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5066 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5067 S.Diag(Loc: D.getIdentifierLoc(),
5068 DiagID: diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5069 D.setInvalidType(true);
5070 }
5071 }
5072
5073 // __ptrauth is illegal on a function return type.
5074 if (T.getPointerAuth()) {
5075 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 0;
5076 }
5077
5078 if (LangOpts.OpenCL) {
5079 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5080 // function.
5081 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5082 T->isPipeType()) {
5083 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_opencl_invalid_return)
5084 << T << 1 /*hint off*/;
5085 D.setInvalidType(true);
5086 }
5087 // OpenCL doesn't support variadic functions and blocks
5088 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5089 // We also allow here any toolchain reserved identifiers.
5090 if (FTI.isVariadic &&
5091 !S.getOpenCLOptions().isAvailableOption(
5092 Ext: "__cl_clang_variadic_functions", LO: S.getLangOpts()) &&
5093 !(D.getIdentifier() &&
5094 ((D.getIdentifier()->getName() == "printf" &&
5095 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5096 D.getIdentifier()->getName().starts_with(Prefix: "__")))) {
5097 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_opencl_variadic_function);
5098 D.setInvalidType(true);
5099 }
5100 }
5101
5102 // Methods cannot return interface types. All ObjC objects are
5103 // passed by reference.
5104 if (T->isObjCObjectType()) {
5105 SourceLocation DiagLoc, FixitLoc;
5106 if (TInfo) {
5107 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5108 FixitLoc = S.getLocForEndOfToken(Loc: TInfo->getTypeLoc().getEndLoc());
5109 } else {
5110 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5111 FixitLoc = S.getLocForEndOfToken(Loc: D.getDeclSpec().getEndLoc());
5112 }
5113 S.Diag(Loc: DiagLoc, DiagID: diag::err_object_cannot_be_passed_returned_by_value)
5114 << 0 << T
5115 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: "*");
5116
5117 T = Context.getObjCObjectPointerType(OIT: T);
5118 if (TInfo) {
5119 TypeLocBuilder TLB;
5120 TLB.pushFullCopy(L: TInfo->getTypeLoc());
5121 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
5122 TLoc.setStarLoc(FixitLoc);
5123 TInfo = TLB.getTypeSourceInfo(Context, T);
5124 } else {
5125 AreDeclaratorChunksValid = false;
5126 }
5127
5128 D.setInvalidType(true);
5129 }
5130
5131 // cv-qualifiers on return types are pointless except when the type is a
5132 // class type in C++.
5133 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5134 // A dependent type or an undeduced type might later become a class
5135 // type.
5136 !(S.getLangOpts().CPlusPlus &&
5137 (T->isRecordType() || T->isDependentType() ||
5138 T->isUndeducedAutoType()))) {
5139 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5140 D.getFunctionDefinitionKind() ==
5141 FunctionDefinitionKind::Definition) {
5142 // [6.9.1/3] qualified void return is invalid on a C
5143 // function definition. Apparently ok on declarations and
5144 // in C++ though (!)
5145 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_func_returning_qualified_void) << T;
5146 } else
5147 diagnoseRedundantReturnTypeQualifiers(S, RetTy: T, D, FunctionChunkIndex: chunkIndex);
5148 }
5149
5150 // C++2a [dcl.fct]p12:
5151 // A volatile-qualified return type is deprecated
5152 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5153 S.Diag(Loc: DeclType.Loc, DiagID: diag::warn_deprecated_volatile_return) << T;
5154
5155 // Objective-C ARC ownership qualifiers are ignored on the function
5156 // return type (by type canonicalization). Complain if this attribute
5157 // was written here.
5158 if (T.getQualifiers().hasObjCLifetime()) {
5159 SourceLocation AttrLoc;
5160 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5161 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(i: chunkIndex + 1);
5162 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5163 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5164 AttrLoc = AL.getLoc();
5165 break;
5166 }
5167 }
5168 }
5169 if (AttrLoc.isInvalid()) {
5170 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5171 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5172 AttrLoc = AL.getLoc();
5173 break;
5174 }
5175 }
5176 }
5177
5178 if (AttrLoc.isValid()) {
5179 // The ownership attributes are almost always written via
5180 // the predefined
5181 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5182 if (AttrLoc.isMacroID())
5183 AttrLoc =
5184 S.SourceMgr.getImmediateExpansionRange(Loc: AttrLoc).getBegin();
5185
5186 S.Diag(Loc: AttrLoc, DiagID: diag::warn_arc_lifetime_result_type)
5187 << T.getQualifiers().getObjCLifetime();
5188 }
5189 }
5190
5191 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5192 // C++ [dcl.fct]p6:
5193 // Types shall not be defined in return or parameter types.
5194 TagDecl *Tag = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
5195 S.Diag(Loc: Tag->getLocation(), DiagID: diag::err_type_defined_in_result_type)
5196 << Context.getCanonicalTagType(TD: Tag);
5197 }
5198
5199 // Exception specs are not allowed in typedefs. Complain, but add it
5200 // anyway.
5201 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5202 S.Diag(Loc: FTI.getExceptionSpecLocBeg(),
5203 DiagID: diag::err_exception_spec_in_typedef)
5204 << (D.getContext() == DeclaratorContext::AliasDecl ||
5205 D.getContext() == DeclaratorContext::AliasTemplate);
5206
5207 // If we see "T var();" or "T var(T());" at block scope, it is probably
5208 // an attempt to initialize a variable, not a function declaration.
5209 if (FTI.isAmbiguous)
5210 warnAboutAmbiguousFunction(S, D, DeclType, RT: T);
5211
5212 FunctionType::ExtInfo EI(
5213 getCCForDeclaratorChunk(S, D, AttrList: DeclType.getAttrs(), FTI, ChunkIndex: chunkIndex));
5214
5215 // OpenCL disallows functions without a prototype, but it doesn't enforce
5216 // strict prototypes as in C23 because it allows a function definition to
5217 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5218 if (!FTI.NumParams && !FTI.isVariadic &&
5219 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5220 // Simple void foo(), where the incoming T is the result type.
5221 T = Context.getFunctionNoProtoType(ResultTy: T, Info: EI);
5222 } else {
5223 // We allow a zero-parameter variadic function in C if the
5224 // function is marked with the "overloadable" attribute. Scan
5225 // for this attribute now. We also allow it in C23 per WG14 N2975.
5226 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5227 if (LangOpts.C23)
5228 S.Diag(Loc: FTI.getEllipsisLoc(),
5229 DiagID: diag::warn_c17_compat_ellipsis_only_parameter);
5230 else if (!D.getDeclarationAttributes().hasAttribute(
5231 K: ParsedAttr::AT_Overloadable) &&
5232 !D.getAttributes().hasAttribute(
5233 K: ParsedAttr::AT_Overloadable) &&
5234 !D.getDeclSpec().getAttributes().hasAttribute(
5235 K: ParsedAttr::AT_Overloadable))
5236 S.Diag(Loc: FTI.getEllipsisLoc(), DiagID: diag::err_ellipsis_first_param);
5237 }
5238
5239 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5240 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5241 // definition.
5242 S.Diag(Loc: FTI.Params[0].IdentLoc,
5243 DiagID: diag::err_ident_list_in_fn_declaration);
5244 D.setInvalidType(true);
5245 // Recover by creating a K&R-style function type, if possible.
5246 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5247 ? Context.getFunctionNoProtoType(ResultTy: T, Info: EI)
5248 : Context.IntTy;
5249 AreDeclaratorChunksValid = false;
5250 break;
5251 }
5252
5253 FunctionProtoType::ExtProtoInfo EPI;
5254 EPI.ExtInfo = EI;
5255 EPI.Variadic = FTI.isVariadic;
5256 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5257 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
5258 EPI.TypeQuals.addCVRUQualifiers(
5259 mask: FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
5260 : 0);
5261 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
5262 : FTI.RefQualifierIsLValueRef? RQ_LValue
5263 : RQ_RValue;
5264
5265 // Otherwise, we have a function with a parameter list that is
5266 // potentially variadic.
5267 SmallVector<QualType, 16> ParamTys;
5268 ParamTys.reserve(N: FTI.NumParams);
5269
5270 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
5271 ExtParameterInfos(FTI.NumParams);
5272 bool HasAnyInterestingExtParameterInfos = false;
5273
5274 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5275 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
5276 QualType ParamTy = Param->getType();
5277 assert(!ParamTy.isNull() && "Couldn't parse type?");
5278
5279 // Look for 'void'. void is allowed only as a single parameter to a
5280 // function with no other parameters (C99 6.7.5.3p10). We record
5281 // int(void) as a FunctionProtoType with an empty parameter list.
5282 if (ParamTy->isVoidType()) {
5283 // If this is something like 'float(int, void)', reject it. 'void'
5284 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5285 // have parameters of incomplete type.
5286 if (FTI.NumParams != 1 || FTI.isVariadic) {
5287 S.Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::err_void_only_param);
5288 ParamTy = Context.IntTy;
5289 Param->setType(ParamTy);
5290 } else if (FTI.Params[i].Ident) {
5291 // Reject, but continue to parse 'int(void abc)'.
5292 S.Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::err_param_with_void_type);
5293 ParamTy = Context.IntTy;
5294 Param->setType(ParamTy);
5295 } else {
5296 // Reject, but continue to parse 'float(const void)'.
5297 if (ParamTy.hasQualifiers())
5298 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_void_param_qualified);
5299
5300 for (const auto *A : Param->attrs()) {
5301 S.Diag(Loc: A->getLoc(), DiagID: diag::warn_attribute_on_void_param)
5302 << A << A->getRange();
5303 }
5304
5305 // Reject, but continue to parse 'float(this void)' as
5306 // 'float(void)'.
5307 if (Param->isExplicitObjectParameter()) {
5308 S.Diag(Loc: Param->getLocation(),
5309 DiagID: diag::err_void_explicit_object_param);
5310 Param->setExplicitObjectParameterLoc(SourceLocation());
5311 }
5312
5313 // Do not add 'void' to the list.
5314 break;
5315 }
5316 } else if (ParamTy->isHalfType()) {
5317 // Disallow half FP parameters.
5318 // FIXME: This really should be in BuildFunctionType.
5319 if (S.getLangOpts().OpenCL) {
5320 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
5321 LO: S.getLangOpts())) {
5322 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_invalid_param)
5323 << ParamTy << 0;
5324 D.setInvalidType();
5325 Param->setInvalidDecl();
5326 }
5327 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5328 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5329 S.Diag(Loc: Param->getLocation(),
5330 DiagID: diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5331 D.setInvalidType();
5332 }
5333 } else if (!FTI.hasPrototype) {
5334 if (Context.isPromotableIntegerType(T: ParamTy)) {
5335 ParamTy = Context.getPromotedIntegerType(PromotableType: ParamTy);
5336 Param->setKNRPromoted(true);
5337 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5338 if (BTy->getKind() == BuiltinType::Float) {
5339 ParamTy = Context.DoubleTy;
5340 Param->setKNRPromoted(true);
5341 }
5342 }
5343 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5344 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5345 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_invalid_param)
5346 << ParamTy << 1 /*hint off*/;
5347 D.setInvalidType();
5348 }
5349
5350 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5351 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(consumed: true);
5352 HasAnyInterestingExtParameterInfos = true;
5353 }
5354
5355 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5356 ExtParameterInfos[i] =
5357 ExtParameterInfos[i].withABI(kind: attr->getABI());
5358 HasAnyInterestingExtParameterInfos = true;
5359 }
5360
5361 if (Param->hasAttr<PassObjectSizeAttr>()) {
5362 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5363 HasAnyInterestingExtParameterInfos = true;
5364 }
5365
5366 if (Param->hasAttr<NoEscapeAttr>()) {
5367 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(NoEscape: true);
5368 HasAnyInterestingExtParameterInfos = true;
5369 }
5370
5371 ParamTys.push_back(Elt: ParamTy);
5372 }
5373
5374 if (HasAnyInterestingExtParameterInfos) {
5375 EPI.ExtParameterInfos = ExtParameterInfos.data();
5376 checkExtParameterInfos(S, paramTypes: ParamTys, EPI,
5377 getParamLoc: [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5378 }
5379
5380 SmallVector<QualType, 4> Exceptions;
5381 SmallVector<ParsedType, 2> DynamicExceptions;
5382 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5383 Expr *NoexceptExpr = nullptr;
5384
5385 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5386 // FIXME: It's rather inefficient to have to split into two vectors
5387 // here.
5388 unsigned N = FTI.getNumExceptions();
5389 DynamicExceptions.reserve(N);
5390 DynamicExceptionRanges.reserve(N);
5391 for (unsigned I = 0; I != N; ++I) {
5392 DynamicExceptions.push_back(Elt: FTI.Exceptions[I].Ty);
5393 DynamicExceptionRanges.push_back(Elt: FTI.Exceptions[I].Range);
5394 }
5395 } else if (isComputedNoexcept(ESpecType: FTI.getExceptionSpecType())) {
5396 NoexceptExpr = FTI.NoexceptExpr;
5397 }
5398
5399 S.checkExceptionSpecification(IsTopLevel: D.isFunctionDeclarationContext(),
5400 EST: FTI.getExceptionSpecType(),
5401 DynamicExceptions,
5402 DynamicExceptionRanges,
5403 NoexceptExpr,
5404 Exceptions,
5405 ESI&: EPI.ExceptionSpec);
5406
5407 // FIXME: Set address space from attrs for C++ mode here.
5408 // OpenCLCPlusPlus: A class member function has an address space.
5409 auto IsClassMember = [&]() {
5410 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5411 state.getDeclarator()
5412 .getCXXScopeSpec()
5413 .getScopeRep()
5414 .getKind() == NestedNameSpecifier::Kind::Type) ||
5415 state.getDeclarator().getContext() ==
5416 DeclaratorContext::Member ||
5417 state.getDeclarator().getContext() ==
5418 DeclaratorContext::LambdaExpr;
5419 };
5420
5421 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5422 LangAS ASIdx = LangAS::Default;
5423 // Take address space attr if any and mark as invalid to avoid adding
5424 // them later while creating QualType.
5425 if (FTI.MethodQualifiers)
5426 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
5427 LangAS ASIdxNew = attr.asOpenCLLangAS();
5428 if (DiagnoseMultipleAddrSpaceAttributes(S, ASOld: ASIdx, ASNew: ASIdxNew,
5429 AttrLoc: attr.getLoc()))
5430 D.setInvalidType(true);
5431 else
5432 ASIdx = ASIdxNew;
5433 }
5434 // If a class member function's address space is not set, set it to
5435 // __generic.
5436 LangAS AS =
5437 (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace()
5438 : ASIdx);
5439 EPI.TypeQuals.addAddressSpace(space: AS);
5440 }
5441 T = Context.getFunctionType(ResultTy: T, Args: ParamTys, EPI);
5442 }
5443 break;
5444 }
5445 case DeclaratorChunk::MemberPointer: {
5446 // The scope spec must refer to a class, or be dependent.
5447 CXXScopeSpec &SS = DeclType.Mem.Scope();
5448
5449 // Handle pointer nullability.
5450 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5451 DeclType.EndLoc, DeclType.getAttrs(),
5452 state.getDeclarator().getAttributePool());
5453
5454 if (SS.isInvalid()) {
5455 // Avoid emitting extra errors if we already errored on the scope.
5456 D.setInvalidType(true);
5457 AreDeclaratorChunksValid = false;
5458 } else {
5459 T = S.BuildMemberPointerType(T, SS, /*Cls=*/nullptr, Loc: DeclType.Loc,
5460 Entity: D.getIdentifier());
5461 }
5462
5463 if (T.isNull()) {
5464 T = Context.IntTy;
5465 D.setInvalidType(true);
5466 AreDeclaratorChunksValid = false;
5467 } else if (DeclType.Mem.TypeQuals) {
5468 T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: DeclType.Mem.TypeQuals);
5469 }
5470 break;
5471 }
5472
5473 case DeclaratorChunk::Pipe: {
5474 T = S.BuildReadPipeType(T, Loc: DeclType.Loc);
5475 processTypeAttrs(state, type&: T, TAL: TAL_DeclSpec,
5476 attrs: D.getMutableDeclSpec().getAttributes());
5477 break;
5478 }
5479 }
5480
5481 if (T.isNull()) {
5482 D.setInvalidType(true);
5483 T = Context.IntTy;
5484 AreDeclaratorChunksValid = false;
5485 }
5486
5487 // See if there are any attributes on this declarator chunk.
5488 processTypeAttrs(state, type&: T, TAL: TAL_DeclChunk, attrs: DeclType.getAttrs(),
5489 CFT: S.CUDA().IdentifyTarget(Attrs: D.getAttributes()));
5490
5491 if (DeclType.Kind != DeclaratorChunk::Paren) {
5492 if (ExpectNoDerefChunk && !IsNoDerefableChunk(Chunk: DeclType))
5493 S.Diag(Loc: DeclType.Loc, DiagID: diag::warn_noderef_on_non_pointer_or_array);
5494
5495 ExpectNoDerefChunk = state.didParseNoDeref();
5496 }
5497 }
5498
5499 if (ExpectNoDerefChunk)
5500 S.Diag(Loc: state.getDeclarator().getBeginLoc(),
5501 DiagID: diag::warn_noderef_on_non_pointer_or_array);
5502
5503 // GNU warning -Wstrict-prototypes
5504 // Warn if a function declaration or definition is without a prototype.
5505 // This warning is issued for all kinds of unprototyped function
5506 // declarations (i.e. function type typedef, function pointer etc.)
5507 // C99 6.7.5.3p14:
5508 // The empty list in a function declarator that is not part of a definition
5509 // of that function specifies that no information about the number or types
5510 // of the parameters is supplied.
5511 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5512 // function declarations whose behavior changes in C23.
5513 if (!LangOpts.requiresStrictPrototypes()) {
5514 bool IsBlock = false;
5515 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5516 switch (DeclType.Kind) {
5517 case DeclaratorChunk::BlockPointer:
5518 IsBlock = true;
5519 break;
5520 case DeclaratorChunk::Function: {
5521 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5522 // We suppress the warning when there's no LParen location, as this
5523 // indicates the declaration was an implicit declaration, which gets
5524 // warned about separately via -Wimplicit-function-declaration. We also
5525 // suppress the warning when we know the function has a prototype.
5526 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5527 FTI.getLParenLoc().isValid())
5528 S.Diag(Loc: DeclType.Loc, DiagID: diag::warn_strict_prototypes)
5529 << IsBlock
5530 << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc(), Code: "void");
5531 IsBlock = false;
5532 break;
5533 }
5534 default:
5535 break;
5536 }
5537 }
5538 }
5539
5540 assert(!T.isNull() && "T must not be null after this point");
5541
5542 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5543 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5544 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5545
5546 // C++ 8.3.5p4:
5547 // A cv-qualifier-seq shall only be part of the function type
5548 // for a nonstatic member function, the function type to which a pointer
5549 // to member refers, or the top-level function type of a function typedef
5550 // declaration.
5551 //
5552 // Core issue 547 also allows cv-qualifiers on function types that are
5553 // top-level template type arguments.
5554 enum {
5555 NonMember,
5556 Member,
5557 ExplicitObjectMember,
5558 DeductionGuide
5559 } Kind = NonMember;
5560 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5561 Kind = DeductionGuide;
5562 else if (!D.getCXXScopeSpec().isSet()) {
5563 if ((D.getContext() == DeclaratorContext::Member ||
5564 D.getContext() == DeclaratorContext::LambdaExpr) &&
5565 !D.getDeclSpec().isFriendSpecified())
5566 Kind = Member;
5567 } else {
5568 DeclContext *DC = S.computeDeclContext(SS: D.getCXXScopeSpec());
5569 if (!DC || DC->isRecord())
5570 Kind = Member;
5571 }
5572
5573 if (Kind == Member) {
5574 unsigned I;
5575 if (D.isFunctionDeclarator(idx&: I)) {
5576 const DeclaratorChunk &Chunk = D.getTypeObject(i: I);
5577 if (Chunk.Fun.NumParams) {
5578 auto *P = dyn_cast_or_null<ParmVarDecl>(Val: Chunk.Fun.Params->Param);
5579 if (P && P->isExplicitObjectParameter())
5580 Kind = ExplicitObjectMember;
5581 }
5582 }
5583 }
5584
5585 // C++11 [dcl.fct]p6 (w/DR1417):
5586 // An attempt to specify a function type with a cv-qualifier-seq or a
5587 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5588 // - the function type for a non-static member function,
5589 // - the function type to which a pointer to member refers,
5590 // - the top-level function type of a function typedef declaration or
5591 // alias-declaration,
5592 // - the type-id in the default argument of a type-parameter, or
5593 // - the type-id of a template-argument for a type-parameter
5594 //
5595 // C++23 [dcl.fct]p6 (P0847R7)
5596 // ... A member-declarator with an explicit-object-parameter-declaration
5597 // shall not include a ref-qualifier or a cv-qualifier-seq and shall not be
5598 // declared static or virtual ...
5599 //
5600 // FIXME: Checking this here is insufficient. We accept-invalid on:
5601 //
5602 // template<typename T> struct S { void f(T); };
5603 // S<int() const> s;
5604 //
5605 // ... for instance.
5606 if (IsQualifiedFunction &&
5607 // Check for non-static member function and not and
5608 // explicit-object-parameter-declaration
5609 (Kind != Member || D.isExplicitObjectMemberFunction() ||
5610 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
5611 (D.getContext() == clang::DeclaratorContext::Member &&
5612 D.isStaticMember())) &&
5613 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5614 D.getContext() != DeclaratorContext::TemplateTypeArg) {
5615 SourceLocation Loc = D.getBeginLoc();
5616 SourceRange RemovalRange;
5617 unsigned I;
5618 if (D.isFunctionDeclarator(idx&: I)) {
5619 SmallVector<SourceLocation, 4> RemovalLocs;
5620 const DeclaratorChunk &Chunk = D.getTypeObject(i: I);
5621 assert(Chunk.Kind == DeclaratorChunk::Function);
5622
5623 if (Chunk.Fun.hasRefQualifier())
5624 RemovalLocs.push_back(Elt: Chunk.Fun.getRefQualifierLoc());
5625
5626 if (Chunk.Fun.hasMethodTypeQualifiers())
5627 Chunk.Fun.MethodQualifiers->forEachQualifier(
5628 Handle: [&](DeclSpec::TQ TypeQual, StringRef QualName,
5629 SourceLocation SL) { RemovalLocs.push_back(Elt: SL); });
5630
5631 if (!RemovalLocs.empty()) {
5632 llvm::sort(C&: RemovalLocs,
5633 Comp: BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5634 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5635 Loc = RemovalLocs.front();
5636 }
5637 }
5638
5639 S.Diag(Loc, DiagID: diag::err_invalid_qualified_function_type)
5640 << Kind << D.isFunctionDeclarator() << T
5641 << getFunctionQualifiersAsString(FnTy)
5642 << FixItHint::CreateRemoval(RemoveRange: RemovalRange);
5643
5644 // Strip the cv-qualifiers and ref-qualifiers from the type.
5645 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5646 EPI.TypeQuals.removeCVRQualifiers();
5647 EPI.RefQualifier = RQ_None;
5648
5649 T = Context.getFunctionType(ResultTy: FnTy->getReturnType(), Args: FnTy->getParamTypes(),
5650 EPI);
5651 // Rebuild any parens around the identifier in the function type.
5652 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5653 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5654 break;
5655 T = S.BuildParenType(T);
5656 }
5657 }
5658 }
5659
5660 // Apply any undistributed attributes from the declaration or declarator.
5661 ParsedAttributesView NonSlidingAttrs;
5662 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5663 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5664 NonSlidingAttrs.addAtEnd(newAttr: &AL);
5665 }
5666 }
5667 processTypeAttrs(state, type&: T, TAL: TAL_DeclName, attrs: NonSlidingAttrs);
5668 processTypeAttrs(state, type&: T, TAL: TAL_DeclName, attrs: D.getAttributes());
5669
5670 // Diagnose any ignored type attributes.
5671 state.diagnoseIgnoredTypeAttrs(type: T);
5672
5673 // C++0x [dcl.constexpr]p9:
5674 // A constexpr specifier used in an object declaration declares the object
5675 // as const.
5676 if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr &&
5677 T->isObjectType())
5678 T.addConst();
5679
5680 // C++2a [dcl.fct]p4:
5681 // A parameter with volatile-qualified type is deprecated
5682 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5683 (D.getContext() == DeclaratorContext::Prototype ||
5684 D.getContext() == DeclaratorContext::LambdaExprParameter))
5685 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::warn_deprecated_volatile_param) << T;
5686
5687 // If there was an ellipsis in the declarator, the declaration declares a
5688 // parameter pack whose type may be a pack expansion type.
5689 if (D.hasEllipsis()) {
5690 // C++0x [dcl.fct]p13:
5691 // A declarator-id or abstract-declarator containing an ellipsis shall
5692 // only be used in a parameter-declaration. Such a parameter-declaration
5693 // is a parameter pack (14.5.3). [...]
5694 switch (D.getContext()) {
5695 case DeclaratorContext::Prototype:
5696 case DeclaratorContext::LambdaExprParameter:
5697 case DeclaratorContext::RequiresExpr:
5698 // C++0x [dcl.fct]p13:
5699 // [...] When it is part of a parameter-declaration-clause, the
5700 // parameter pack is a function parameter pack (14.5.3). The type T
5701 // of the declarator-id of the function parameter pack shall contain
5702 // a template parameter pack; each template parameter pack in T is
5703 // expanded by the function parameter pack.
5704 //
5705 // We represent function parameter packs as function parameters whose
5706 // type is a pack expansion.
5707 if (!T->containsUnexpandedParameterPack() &&
5708 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5709 S.Diag(Loc: D.getEllipsisLoc(),
5710 DiagID: diag::err_function_parameter_pack_without_parameter_packs)
5711 << T << D.getSourceRange();
5712 D.setEllipsisLoc(SourceLocation());
5713 } else {
5714 T = Context.getPackExpansionType(Pattern: T, NumExpansions: std::nullopt,
5715 /*ExpectPackInType=*/false);
5716 }
5717 break;
5718 case DeclaratorContext::TemplateParam:
5719 // C++0x [temp.param]p15:
5720 // If a template-parameter is a [...] is a parameter-declaration that
5721 // declares a parameter pack (8.3.5), then the template-parameter is a
5722 // template parameter pack (14.5.3).
5723 //
5724 // Note: core issue 778 clarifies that, if there are any unexpanded
5725 // parameter packs in the type of the non-type template parameter, then
5726 // it expands those parameter packs.
5727 if (T->containsUnexpandedParameterPack())
5728 T = Context.getPackExpansionType(Pattern: T, NumExpansions: std::nullopt);
5729 else
5730 S.Diag(Loc: D.getEllipsisLoc(),
5731 DiagID: LangOpts.CPlusPlus11
5732 ? diag::warn_cxx98_compat_variadic_templates
5733 : diag::ext_variadic_templates);
5734 break;
5735
5736 case DeclaratorContext::File:
5737 case DeclaratorContext::KNRTypeList:
5738 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5739 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
5740 case DeclaratorContext::TypeName:
5741 case DeclaratorContext::FunctionalCast:
5742 case DeclaratorContext::CXXNew:
5743 case DeclaratorContext::AliasDecl:
5744 case DeclaratorContext::AliasTemplate:
5745 case DeclaratorContext::Member:
5746 case DeclaratorContext::Block:
5747 case DeclaratorContext::ForInit:
5748 case DeclaratorContext::SelectionInit:
5749 case DeclaratorContext::Condition:
5750 case DeclaratorContext::CXXCatch:
5751 case DeclaratorContext::ObjCCatch:
5752 case DeclaratorContext::BlockLiteral:
5753 case DeclaratorContext::LambdaExpr:
5754 case DeclaratorContext::ConversionId:
5755 case DeclaratorContext::TrailingReturn:
5756 case DeclaratorContext::TrailingReturnVar:
5757 case DeclaratorContext::TemplateArg:
5758 case DeclaratorContext::TemplateTypeArg:
5759 case DeclaratorContext::Association:
5760 // FIXME: We may want to allow parameter packs in block-literal contexts
5761 // in the future.
5762 S.Diag(Loc: D.getEllipsisLoc(),
5763 DiagID: diag::err_ellipsis_in_declarator_not_parameter);
5764 D.setEllipsisLoc(SourceLocation());
5765 break;
5766 }
5767 }
5768
5769 assert(!T.isNull() && "T must not be null at the end of this function");
5770 if (!AreDeclaratorChunksValid)
5771 return Context.getTrivialTypeSourceInfo(T);
5772
5773 if (state.didParseHLSLParamMod() && !T->isConstantArrayType())
5774 T = S.HLSL().getInoutParameterType(Ty: T);
5775 return GetTypeSourceInfoForDeclarator(State&: state, T, ReturnTypeInfo: TInfo);
5776}
5777
5778TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D) {
5779 // Determine the type of the declarator. Not all forms of declarator
5780 // have a type.
5781
5782 TypeProcessingState state(*this, D);
5783
5784 TypeSourceInfo *ReturnTypeInfo = nullptr;
5785 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5786 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5787 inferARCWriteback(state, declSpecType&: T);
5788
5789 return GetFullTypeForDeclarator(state, declSpecType: T, TInfo: ReturnTypeInfo);
5790}
5791
5792static void transferARCOwnershipToDeclSpec(Sema &S,
5793 QualType &declSpecTy,
5794 Qualifiers::ObjCLifetime ownership) {
5795 if (declSpecTy->isObjCRetainableType() &&
5796 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5797 Qualifiers qs;
5798 qs.addObjCLifetime(type: ownership);
5799 declSpecTy = S.Context.getQualifiedType(T: declSpecTy, Qs: qs);
5800 }
5801}
5802
5803static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5804 Qualifiers::ObjCLifetime ownership,
5805 unsigned chunkIndex) {
5806 Sema &S = state.getSema();
5807 Declarator &D = state.getDeclarator();
5808
5809 // Look for an explicit lifetime attribute.
5810 DeclaratorChunk &chunk = D.getTypeObject(i: chunkIndex);
5811 if (chunk.getAttrs().hasAttribute(K: ParsedAttr::AT_ObjCOwnership))
5812 return;
5813
5814 const char *attrStr = nullptr;
5815 switch (ownership) {
5816 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5817 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5818 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5819 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5820 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5821 }
5822
5823 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5824 Arg->setIdentifierInfo(&S.Context.Idents.get(Name: attrStr));
5825
5826 ArgsUnion Args(Arg);
5827
5828 // If there wasn't one, add one (with an invalid source location
5829 // so that we don't make an AttributedType for it).
5830 ParsedAttr *attr =
5831 D.getAttributePool().create(attrName: &S.Context.Idents.get(Name: "objc_ownership"),
5832 attrRange: SourceLocation(), scope: AttributeScopeInfo(),
5833 /*args*/ &Args, numArgs: 1, form: ParsedAttr::Form::GNU());
5834 chunk.getAttrs().addAtEnd(newAttr: attr);
5835 // TODO: mark whether we did this inference?
5836}
5837
5838/// Used for transferring ownership in casts resulting in l-values.
5839static void transferARCOwnership(TypeProcessingState &state,
5840 QualType &declSpecTy,
5841 Qualifiers::ObjCLifetime ownership) {
5842 Sema &S = state.getSema();
5843 Declarator &D = state.getDeclarator();
5844
5845 int inner = -1;
5846 bool hasIndirection = false;
5847 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5848 DeclaratorChunk &chunk = D.getTypeObject(i);
5849 switch (chunk.Kind) {
5850 case DeclaratorChunk::Paren:
5851 // Ignore parens.
5852 break;
5853
5854 case DeclaratorChunk::Array:
5855 case DeclaratorChunk::Reference:
5856 case DeclaratorChunk::Pointer:
5857 if (inner != -1)
5858 hasIndirection = true;
5859 inner = i;
5860 break;
5861
5862 case DeclaratorChunk::BlockPointer:
5863 if (inner != -1)
5864 transferARCOwnershipToDeclaratorChunk(state, ownership, chunkIndex: i);
5865 return;
5866
5867 case DeclaratorChunk::Function:
5868 case DeclaratorChunk::MemberPointer:
5869 case DeclaratorChunk::Pipe:
5870 return;
5871 }
5872 }
5873
5874 if (inner == -1)
5875 return;
5876
5877 DeclaratorChunk &chunk = D.getTypeObject(i: inner);
5878 if (chunk.Kind == DeclaratorChunk::Pointer) {
5879 if (declSpecTy->isObjCRetainableType())
5880 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5881 if (declSpecTy->isObjCObjectType() && hasIndirection)
5882 return transferARCOwnershipToDeclaratorChunk(state, ownership, chunkIndex: inner);
5883 } else {
5884 assert(chunk.Kind == DeclaratorChunk::Array ||
5885 chunk.Kind == DeclaratorChunk::Reference);
5886 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5887 }
5888}
5889
5890TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
5891 TypeProcessingState state(*this, D);
5892
5893 TypeSourceInfo *ReturnTypeInfo = nullptr;
5894 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5895
5896 if (getLangOpts().ObjC) {
5897 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(T: FromTy);
5898 if (ownership != Qualifiers::OCL_None)
5899 transferARCOwnership(state, declSpecTy, ownership);
5900 }
5901
5902 return GetFullTypeForDeclarator(state, declSpecType: declSpecTy, TInfo: ReturnTypeInfo);
5903}
5904
5905static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5906 TypeProcessingState &State) {
5907 TL.setAttr(State.takeAttrForAttributedType(AT: TL.getTypePtr()));
5908}
5909
5910static void fillHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL,
5911 TypeProcessingState &State) {
5912 HLSLAttributedResourceLocInfo LocInfo =
5913 State.getSema().HLSL().TakeLocForHLSLAttribute(RT: TL.getTypePtr());
5914 TL.setSourceRange(LocInfo.Range);
5915 TL.setContainedTypeSourceInfo(LocInfo.ContainedTyInfo);
5916}
5917
5918static void fillMatrixTypeLoc(MatrixTypeLoc MTL,
5919 const ParsedAttributesView &Attrs) {
5920 for (const ParsedAttr &AL : Attrs) {
5921 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
5922 MTL.setAttrNameLoc(AL.getLoc());
5923 MTL.setAttrRowOperand(AL.getArgAsExpr(Arg: 0));
5924 MTL.setAttrColumnOperand(AL.getArgAsExpr(Arg: 1));
5925 MTL.setAttrOperandParensRange(SourceRange());
5926 return;
5927 }
5928 }
5929
5930 llvm_unreachable("no matrix_type attribute found at the expected location!");
5931}
5932
5933static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5934 SourceLocation Loc;
5935 switch (Chunk.Kind) {
5936 case DeclaratorChunk::Function:
5937 case DeclaratorChunk::Array:
5938 case DeclaratorChunk::Paren:
5939 case DeclaratorChunk::Pipe:
5940 llvm_unreachable("cannot be _Atomic qualified");
5941
5942 case DeclaratorChunk::Pointer:
5943 Loc = Chunk.Ptr.AtomicQualLoc;
5944 break;
5945
5946 case DeclaratorChunk::BlockPointer:
5947 case DeclaratorChunk::Reference:
5948 case DeclaratorChunk::MemberPointer:
5949 // FIXME: Provide a source location for the _Atomic keyword.
5950 break;
5951 }
5952
5953 ATL.setKWLoc(Loc);
5954 ATL.setParensRange(SourceRange());
5955}
5956
5957namespace {
5958 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5959 Sema &SemaRef;
5960 ASTContext &Context;
5961 TypeProcessingState &State;
5962 const DeclSpec &DS;
5963
5964 public:
5965 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
5966 const DeclSpec &DS)
5967 : SemaRef(S), Context(Context), State(State), DS(DS) {}
5968
5969 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5970 Visit(TyLoc: TL.getModifiedLoc());
5971 fillAttributedTypeLoc(TL, State);
5972 }
5973 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
5974 Visit(TyLoc: TL.getWrappedLoc());
5975 }
5976 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
5977 Visit(TyLoc: TL.getWrappedLoc());
5978 }
5979 void VisitHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL) {
5980 Visit(TyLoc: TL.getWrappedLoc());
5981 fillHLSLAttributedResourceTypeLoc(TL, State);
5982 }
5983 void VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {}
5984 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5985 Visit(TyLoc: TL.getInnerLoc());
5986 TL.setExpansionLoc(
5987 State.getExpansionLocForMacroQualifiedType(MQT: TL.getTypePtr()));
5988 }
5989 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5990 Visit(TyLoc: TL.getUnqualifiedLoc());
5991 }
5992 // Allow to fill pointee's type locations, e.g.,
5993 // int __attr * __attr * __attr *p;
5994 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TyLoc: TL.getNextTypeLoc()); }
5995 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5996 if (DS.getTypeSpecType() == TST_typename) {
5997 TypeSourceInfo *TInfo = nullptr;
5998 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
5999 if (TInfo) {
6000 TL.copy(other: TInfo->getTypeLoc().castAs<TypedefTypeLoc>());
6001 return;
6002 }
6003 }
6004 TL.set(ElaboratedKeywordLoc: TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6005 ? DS.getTypeSpecTypeLoc()
6006 : SourceLocation(),
6007 QualifierLoc: DS.getTypeSpecScope().getWithLocInContext(Context),
6008 NameLoc: DS.getTypeSpecTypeNameLoc());
6009 }
6010 void VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6011 if (DS.getTypeSpecType() == TST_typename) {
6012 TypeSourceInfo *TInfo = nullptr;
6013 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6014 if (TInfo) {
6015 TL.copy(other: TInfo->getTypeLoc().castAs<UnresolvedUsingTypeLoc>());
6016 return;
6017 }
6018 }
6019 TL.set(ElaboratedKeywordLoc: TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6020 ? DS.getTypeSpecTypeLoc()
6021 : SourceLocation(),
6022 QualifierLoc: DS.getTypeSpecScope().getWithLocInContext(Context),
6023 NameLoc: DS.getTypeSpecTypeNameLoc());
6024 }
6025 void VisitUsingTypeLoc(UsingTypeLoc TL) {
6026 if (DS.getTypeSpecType() == TST_typename) {
6027 TypeSourceInfo *TInfo = nullptr;
6028 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6029 if (TInfo) {
6030 TL.copy(other: TInfo->getTypeLoc().castAs<UsingTypeLoc>());
6031 return;
6032 }
6033 }
6034 TL.set(ElaboratedKeywordLoc: TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6035 ? DS.getTypeSpecTypeLoc()
6036 : SourceLocation(),
6037 QualifierLoc: DS.getTypeSpecScope().getWithLocInContext(Context),
6038 NameLoc: DS.getTypeSpecTypeNameLoc());
6039 }
6040 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6041 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6042 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6043 // addition field. What we have is good enough for display of location
6044 // of 'fixit' on interface name.
6045 TL.setNameEndLoc(DS.getEndLoc());
6046 }
6047 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6048 TypeSourceInfo *RepTInfo = nullptr;
6049 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &RepTInfo);
6050 TL.copy(other: RepTInfo->getTypeLoc());
6051 }
6052 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6053 TypeSourceInfo *RepTInfo = nullptr;
6054 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &RepTInfo);
6055 TL.copy(other: RepTInfo->getTypeLoc());
6056 }
6057 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6058 TypeSourceInfo *TInfo = nullptr;
6059 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6060
6061 // If we got no declarator info from previous Sema routines,
6062 // just fill with the typespec loc.
6063 if (!TInfo) {
6064 TL.initialize(Context, Loc: DS.getTypeSpecTypeNameLoc());
6065 return;
6066 }
6067
6068 TypeLoc OldTL = TInfo->getTypeLoc();
6069 TL.copy(Loc: OldTL.castAs<TemplateSpecializationTypeLoc>());
6070 assert(TL.getRAngleLoc() ==
6071 OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6072 }
6073 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6074 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
6075 DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr);
6076 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6077 TL.setParensRange(DS.getTypeofParensRange());
6078 }
6079 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6080 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
6081 DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType);
6082 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6083 TL.setParensRange(DS.getTypeofParensRange());
6084 assert(DS.getRepAsType());
6085 TypeSourceInfo *TInfo = nullptr;
6086 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6087 TL.setUnmodifiedTInfo(TInfo);
6088 }
6089 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6090 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
6091 TL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
6092 TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6093 }
6094 void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6095 assert(DS.getTypeSpecType() == DeclSpec::TST_typename_pack_indexing);
6096 TL.setEllipsisLoc(DS.getEllipsisLoc());
6097 }
6098 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6099 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6100 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6101 TL.setParensRange(DS.getTypeofParensRange());
6102 assert(DS.getRepAsType());
6103 TypeSourceInfo *TInfo = nullptr;
6104 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6105 TL.setUnderlyingTInfo(TInfo);
6106 }
6107 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6108 // By default, use the source location of the type specifier.
6109 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
6110 if (TL.needsExtraLocalData()) {
6111 // Set info for the written builtin specifiers.
6112 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
6113 // Try to have a meaningful source location.
6114 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6115 TL.expandBuiltinRange(Range: DS.getTypeSpecSignLoc());
6116 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6117 TL.expandBuiltinRange(Range: DS.getTypeSpecWidthRange());
6118 }
6119 }
6120 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6121 assert(DS.getTypeSpecType() == TST_typename);
6122 TypeSourceInfo *TInfo = nullptr;
6123 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6124 assert(TInfo);
6125 TL.copy(Loc: TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6126 }
6127 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6128 assert(DS.getTypeSpecType() == TST_auto ||
6129 DS.getTypeSpecType() == TST_decltype_auto ||
6130 DS.getTypeSpecType() == TST_auto_type ||
6131 DS.getTypeSpecType() == TST_unspecified);
6132 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6133 if (DS.getTypeSpecType() == TST_decltype_auto)
6134 TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6135 if (!DS.isConstrainedAuto())
6136 return;
6137 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6138 if (!TemplateId)
6139 return;
6140
6141 NestedNameSpecifierLoc NNS =
6142 (DS.getTypeSpecScope().isNotEmpty()
6143 ? DS.getTypeSpecScope().getWithLocInContext(Context)
6144 : NestedNameSpecifierLoc());
6145 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6146 TemplateId->RAngleLoc);
6147 if (TemplateId->NumArgs > 0) {
6148 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6149 TemplateId->NumArgs);
6150 SemaRef.translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgsInfo);
6151 }
6152 DeclarationNameInfo DNI = DeclarationNameInfo(
6153 TL.getTypePtr()->getTypeConstraintConcept()->getDeclName(),
6154 TemplateId->TemplateNameLoc);
6155
6156 NamedDecl *FoundDecl;
6157 if (auto TN = TemplateId->Template.get();
6158 UsingShadowDecl *USD = TN.getAsUsingShadowDecl())
6159 FoundDecl = cast<NamedDecl>(Val: USD);
6160 else
6161 FoundDecl = cast_if_present<NamedDecl>(Val: TN.getAsTemplateDecl());
6162
6163 auto *CR = ConceptReference::Create(
6164 C: Context, NNS, TemplateKWLoc: TemplateId->TemplateKWLoc, ConceptNameInfo: DNI, FoundDecl,
6165 /*NamedDecl=*/NamedConcept: TL.getTypePtr()->getTypeConstraintConcept(),
6166 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgsInfo));
6167 TL.setConceptReference(CR);
6168 }
6169 void VisitDeducedTemplateSpecializationTypeLoc(
6170 DeducedTemplateSpecializationTypeLoc TL) {
6171 assert(DS.getTypeSpecType() == TST_typename);
6172 TypeSourceInfo *TInfo = nullptr;
6173 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6174 assert(TInfo);
6175 TL.copy(
6176 other: TInfo->getTypeLoc().castAs<DeducedTemplateSpecializationTypeLoc>());
6177 }
6178 void VisitTagTypeLoc(TagTypeLoc TL) {
6179 if (DS.getTypeSpecType() == TST_typename) {
6180 TypeSourceInfo *TInfo = nullptr;
6181 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6182 if (TInfo) {
6183 TL.copy(other: TInfo->getTypeLoc().castAs<TagTypeLoc>());
6184 return;
6185 }
6186 }
6187 TL.setElaboratedKeywordLoc(TL.getTypePtr()->getKeyword() !=
6188 ElaboratedTypeKeyword::None
6189 ? DS.getTypeSpecTypeLoc()
6190 : SourceLocation());
6191 TL.setQualifierLoc(DS.getTypeSpecScope().getWithLocInContext(Context));
6192 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
6193 }
6194 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6195 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6196 // or an _Atomic qualifier.
6197 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
6198 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6199 TL.setParensRange(DS.getTypeofParensRange());
6200
6201 TypeSourceInfo *TInfo = nullptr;
6202 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6203 assert(TInfo);
6204 TL.getValueLoc().initializeFullCopy(Other: TInfo->getTypeLoc());
6205 } else {
6206 TL.setKWLoc(DS.getAtomicSpecLoc());
6207 // No parens, to indicate this was spelled as an _Atomic qualifier.
6208 TL.setParensRange(SourceRange());
6209 Visit(TyLoc: TL.getValueLoc());
6210 }
6211 }
6212
6213 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6214 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6215
6216 TypeSourceInfo *TInfo = nullptr;
6217 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6218 TL.getValueLoc().initializeFullCopy(Other: TInfo->getTypeLoc());
6219 }
6220
6221 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6222 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6223 }
6224
6225 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6226 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6227 }
6228
6229 void VisitTypeLoc(TypeLoc TL) {
6230 // FIXME: add other typespec types and change this to an assert.
6231 TL.initialize(Context, Loc: DS.getTypeSpecTypeLoc());
6232 }
6233 };
6234
6235 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6236 ASTContext &Context;
6237 TypeProcessingState &State;
6238 const DeclaratorChunk &Chunk;
6239
6240 public:
6241 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6242 const DeclaratorChunk &Chunk)
6243 : Context(Context), State(State), Chunk(Chunk) {}
6244
6245 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6246 llvm_unreachable("qualified type locs not expected here!");
6247 }
6248 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6249 llvm_unreachable("decayed type locs not expected here!");
6250 }
6251 void VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6252 llvm_unreachable("array parameter type locs not expected here!");
6253 }
6254
6255 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6256 fillAttributedTypeLoc(TL, State);
6257 }
6258 void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
6259 // nothing
6260 }
6261 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6262 // nothing
6263 }
6264 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
6265 // nothing
6266 }
6267 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6268 // nothing
6269 }
6270 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6271 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6272 TL.setCaretLoc(Chunk.Loc);
6273 }
6274 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6275 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6276 TL.setStarLoc(Chunk.Loc);
6277 }
6278 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6279 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6280 TL.setStarLoc(Chunk.Loc);
6281 }
6282 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6283 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6284 TL.setStarLoc(Chunk.Mem.StarLoc);
6285 TL.setQualifierLoc(Chunk.Mem.Scope().getWithLocInContext(Context));
6286 }
6287 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6288 assert(Chunk.Kind == DeclaratorChunk::Reference);
6289 // 'Amp' is misleading: this might have been originally
6290 /// spelled with AmpAmp.
6291 TL.setAmpLoc(Chunk.Loc);
6292 }
6293 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6294 assert(Chunk.Kind == DeclaratorChunk::Reference);
6295 assert(!Chunk.Ref.LValueRef);
6296 TL.setAmpAmpLoc(Chunk.Loc);
6297 }
6298 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6299 assert(Chunk.Kind == DeclaratorChunk::Array);
6300 TL.setLBracketLoc(Chunk.Loc);
6301 TL.setRBracketLoc(Chunk.EndLoc);
6302 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6303 }
6304 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6305 assert(Chunk.Kind == DeclaratorChunk::Function);
6306 TL.setLocalRangeBegin(Chunk.Loc);
6307 TL.setLocalRangeEnd(Chunk.EndLoc);
6308
6309 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6310 TL.setLParenLoc(FTI.getLParenLoc());
6311 TL.setRParenLoc(FTI.getRParenLoc());
6312 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6313 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
6314 TL.setParam(i: tpi++, VD: Param);
6315 }
6316 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
6317 }
6318 void VisitParenTypeLoc(ParenTypeLoc TL) {
6319 assert(Chunk.Kind == DeclaratorChunk::Paren);
6320 TL.setLParenLoc(Chunk.Loc);
6321 TL.setRParenLoc(Chunk.EndLoc);
6322 }
6323 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6324 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6325 TL.setKWLoc(Chunk.Loc);
6326 }
6327 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6328 TL.setNameLoc(Chunk.Loc);
6329 }
6330 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6331 TL.setExpansionLoc(Chunk.Loc);
6332 }
6333 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6334 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6335 TL.setNameLoc(Chunk.Loc);
6336 }
6337 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6338 TL.setNameLoc(Chunk.Loc);
6339 }
6340 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6341 fillAtomicQualLoc(ATL: TL, Chunk);
6342 }
6343 void
6344 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6345 TL.setNameLoc(Chunk.Loc);
6346 }
6347 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6348 fillMatrixTypeLoc(MTL: TL, Attrs: Chunk.getAttrs());
6349 }
6350
6351 void VisitTypeLoc(TypeLoc TL) {
6352 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6353 }
6354 };
6355} // end anonymous namespace
6356
6357static void
6358fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
6359 const ParsedAttributesView &Attrs) {
6360 for (const ParsedAttr &AL : Attrs) {
6361 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6362 DASTL.setAttrNameLoc(AL.getLoc());
6363 DASTL.setAttrExprOperand(AL.getArgAsExpr(Arg: 0));
6364 DASTL.setAttrOperandParensRange(SourceRange());
6365 return;
6366 }
6367 }
6368
6369 llvm_unreachable(
6370 "no address_space attribute found at the expected location!");
6371}
6372
6373/// Create and instantiate a TypeSourceInfo with type source information.
6374///
6375/// \param T QualType referring to the type as written in source code.
6376///
6377/// \param ReturnTypeInfo For declarators whose return type does not show
6378/// up in the normal place in the declaration specifiers (such as a C++
6379/// conversion function), this pointer will refer to a type source information
6380/// for that return type.
6381static TypeSourceInfo *
6382GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6383 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6384 Sema &S = State.getSema();
6385 Declarator &D = State.getDeclarator();
6386
6387 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
6388 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6389
6390 // Handle parameter packs whose type is a pack expansion.
6391 if (isa<PackExpansionType>(Val: T)) {
6392 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6393 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6394 }
6395
6396 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6397 // Microsoft property fields can have multiple sizeless array chunks
6398 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6399 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6400 D.getDeclSpec().getAttributes().hasMSPropertyAttr())
6401 continue;
6402
6403 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6404 // declarator chunk.
6405 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6406 fillAtomicQualLoc(ATL, Chunk: D.getTypeObject(i));
6407 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6408 }
6409
6410 bool HasDesugaredTypeLoc = true;
6411 while (HasDesugaredTypeLoc) {
6412 switch (CurrTL.getTypeLocClass()) {
6413 case TypeLoc::MacroQualified: {
6414 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6415 TL.setExpansionLoc(
6416 State.getExpansionLocForMacroQualifiedType(MQT: TL.getTypePtr()));
6417 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6418 break;
6419 }
6420
6421 case TypeLoc::Attributed: {
6422 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6423 fillAttributedTypeLoc(TL, State);
6424 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6425 break;
6426 }
6427
6428 case TypeLoc::Adjusted:
6429 case TypeLoc::BTFTagAttributed: {
6430 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6431 break;
6432 }
6433
6434 case TypeLoc::DependentAddressSpace: {
6435 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6436 fillDependentAddressSpaceTypeLoc(DASTL: TL, Attrs: D.getTypeObject(i).getAttrs());
6437 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6438 break;
6439 }
6440
6441 default:
6442 HasDesugaredTypeLoc = false;
6443 break;
6444 }
6445 }
6446
6447 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(TyLoc: CurrTL);
6448 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6449 }
6450
6451 // If we have different source information for the return type, use
6452 // that. This really only applies to C++ conversion functions.
6453 if (ReturnTypeInfo) {
6454 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6455 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6456 memcpy(dest: CurrTL.getOpaqueData(), src: TL.getOpaqueData(), n: TL.getFullDataSize());
6457 } else {
6458 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(TyLoc: CurrTL);
6459 }
6460
6461 return TInfo;
6462}
6463
6464/// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6465ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
6466 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6467 // and Sema during declaration parsing. Try deallocating/caching them when
6468 // it's appropriate, instead of allocating them and keeping them around.
6469 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(Size: sizeof(LocInfoType),
6470 Alignment: alignof(LocInfoType));
6471 new (LocT) LocInfoType(T, TInfo);
6472 assert(LocT->getTypeClass() != T->getTypeClass() &&
6473 "LocInfoType's TypeClass conflicts with an existing Type class");
6474 return ParsedType::make(P: QualType(LocT, 0));
6475}
6476
6477void LocInfoType::getAsStringInternal(std::string &Str,
6478 const PrintingPolicy &Policy) const {
6479 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6480 " was used directly instead of getting the QualType through"
6481 " GetTypeFromParser");
6482}
6483
6484TypeResult Sema::ActOnTypeName(Declarator &D) {
6485 // C99 6.7.6: Type names have no identifier. This is already validated by
6486 // the parser.
6487 assert(D.getIdentifier() == nullptr &&
6488 "Type name should have no identifier!");
6489
6490 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6491 QualType T = TInfo->getType();
6492 if (D.isInvalidType())
6493 return true;
6494
6495 // Make sure there are no unused decl attributes on the declarator.
6496 // We don't want to do this for ObjC parameters because we're going
6497 // to apply them to the actual parameter declaration.
6498 // Likewise, we don't want to do this for alias declarations, because
6499 // we are actually going to build a declaration from this eventually.
6500 if (D.getContext() != DeclaratorContext::ObjCParameter &&
6501 D.getContext() != DeclaratorContext::AliasDecl &&
6502 D.getContext() != DeclaratorContext::AliasTemplate)
6503 checkUnusedDeclAttributes(D);
6504
6505 if (getLangOpts().CPlusPlus) {
6506 // Check that there are no default arguments (C++ only).
6507 CheckExtraCXXDefaultArguments(D);
6508 }
6509
6510 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
6511 const AutoType *AT = TL.getTypePtr();
6512 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
6513 }
6514 return CreateParsedType(T, TInfo);
6515}
6516
6517//===----------------------------------------------------------------------===//
6518// Type Attribute Processing
6519//===----------------------------------------------------------------------===//
6520
6521/// Build an AddressSpace index from a constant expression and diagnose any
6522/// errors related to invalid address_spaces. Returns true on successfully
6523/// building an AddressSpace index.
6524static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6525 const Expr *AddrSpace,
6526 SourceLocation AttrLoc) {
6527 if (!AddrSpace->isValueDependent()) {
6528 std::optional<llvm::APSInt> OptAddrSpace =
6529 AddrSpace->getIntegerConstantExpr(Ctx: S.Context);
6530 if (!OptAddrSpace) {
6531 S.Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type)
6532 << "'address_space'" << AANT_ArgumentIntegerConstant
6533 << AddrSpace->getSourceRange();
6534 return false;
6535 }
6536 llvm::APSInt &addrSpace = *OptAddrSpace;
6537
6538 // Bounds checking.
6539 if (addrSpace.isSigned()) {
6540 if (addrSpace.isNegative()) {
6541 S.Diag(Loc: AttrLoc, DiagID: diag::err_attribute_address_space_negative)
6542 << AddrSpace->getSourceRange();
6543 return false;
6544 }
6545 addrSpace.setIsSigned(false);
6546 }
6547
6548 llvm::APSInt max(addrSpace.getBitWidth());
6549 max =
6550 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
6551
6552 if (addrSpace > max) {
6553 S.Diag(Loc: AttrLoc, DiagID: diag::err_attribute_address_space_too_high)
6554 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6555 return false;
6556 }
6557
6558 ASIdx =
6559 getLangASFromTargetAS(TargetAS: static_cast<unsigned>(addrSpace.getZExtValue()));
6560 return true;
6561 }
6562
6563 // Default value for DependentAddressSpaceTypes
6564 ASIdx = LangAS::Default;
6565 return true;
6566}
6567
6568QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
6569 SourceLocation AttrLoc) {
6570 if (!AddrSpace->isValueDependent()) {
6571 if (DiagnoseMultipleAddrSpaceAttributes(S&: *this, ASOld: T.getAddressSpace(), ASNew: ASIdx,
6572 AttrLoc))
6573 return QualType();
6574
6575 return Context.getAddrSpaceQualType(T, AddressSpace: ASIdx);
6576 }
6577
6578 // A check with similar intentions as checking if a type already has an
6579 // address space except for on a dependent types, basically if the
6580 // current type is already a DependentAddressSpaceType then its already
6581 // lined up to have another address space on it and we can't have
6582 // multiple address spaces on the one pointer indirection
6583 if (T->getAs<DependentAddressSpaceType>()) {
6584 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_address_multiple_qualifiers);
6585 return QualType();
6586 }
6587
6588 return Context.getDependentAddressSpaceType(PointeeType: T, AddrSpaceExpr: AddrSpace, AttrLoc);
6589}
6590
6591QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
6592 SourceLocation AttrLoc) {
6593 LangAS ASIdx;
6594 if (!BuildAddressSpaceIndex(S&: *this, ASIdx, AddrSpace, AttrLoc))
6595 return QualType();
6596 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6597}
6598
6599static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr,
6600 TypeProcessingState &State) {
6601 Sema &S = State.getSema();
6602
6603 // This attribute is only supported in C.
6604 // FIXME: we should implement checkCommonAttributeFeatures() in SemaAttr.cpp
6605 // such that it handles type attributes, and then call that from
6606 // processTypeAttrs() instead of one-off checks like this.
6607 if (!Attr.diagnoseLangOpts(S)) {
6608 Attr.setInvalid();
6609 return;
6610 }
6611
6612 // Check the number of attribute arguments.
6613 if (Attr.getNumArgs() != 1) {
6614 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments)
6615 << Attr << 1;
6616 Attr.setInvalid();
6617 return;
6618 }
6619
6620 // Ensure the argument is a string.
6621 auto *StrLiteral = dyn_cast<StringLiteral>(Val: Attr.getArgAsExpr(Arg: 0));
6622 if (!StrLiteral) {
6623 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_argument_type)
6624 << Attr << AANT_ArgumentString;
6625 Attr.setInvalid();
6626 return;
6627 }
6628
6629 ASTContext &Ctx = S.Context;
6630 StringRef BTFTypeTag = StrLiteral->getString();
6631 Type = State.getBTFTagAttributedType(
6632 BTFAttr: ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), WrappedType: Type);
6633}
6634
6635/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6636/// specified type. The attribute contains 1 argument, the id of the address
6637/// space for the type.
6638static void HandleAddressSpaceTypeAttribute(QualType &Type,
6639 const ParsedAttr &Attr,
6640 TypeProcessingState &State) {
6641 Sema &S = State.getSema();
6642
6643 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6644 // qualified by an address-space qualifier."
6645 if (Type->isFunctionType()) {
6646 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_address_function_type);
6647 Attr.setInvalid();
6648 return;
6649 }
6650
6651 LangAS ASIdx;
6652 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6653
6654 // Check the attribute arguments.
6655 if (Attr.getNumArgs() != 1) {
6656 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << Attr
6657 << 1;
6658 Attr.setInvalid();
6659 return;
6660 }
6661
6662 Expr *ASArgExpr = Attr.getArgAsExpr(Arg: 0);
6663 LangAS ASIdx;
6664 if (!BuildAddressSpaceIndex(S, ASIdx, AddrSpace: ASArgExpr, AttrLoc: Attr.getLoc())) {
6665 Attr.setInvalid();
6666 return;
6667 }
6668
6669 ASTContext &Ctx = S.Context;
6670 auto *ASAttr =
6671 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6672
6673 // If the expression is not value dependent (not templated), then we can
6674 // apply the address space qualifiers just to the equivalent type.
6675 // Otherwise, we make an AttributedType with the modified and equivalent
6676 // type the same, and wrap it in a DependentAddressSpaceType. When this
6677 // dependent type is resolved, the qualifier is added to the equivalent type
6678 // later.
6679 QualType T;
6680 if (!ASArgExpr->isValueDependent()) {
6681 QualType EquivType =
6682 S.BuildAddressSpaceAttr(T&: Type, ASIdx, AddrSpace: ASArgExpr, AttrLoc: Attr.getLoc());
6683 if (EquivType.isNull()) {
6684 Attr.setInvalid();
6685 return;
6686 }
6687 T = State.getAttributedType(A: ASAttr, ModifiedType: Type, EquivType);
6688 } else {
6689 T = State.getAttributedType(A: ASAttr, ModifiedType: Type, EquivType: Type);
6690 T = S.BuildAddressSpaceAttr(T, ASIdx, AddrSpace: ASArgExpr, AttrLoc: Attr.getLoc());
6691 }
6692
6693 if (!T.isNull())
6694 Type = T;
6695 else
6696 Attr.setInvalid();
6697 } else {
6698 // The keyword-based type attributes imply which address space to use.
6699 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6700 : Attr.asOpenCLLangAS();
6701 if (S.getLangOpts().HLSL)
6702 ASIdx = Attr.asHLSLLangAS();
6703
6704 if (ASIdx == LangAS::Default)
6705 llvm_unreachable("Invalid address space");
6706
6707 if (DiagnoseMultipleAddrSpaceAttributes(S, ASOld: Type.getAddressSpace(), ASNew: ASIdx,
6708 AttrLoc: Attr.getLoc())) {
6709 Attr.setInvalid();
6710 return;
6711 }
6712
6713 Type = S.Context.getAddrSpaceQualType(T: Type, AddressSpace: ASIdx);
6714 }
6715}
6716
6717static void HandleOverflowBehaviorAttr(QualType &Type, const ParsedAttr &Attr,
6718 TypeProcessingState &State) {
6719 Sema &S = State.getSema();
6720
6721 // Check for -fexperimental-overflow-behavior-types
6722 if (!S.getLangOpts().OverflowBehaviorTypes) {
6723 S.Diag(Loc: Attr.getLoc(), DiagID: diag::warn_overflow_behavior_attribute_disabled)
6724 << Attr << 1;
6725 Attr.setInvalid();
6726 return;
6727 }
6728
6729 // Check the number of attribute arguments.
6730 if (Attr.getNumArgs() != 1) {
6731 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments)
6732 << Attr << 1;
6733 Attr.setInvalid();
6734 return;
6735 }
6736
6737 // Check that the underlying type is an integer type
6738 if (!Type->isIntegerType()) {
6739 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_overflow_behavior_non_integer_type)
6740 << Attr << Type.getAsString() << 0; // 0 for attribute
6741 Attr.setInvalid();
6742 return;
6743 }
6744
6745 StringRef KindName = "";
6746 IdentifierInfo *Ident = nullptr;
6747
6748 if (Attr.isArgIdent(Arg: 0)) {
6749 Ident = Attr.getArgAsIdent(Arg: 0)->getIdentifierInfo();
6750 KindName = Ident->getName();
6751 }
6752
6753 // Support identifier or string argument types. Failure to provide one of
6754 // these two types results in a diagnostic that hints towards using string
6755 // arguments (either "wrap" or "trap") as this is the most common use
6756 // pattern.
6757 if (!Ident) {
6758 auto *Str = dyn_cast<StringLiteral>(Val: Attr.getArgAsExpr(Arg: 0));
6759 if (Str)
6760 KindName = Str->getString();
6761 else {
6762 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_argument_type)
6763 << Attr << AANT_ArgumentString;
6764 Attr.setInvalid();
6765 return;
6766 }
6767 }
6768
6769 OverflowBehaviorType::OverflowBehaviorKind Kind;
6770 if (KindName == "wrap") {
6771 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
6772 } else if (KindName == "trap") {
6773 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
6774 } else {
6775 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_overflow_behavior_unknown_ident)
6776 << KindName << Attr;
6777 Attr.setInvalid();
6778 return;
6779 }
6780
6781 // Check for mixed specifier/attribute usage
6782 const DeclSpec &DS = State.getDeclarator().getDeclSpec();
6783 if (DS.isWrapSpecified() || DS.isTrapSpecified()) {
6784 // We have both specifier and attribute on the same type. If
6785 // OverflowBehaviorKinds are the same we can just warn.
6786 OverflowBehaviorType::OverflowBehaviorKind SpecifierKind =
6787 DS.isWrapSpecified() ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
6788 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
6789
6790 if (SpecifierKind != Kind) {
6791 StringRef SpecifierName = DS.isWrapSpecified() ? "wrap" : "trap";
6792 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_conflicting_overflow_behaviors)
6793 << 1 << SpecifierName << KindName;
6794 Attr.setInvalid();
6795 return;
6796 }
6797 S.Diag(Loc: Attr.getLoc(), DiagID: diag::warn_redundant_overflow_behaviors_mixed)
6798 << KindName;
6799 Attr.setInvalid();
6800 return;
6801 }
6802
6803 // Check for conflicting overflow behavior attributes
6804 if (const auto *ExistingOBT = Type->getAs<OverflowBehaviorType>()) {
6805 OverflowBehaviorType::OverflowBehaviorKind ExistingKind =
6806 ExistingOBT->getBehaviorKind();
6807 if (ExistingKind != Kind) {
6808 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_conflicting_overflow_behaviors) << 0;
6809 if (Kind == OverflowBehaviorType::OverflowBehaviorKind::Trap) {
6810 Type = State.getOverflowBehaviorType(Kind,
6811 UnderlyingType: ExistingOBT->getUnderlyingType());
6812 }
6813 return;
6814 }
6815 } else {
6816 Type = State.getOverflowBehaviorType(Kind, UnderlyingType: Type);
6817 }
6818}
6819
6820/// handleObjCOwnershipTypeAttr - Process an objc_ownership
6821/// attribute on the specified type.
6822///
6823/// Returns 'true' if the attribute was handled.
6824static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6825 ParsedAttr &attr, QualType &type) {
6826 bool NonObjCPointer = false;
6827
6828 if (!type->isDependentType() && !type->isUndeducedType()) {
6829 if (const PointerType *ptr = type->getAs<PointerType>()) {
6830 QualType pointee = ptr->getPointeeType();
6831 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6832 return false;
6833 // It is important not to lose the source info that there was an attribute
6834 // applied to non-objc pointer. We will create an attributed type but
6835 // its type will be the same as the original type.
6836 NonObjCPointer = true;
6837 } else if (!type->isObjCRetainableType()) {
6838 return false;
6839 }
6840
6841 // Don't accept an ownership attribute in the declspec if it would
6842 // just be the return type of a block pointer.
6843 if (state.isProcessingDeclSpec()) {
6844 Declarator &D = state.getDeclarator();
6845 if (maybeMovePastReturnType(declarator&: D, i: D.getNumTypeObjects(),
6846 /*onlyBlockPointers=*/true))
6847 return false;
6848 }
6849 }
6850
6851 Sema &S = state.getSema();
6852 SourceLocation AttrLoc = attr.getLoc();
6853 if (AttrLoc.isMacroID())
6854 AttrLoc =
6855 S.getSourceManager().getImmediateExpansionRange(Loc: AttrLoc).getBegin();
6856
6857 if (!attr.isArgIdent(Arg: 0)) {
6858 S.Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type) << attr
6859 << AANT_ArgumentString;
6860 attr.setInvalid();
6861 return true;
6862 }
6863
6864 IdentifierInfo *II = attr.getArgAsIdent(Arg: 0)->getIdentifierInfo();
6865 Qualifiers::ObjCLifetime lifetime;
6866 if (II->isStr(Str: "none"))
6867 lifetime = Qualifiers::OCL_ExplicitNone;
6868 else if (II->isStr(Str: "strong"))
6869 lifetime = Qualifiers::OCL_Strong;
6870 else if (II->isStr(Str: "weak"))
6871 lifetime = Qualifiers::OCL_Weak;
6872 else if (II->isStr(Str: "autoreleasing"))
6873 lifetime = Qualifiers::OCL_Autoreleasing;
6874 else {
6875 S.Diag(Loc: AttrLoc, DiagID: diag::warn_attribute_type_not_supported) << attr << II;
6876 attr.setInvalid();
6877 return true;
6878 }
6879
6880 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6881 // outside of ARC mode.
6882 if (!S.getLangOpts().ObjCAutoRefCount &&
6883 lifetime != Qualifiers::OCL_Weak &&
6884 lifetime != Qualifiers::OCL_ExplicitNone) {
6885 return true;
6886 }
6887
6888 SplitQualType underlyingType = type.split();
6889
6890 // Check for redundant/conflicting ownership qualifiers.
6891 if (Qualifiers::ObjCLifetime previousLifetime
6892 = type.getQualifiers().getObjCLifetime()) {
6893 // If it's written directly, that's an error.
6894 if (S.Context.hasDirectOwnershipQualifier(Ty: type)) {
6895 S.Diag(Loc: AttrLoc, DiagID: diag::err_attr_objc_ownership_redundant)
6896 << type;
6897 return true;
6898 }
6899
6900 // Otherwise, if the qualifiers actually conflict, pull sugar off
6901 // and remove the ObjCLifetime qualifiers.
6902 if (previousLifetime != lifetime) {
6903 // It's possible to have multiple local ObjCLifetime qualifiers. We
6904 // can't stop after we reach a type that is directly qualified.
6905 const Type *prevTy = nullptr;
6906 while (!prevTy || prevTy != underlyingType.Ty) {
6907 prevTy = underlyingType.Ty;
6908 underlyingType = underlyingType.getSingleStepDesugaredType();
6909 }
6910 underlyingType.Quals.removeObjCLifetime();
6911 }
6912 }
6913
6914 underlyingType.Quals.addObjCLifetime(type: lifetime);
6915
6916 if (NonObjCPointer) {
6917 StringRef name = attr.getAttrName()->getName();
6918 switch (lifetime) {
6919 case Qualifiers::OCL_None:
6920 case Qualifiers::OCL_ExplicitNone:
6921 break;
6922 case Qualifiers::OCL_Strong: name = "__strong"; break;
6923 case Qualifiers::OCL_Weak: name = "__weak"; break;
6924 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6925 }
6926 S.Diag(Loc: AttrLoc, DiagID: diag::warn_type_attribute_wrong_type) << name
6927 << TDS_ObjCObjOrBlock << type;
6928 }
6929
6930 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6931 // because having both 'T' and '__unsafe_unretained T' exist in the type
6932 // system causes unfortunate widespread consistency problems. (For example,
6933 // they're not considered compatible types, and we mangle them identicially
6934 // as template arguments.) These problems are all individually fixable,
6935 // but it's easier to just not add the qualifier and instead sniff it out
6936 // in specific places using isObjCInertUnsafeUnretainedType().
6937 //
6938 // Doing this does means we miss some trivial consistency checks that
6939 // would've triggered in ARC, but that's better than trying to solve all
6940 // the coexistence problems with __unsafe_unretained.
6941 if (!S.getLangOpts().ObjCAutoRefCount &&
6942 lifetime == Qualifiers::OCL_ExplicitNone) {
6943 type = state.getAttributedType(
6944 A: createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(Ctx&: S.Context, AL&: attr),
6945 ModifiedType: type, EquivType: type);
6946 return true;
6947 }
6948
6949 QualType origType = type;
6950 if (!NonObjCPointer)
6951 type = S.Context.getQualifiedType(split: underlyingType);
6952
6953 // If we have a valid source location for the attribute, use an
6954 // AttributedType instead.
6955 if (AttrLoc.isValid()) {
6956 type = state.getAttributedType(A: ::new (S.Context)
6957 ObjCOwnershipAttr(S.Context, attr, II),
6958 ModifiedType: origType, EquivType: type);
6959 }
6960
6961 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6962 unsigned diagnostic, QualType type) {
6963 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
6964 S.DelayedDiagnostics.add(
6965 diag: sema::DelayedDiagnostic::makeForbiddenType(
6966 loc: S.getSourceManager().getExpansionLoc(Loc: loc),
6967 diagnostic, type, /*ignored*/ argument: 0));
6968 } else {
6969 S.Diag(Loc: loc, DiagID: diagnostic);
6970 }
6971 };
6972
6973 // Sometimes, __weak isn't allowed.
6974 if (lifetime == Qualifiers::OCL_Weak &&
6975 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6976
6977 // Use a specialized diagnostic if the runtime just doesn't support them.
6978 unsigned diagnostic =
6979 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6980 : diag::err_arc_weak_no_runtime);
6981
6982 // In any case, delay the diagnostic until we know what we're parsing.
6983 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6984
6985 attr.setInvalid();
6986 return true;
6987 }
6988
6989 // Forbid __weak for class objects marked as
6990 // objc_arc_weak_reference_unavailable
6991 if (lifetime == Qualifiers::OCL_Weak) {
6992 if (const ObjCObjectPointerType *ObjT =
6993 type->getAs<ObjCObjectPointerType>()) {
6994 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6995 if (Class->isArcWeakrefUnavailable()) {
6996 S.Diag(Loc: AttrLoc, DiagID: diag::err_arc_unsupported_weak_class);
6997 S.Diag(Loc: ObjT->getInterfaceDecl()->getLocation(),
6998 DiagID: diag::note_class_declared);
6999 }
7000 }
7001 }
7002 }
7003
7004 return true;
7005}
7006
7007/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
7008/// attribute on the specified type. Returns true to indicate that
7009/// the attribute was handled, false to indicate that the type does
7010/// not permit the attribute.
7011static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7012 QualType &type) {
7013 Sema &S = state.getSema();
7014
7015 // Delay if this isn't some kind of pointer.
7016 if (!type->isPointerType() &&
7017 !type->isObjCObjectPointerType() &&
7018 !type->isBlockPointerType())
7019 return false;
7020
7021 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7022 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attribute_multiple_objc_gc);
7023 attr.setInvalid();
7024 return true;
7025 }
7026
7027 // Check the attribute arguments.
7028 if (!attr.isArgIdent(Arg: 0)) {
7029 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attribute_argument_type)
7030 << attr << AANT_ArgumentString;
7031 attr.setInvalid();
7032 return true;
7033 }
7034 Qualifiers::GC GCAttr;
7035 if (attr.getNumArgs() > 1) {
7036 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << attr
7037 << 1;
7038 attr.setInvalid();
7039 return true;
7040 }
7041
7042 IdentifierInfo *II = attr.getArgAsIdent(Arg: 0)->getIdentifierInfo();
7043 if (II->isStr(Str: "weak"))
7044 GCAttr = Qualifiers::Weak;
7045 else if (II->isStr(Str: "strong"))
7046 GCAttr = Qualifiers::Strong;
7047 else {
7048 S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_attribute_type_not_supported)
7049 << attr << II;
7050 attr.setInvalid();
7051 return true;
7052 }
7053
7054 QualType origType = type;
7055 type = S.Context.getObjCGCQualType(T: origType, gcAttr: GCAttr);
7056
7057 // Make an attributed type to preserve the source information.
7058 if (attr.getLoc().isValid())
7059 type = state.getAttributedType(
7060 A: ::new (S.Context) ObjCGCAttr(S.Context, attr, II), ModifiedType: origType, EquivType: type);
7061
7062 return true;
7063}
7064
7065namespace {
7066 /// A helper class to unwrap a type down to a function for the
7067 /// purposes of applying attributes there.
7068 ///
7069 /// Use:
7070 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
7071 /// if (unwrapped.isFunctionType()) {
7072 /// const FunctionType *fn = unwrapped.get();
7073 /// // change fn somehow
7074 /// T = unwrapped.wrap(fn);
7075 /// }
7076 struct FunctionTypeUnwrapper {
7077 enum WrapKind {
7078 Desugar,
7079 Attributed,
7080 Parens,
7081 Array,
7082 Pointer,
7083 BlockPointer,
7084 Reference,
7085 MemberPointer,
7086 MacroQualified,
7087 };
7088
7089 QualType Original;
7090 const FunctionType *Fn;
7091 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7092
7093 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7094 while (true) {
7095 const Type *Ty = T.getTypePtr();
7096 if (isa<FunctionType>(Val: Ty)) {
7097 Fn = cast<FunctionType>(Val: Ty);
7098 return;
7099 } else if (isa<ParenType>(Val: Ty)) {
7100 T = cast<ParenType>(Val: Ty)->getInnerType();
7101 Stack.push_back(Elt: Parens);
7102 } else if (isa<ConstantArrayType>(Val: Ty) || isa<VariableArrayType>(Val: Ty) ||
7103 isa<IncompleteArrayType>(Val: Ty)) {
7104 T = cast<ArrayType>(Val: Ty)->getElementType();
7105 Stack.push_back(Elt: Array);
7106 } else if (isa<PointerType>(Val: Ty)) {
7107 T = cast<PointerType>(Val: Ty)->getPointeeType();
7108 Stack.push_back(Elt: Pointer);
7109 } else if (isa<BlockPointerType>(Val: Ty)) {
7110 T = cast<BlockPointerType>(Val: Ty)->getPointeeType();
7111 Stack.push_back(Elt: BlockPointer);
7112 } else if (isa<MemberPointerType>(Val: Ty)) {
7113 T = cast<MemberPointerType>(Val: Ty)->getPointeeType();
7114 Stack.push_back(Elt: MemberPointer);
7115 } else if (isa<ReferenceType>(Val: Ty)) {
7116 T = cast<ReferenceType>(Val: Ty)->getPointeeType();
7117 Stack.push_back(Elt: Reference);
7118 } else if (isa<AttributedType>(Val: Ty)) {
7119 T = cast<AttributedType>(Val: Ty)->getEquivalentType();
7120 Stack.push_back(Elt: Attributed);
7121 } else if (isa<MacroQualifiedType>(Val: Ty)) {
7122 T = cast<MacroQualifiedType>(Val: Ty)->getUnderlyingType();
7123 Stack.push_back(Elt: MacroQualified);
7124 } else {
7125 const Type *DTy = Ty->getUnqualifiedDesugaredType();
7126 if (Ty == DTy) {
7127 Fn = nullptr;
7128 return;
7129 }
7130
7131 T = QualType(DTy, 0);
7132 Stack.push_back(Elt: Desugar);
7133 }
7134 }
7135 }
7136
7137 bool isFunctionType() const { return (Fn != nullptr); }
7138 const FunctionType *get() const { return Fn; }
7139
7140 QualType wrap(Sema &S, const FunctionType *New) {
7141 // If T wasn't modified from the unwrapped type, do nothing.
7142 if (New == get()) return Original;
7143
7144 Fn = New;
7145 return wrap(C&: S.Context, Old: Original, I: 0);
7146 }
7147
7148 private:
7149 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7150 if (I == Stack.size())
7151 return C.getQualifiedType(T: Fn, Qs: Old.getQualifiers());
7152
7153 // Build up the inner type, applying the qualifiers from the old
7154 // type to the new type.
7155 SplitQualType SplitOld = Old.split();
7156
7157 // As a special case, tail-recurse if there are no qualifiers.
7158 if (SplitOld.Quals.empty())
7159 return wrap(C, Old: SplitOld.Ty, I);
7160 return C.getQualifiedType(T: wrap(C, Old: SplitOld.Ty, I), Qs: SplitOld.Quals);
7161 }
7162
7163 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7164 if (I == Stack.size()) return QualType(Fn, 0);
7165
7166 switch (static_cast<WrapKind>(Stack[I++])) {
7167 case Desugar:
7168 // This is the point at which we potentially lose source
7169 // information.
7170 return wrap(C, Old: Old->getUnqualifiedDesugaredType(), I);
7171
7172 case Attributed:
7173 return wrap(C, Old: cast<AttributedType>(Val: Old)->getEquivalentType(), I);
7174
7175 case Parens: {
7176 QualType New = wrap(C, Old: cast<ParenType>(Val: Old)->getInnerType(), I);
7177 return C.getParenType(NamedType: New);
7178 }
7179
7180 case MacroQualified:
7181 return wrap(C, Old: cast<MacroQualifiedType>(Val: Old)->getUnderlyingType(), I);
7182
7183 case Array: {
7184 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: Old)) {
7185 QualType New = wrap(C, Old: CAT->getElementType(), I);
7186 return C.getConstantArrayType(EltTy: New, ArySize: CAT->getSize(), SizeExpr: CAT->getSizeExpr(),
7187 ASM: CAT->getSizeModifier(),
7188 IndexTypeQuals: CAT->getIndexTypeCVRQualifiers());
7189 }
7190
7191 if (const auto *VAT = dyn_cast<VariableArrayType>(Val: Old)) {
7192 QualType New = wrap(C, Old: VAT->getElementType(), I);
7193 return C.getVariableArrayType(EltTy: New, NumElts: VAT->getSizeExpr(),
7194 ASM: VAT->getSizeModifier(),
7195 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers());
7196 }
7197
7198 const auto *IAT = cast<IncompleteArrayType>(Val: Old);
7199 QualType New = wrap(C, Old: IAT->getElementType(), I);
7200 return C.getIncompleteArrayType(EltTy: New, ASM: IAT->getSizeModifier(),
7201 IndexTypeQuals: IAT->getIndexTypeCVRQualifiers());
7202 }
7203
7204 case Pointer: {
7205 QualType New = wrap(C, Old: cast<PointerType>(Val: Old)->getPointeeType(), I);
7206 return C.getPointerType(T: New);
7207 }
7208
7209 case BlockPointer: {
7210 QualType New = wrap(C, Old: cast<BlockPointerType>(Val: Old)->getPointeeType(),I);
7211 return C.getBlockPointerType(T: New);
7212 }
7213
7214 case MemberPointer: {
7215 const MemberPointerType *OldMPT = cast<MemberPointerType>(Val: Old);
7216 QualType New = wrap(C, Old: OldMPT->getPointeeType(), I);
7217 return C.getMemberPointerType(T: New, Qualifier: OldMPT->getQualifier(),
7218 Cls: OldMPT->getMostRecentCXXRecordDecl());
7219 }
7220
7221 case Reference: {
7222 const ReferenceType *OldRef = cast<ReferenceType>(Val: Old);
7223 QualType New = wrap(C, Old: OldRef->getPointeeType(), I);
7224 if (isa<LValueReferenceType>(Val: OldRef))
7225 return C.getLValueReferenceType(T: New, SpelledAsLValue: OldRef->isSpelledAsLValue());
7226 else
7227 return C.getRValueReferenceType(T: New);
7228 }
7229 }
7230
7231 llvm_unreachable("unknown wrapping kind");
7232 }
7233 };
7234} // end anonymous namespace
7235
7236static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7237 ParsedAttr &PAttr, QualType &Type) {
7238 Sema &S = State.getSema();
7239
7240 Attr *A;
7241 switch (PAttr.getKind()) {
7242 default: llvm_unreachable("Unknown attribute kind");
7243 case ParsedAttr::AT_Ptr32:
7244 A = createSimpleAttr<Ptr32Attr>(Ctx&: S.Context, AL&: PAttr);
7245 break;
7246 case ParsedAttr::AT_Ptr64:
7247 A = createSimpleAttr<Ptr64Attr>(Ctx&: S.Context, AL&: PAttr);
7248 break;
7249 case ParsedAttr::AT_SPtr:
7250 A = createSimpleAttr<SPtrAttr>(Ctx&: S.Context, AL&: PAttr);
7251 break;
7252 case ParsedAttr::AT_UPtr:
7253 A = createSimpleAttr<UPtrAttr>(Ctx&: S.Context, AL&: PAttr);
7254 break;
7255 }
7256
7257 std::bitset<attr::LastAttr> Attrs;
7258 QualType Desugared = Type;
7259 for (;;) {
7260 if (const TypedefType *TT = dyn_cast<TypedefType>(Val&: Desugared)) {
7261 Desugared = TT->desugar();
7262 continue;
7263 }
7264 const AttributedType *AT = dyn_cast<AttributedType>(Val&: Desugared);
7265 if (!AT)
7266 break;
7267 Attrs[AT->getAttrKind()] = true;
7268 Desugared = AT->getModifiedType();
7269 }
7270
7271 // You cannot specify duplicate type attributes, so if the attribute has
7272 // already been applied, flag it.
7273 attr::Kind NewAttrKind = A->getKind();
7274 if (Attrs[NewAttrKind]) {
7275 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::warn_duplicate_attribute_exact) << PAttr;
7276 return true;
7277 }
7278 Attrs[NewAttrKind] = true;
7279
7280 // You cannot have both __sptr and __uptr on the same type, nor can you
7281 // have __ptr32 and __ptr64.
7282 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7283 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
7284 << "'__ptr32'"
7285 << "'__ptr64'" << /*isRegularKeyword=*/0;
7286 return true;
7287 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7288 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
7289 << "'__sptr'"
7290 << "'__uptr'" << /*isRegularKeyword=*/0;
7291 return true;
7292 }
7293
7294 // Check the raw (i.e., desugared) Canonical type to see if it
7295 // is a pointer type.
7296 if (!isa<PointerType>(Val: Desugared)) {
7297 // Pointer type qualifiers can only operate on pointer types, but not
7298 // pointer-to-member types.
7299 if (Type->isMemberPointerType())
7300 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::err_attribute_no_member_pointers) << PAttr;
7301 else
7302 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::err_attribute_pointers_only) << PAttr << 0;
7303 return true;
7304 }
7305
7306 // Add address space to type based on its attributes.
7307 LangAS ASIdx = LangAS::Default;
7308 uint64_t PtrWidth =
7309 S.Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
7310 if (PtrWidth == 32) {
7311 if (Attrs[attr::Ptr64])
7312 ASIdx = LangAS::ptr64;
7313 else if (Attrs[attr::UPtr])
7314 ASIdx = LangAS::ptr32_uptr;
7315 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7316 if (S.Context.getTargetInfo().getTriple().isOSzOS() || Attrs[attr::UPtr])
7317 ASIdx = LangAS::ptr32_uptr;
7318 else
7319 ASIdx = LangAS::ptr32_sptr;
7320 }
7321
7322 QualType Pointee = Type->getPointeeType();
7323 if (ASIdx != LangAS::Default)
7324 Pointee = S.Context.getAddrSpaceQualType(
7325 T: S.Context.removeAddrSpaceQualType(T: Pointee), AddressSpace: ASIdx);
7326 Type = State.getAttributedType(A, ModifiedType: Type, EquivType: S.Context.getPointerType(T: Pointee));
7327 return false;
7328}
7329
7330static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7331 QualType &QT, ParsedAttr &PAttr) {
7332 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7333
7334 Sema &S = State.getSema();
7335 Attr *A = createSimpleAttr<WebAssemblyFuncrefAttr>(Ctx&: S.Context, AL&: PAttr);
7336
7337 std::bitset<attr::LastAttr> Attrs;
7338 attr::Kind NewAttrKind = A->getKind();
7339 const auto *AT = dyn_cast<AttributedType>(Val&: QT);
7340 while (AT) {
7341 Attrs[AT->getAttrKind()] = true;
7342 AT = dyn_cast<AttributedType>(Val: AT->getModifiedType());
7343 }
7344
7345 // You cannot specify duplicate type attributes, so if the attribute has
7346 // already been applied, flag it.
7347 if (Attrs[NewAttrKind]) {
7348 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::warn_duplicate_attribute_exact) << PAttr;
7349 return true;
7350 }
7351
7352 // Check that the type is a function pointer type.
7353 QualType Desugared = QT.getDesugaredType(Context: S.Context);
7354 const auto *Ptr = dyn_cast<PointerType>(Val&: Desugared);
7355 if (!Ptr || !Ptr->getPointeeType()->isFunctionType()) {
7356 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::err_attribute_webassembly_funcref);
7357 return true;
7358 }
7359
7360 // Add address space to type based on its attributes.
7361 LangAS ASIdx = LangAS::wasm_funcref;
7362 QualType Pointee = QT->getPointeeType();
7363 Pointee = S.Context.getAddrSpaceQualType(
7364 T: S.Context.removeAddrSpaceQualType(T: Pointee), AddressSpace: ASIdx);
7365 QT = State.getAttributedType(A, ModifiedType: QT, EquivType: S.Context.getPointerType(T: Pointee));
7366 return false;
7367}
7368
7369static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL,
7370 QualType &QT, ParsedAttr &PAttr) {
7371 if (TAL == TAL_DeclName)
7372 return;
7373
7374 Sema &S = State.getSema();
7375 auto &D = State.getDeclarator();
7376
7377 // If the attribute appears in declaration specifiers
7378 // it should be handled as a declaration attribute,
7379 // unless it's associated with a type or a function
7380 // prototype (i.e. appears on a parameter or result type).
7381 if (State.isProcessingDeclSpec()) {
7382 if (!(D.isPrototypeContext() ||
7383 D.getContext() == DeclaratorContext::TypeName))
7384 return;
7385
7386 if (auto *chunk = D.getInnermostNonParenChunk()) {
7387 moveAttrFromListToList(attr&: PAttr, fromList&: State.getCurrentAttributes(),
7388 toList&: const_cast<DeclaratorChunk *>(chunk)->getAttrs());
7389 return;
7390 }
7391 }
7392
7393 StringRef Str;
7394 if (!S.checkStringLiteralArgumentAttr(Attr: PAttr, ArgNum: 0, Str)) {
7395 PAttr.setInvalid();
7396 return;
7397 }
7398
7399 // If the attribute as attached to a paren move it closer to
7400 // the declarator. This can happen in block declarations when
7401 // an attribute is placed before `^` i.e. `(__attribute__((...)) ^)`.
7402 //
7403 // Note that it's actually invalid to use GNU style attributes
7404 // in a block but such cases are currently handled gracefully
7405 // but the parser and behavior should be consistent between
7406 // cases when attribute appears before/after block's result
7407 // type and inside (^).
7408 if (TAL == TAL_DeclChunk) {
7409 auto chunkIdx = State.getCurrentChunkIndex();
7410 if (chunkIdx >= 1 &&
7411 D.getTypeObject(i: chunkIdx).Kind == DeclaratorChunk::Paren) {
7412 moveAttrFromListToList(attr&: PAttr, fromList&: State.getCurrentAttributes(),
7413 toList&: D.getTypeObject(i: chunkIdx - 1).getAttrs());
7414 return;
7415 }
7416 }
7417
7418 auto *A = ::new (S.Context) SwiftAttrAttr(S.Context, PAttr, Str);
7419 QT = State.getAttributedType(A, ModifiedType: QT, EquivType: QT);
7420 PAttr.setUsedAsTypeAttr();
7421}
7422
7423/// Rebuild an attributed type without the nullability attribute on it.
7424static QualType rebuildAttributedTypeWithoutNullability(ASTContext &Ctx,
7425 QualType Type) {
7426 auto Attributed = dyn_cast<AttributedType>(Val: Type.getTypePtr());
7427 if (!Attributed)
7428 return Type;
7429
7430 // Skip the nullability attribute; we're done.
7431 if (Attributed->getImmediateNullability())
7432 return Attributed->getModifiedType();
7433
7434 // Build the modified type.
7435 QualType Modified = rebuildAttributedTypeWithoutNullability(
7436 Ctx, Type: Attributed->getModifiedType());
7437 assert(Modified.getTypePtr() != Attributed->getModifiedType().getTypePtr());
7438 return Ctx.getAttributedType(attrKind: Attributed->getAttrKind(), modifiedType: Modified,
7439 equivalentType: Attributed->getEquivalentType(),
7440 attr: Attributed->getAttr());
7441}
7442
7443/// Map a nullability attribute kind to a nullability kind.
7444static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
7445 switch (kind) {
7446 case ParsedAttr::AT_TypeNonNull:
7447 return NullabilityKind::NonNull;
7448
7449 case ParsedAttr::AT_TypeNullable:
7450 return NullabilityKind::Nullable;
7451
7452 case ParsedAttr::AT_TypeNullableResult:
7453 return NullabilityKind::NullableResult;
7454
7455 case ParsedAttr::AT_TypeNullUnspecified:
7456 return NullabilityKind::Unspecified;
7457
7458 default:
7459 llvm_unreachable("not a nullability attribute kind");
7460 }
7461}
7462
7463static bool CheckNullabilityTypeSpecifier(
7464 Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT,
7465 NullabilityKind Nullability, SourceLocation NullabilityLoc,
7466 bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting) {
7467 bool Implicit = (State == nullptr);
7468 if (!Implicit)
7469 recordNullabilitySeen(S, loc: NullabilityLoc);
7470
7471 // Check for existing nullability attributes on the type.
7472 QualType Desugared = QT;
7473 while (auto *Attributed = dyn_cast<AttributedType>(Val: Desugared.getTypePtr())) {
7474 // Check whether there is already a null
7475 if (auto ExistingNullability = Attributed->getImmediateNullability()) {
7476 // Duplicated nullability.
7477 if (Nullability == *ExistingNullability) {
7478 if (Implicit)
7479 break;
7480
7481 S.Diag(Loc: NullabilityLoc, DiagID: diag::warn_nullability_duplicate)
7482 << DiagNullabilityKind(Nullability, IsContextSensitive)
7483 << FixItHint::CreateRemoval(RemoveRange: NullabilityLoc);
7484
7485 break;
7486 }
7487
7488 if (!OverrideExisting) {
7489 // Conflicting nullability.
7490 S.Diag(Loc: NullabilityLoc, DiagID: diag::err_nullability_conflicting)
7491 << DiagNullabilityKind(Nullability, IsContextSensitive)
7492 << DiagNullabilityKind(*ExistingNullability, false);
7493 return true;
7494 }
7495
7496 // Rebuild the attributed type, dropping the existing nullability.
7497 QT = rebuildAttributedTypeWithoutNullability(Ctx&: S.Context, Type: QT);
7498 }
7499
7500 Desugared = Attributed->getModifiedType();
7501 }
7502
7503 // If there is already a different nullability specifier, complain.
7504 // This (unlike the code above) looks through typedefs that might
7505 // have nullability specifiers on them, which means we cannot
7506 // provide a useful Fix-It.
7507 if (auto ExistingNullability = Desugared->getNullability()) {
7508 if (Nullability != *ExistingNullability && !Implicit) {
7509 S.Diag(Loc: NullabilityLoc, DiagID: diag::err_nullability_conflicting)
7510 << DiagNullabilityKind(Nullability, IsContextSensitive)
7511 << DiagNullabilityKind(*ExistingNullability, false);
7512
7513 // Try to find the typedef with the existing nullability specifier.
7514 if (auto TT = Desugared->getAs<TypedefType>()) {
7515 TypedefNameDecl *typedefDecl = TT->getDecl();
7516 QualType underlyingType = typedefDecl->getUnderlyingType();
7517 if (auto typedefNullability =
7518 AttributedType::stripOuterNullability(T&: underlyingType)) {
7519 if (*typedefNullability == *ExistingNullability) {
7520 S.Diag(Loc: typedefDecl->getLocation(), DiagID: diag::note_nullability_here)
7521 << DiagNullabilityKind(*ExistingNullability, false);
7522 }
7523 }
7524 }
7525
7526 return true;
7527 }
7528 }
7529
7530 // If this definitely isn't a pointer type, reject the specifier.
7531 if (!Desugared->canHaveNullability() &&
7532 !(AllowOnArrayType && Desugared->isArrayType())) {
7533 if (!Implicit)
7534 S.Diag(Loc: NullabilityLoc, DiagID: diag::err_nullability_nonpointer)
7535 << DiagNullabilityKind(Nullability, IsContextSensitive) << QT;
7536
7537 return true;
7538 }
7539
7540 // For the context-sensitive keywords/Objective-C property
7541 // attributes, require that the type be a single-level pointer.
7542 if (IsContextSensitive) {
7543 // Make sure that the pointee isn't itself a pointer type.
7544 const Type *pointeeType = nullptr;
7545 if (Desugared->isArrayType())
7546 pointeeType = Desugared->getArrayElementTypeNoTypeQual();
7547 else if (Desugared->isAnyPointerType())
7548 pointeeType = Desugared->getPointeeType().getTypePtr();
7549
7550 if (pointeeType && (pointeeType->isAnyPointerType() ||
7551 pointeeType->isObjCObjectPointerType() ||
7552 pointeeType->isMemberPointerType())) {
7553 S.Diag(Loc: NullabilityLoc, DiagID: diag::err_nullability_cs_multilevel)
7554 << DiagNullabilityKind(Nullability, true) << QT;
7555 S.Diag(Loc: NullabilityLoc, DiagID: diag::note_nullability_type_specifier)
7556 << DiagNullabilityKind(Nullability, false) << QT
7557 << FixItHint::CreateReplacement(RemoveRange: NullabilityLoc,
7558 Code: getNullabilitySpelling(kind: Nullability));
7559 return true;
7560 }
7561 }
7562
7563 // Form the attributed type.
7564 if (State) {
7565 assert(PAttr);
7566 Attr *A = createNullabilityAttr(Ctx&: S.Context, Attr&: *PAttr, NK: Nullability);
7567 QT = State->getAttributedType(A, ModifiedType: QT, EquivType: QT);
7568 } else {
7569 QT = S.Context.getAttributedType(nullability: Nullability, modifiedType: QT, equivalentType: QT);
7570 }
7571 return false;
7572}
7573
7574static bool CheckNullabilityTypeSpecifier(TypeProcessingState &State,
7575 QualType &Type, ParsedAttr &Attr,
7576 bool AllowOnArrayType) {
7577 NullabilityKind Nullability = mapNullabilityAttrKind(kind: Attr.getKind());
7578 SourceLocation NullabilityLoc = Attr.getLoc();
7579 bool IsContextSensitive = Attr.isContextSensitiveKeywordAttribute();
7580
7581 return CheckNullabilityTypeSpecifier(S&: State.getSema(), State: &State, PAttr: &Attr, QT&: Type,
7582 Nullability, NullabilityLoc,
7583 IsContextSensitive, AllowOnArrayType,
7584 /*overrideExisting*/ OverrideExisting: false);
7585}
7586
7587bool Sema::CheckImplicitNullabilityTypeSpecifier(QualType &Type,
7588 NullabilityKind Nullability,
7589 SourceLocation DiagLoc,
7590 bool AllowArrayTypes,
7591 bool OverrideExisting) {
7592 return CheckNullabilityTypeSpecifier(
7593 S&: *this, State: nullptr, PAttr: nullptr, QT&: Type, Nullability, NullabilityLoc: DiagLoc,
7594 /*isContextSensitive*/ IsContextSensitive: false, AllowOnArrayType: AllowArrayTypes, OverrideExisting);
7595}
7596
7597bool Sema::CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS) {
7598 QualType T = VD->getType();
7599
7600 // Check that the variable's type can fit in the specified address space. This
7601 // is determined by how far a pointer in that address space can reach.
7602 llvm::APInt MaxSizeForAddrSpace =
7603 llvm::APInt::getMaxValue(numBits: Context.getTargetInfo().getPointerWidth(AddrSpace: AS));
7604 std::optional<CharUnits> TSizeInChars = Context.getTypeSizeInCharsIfKnown(Ty: T);
7605 if (TSizeInChars && static_cast<uint64_t>(TSizeInChars->getQuantity()) >
7606 MaxSizeForAddrSpace.getZExtValue()) {
7607 Diag(Loc: VD->getLocation(), DiagID: diag::err_type_too_large_for_address_space)
7608 << T << MaxSizeForAddrSpace;
7609 return false;
7610 }
7611
7612 return true;
7613}
7614
7615/// Check the application of the Objective-C '__kindof' qualifier to
7616/// the given type.
7617static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7618 ParsedAttr &attr) {
7619 Sema &S = state.getSema();
7620
7621 if (isa<ObjCTypeParamType>(Val: type)) {
7622 // Build the attributed type to record where __kindof occurred.
7623 type = state.getAttributedType(
7624 A: createSimpleAttr<ObjCKindOfAttr>(Ctx&: S.Context, AL&: attr), ModifiedType: type, EquivType: type);
7625 return false;
7626 }
7627
7628 // Find out if it's an Objective-C object or object pointer type;
7629 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7630 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7631 : type->getAs<ObjCObjectType>();
7632
7633 // If not, we can't apply __kindof.
7634 if (!objType) {
7635 // FIXME: Handle dependent types that aren't yet object types.
7636 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_objc_kindof_nonobject)
7637 << type;
7638 return true;
7639 }
7640
7641 // Rebuild the "equivalent" type, which pushes __kindof down into
7642 // the object type.
7643 // There is no need to apply kindof on an unqualified id type.
7644 QualType equivType = S.Context.getObjCObjectType(
7645 Base: objType->getBaseType(), typeArgs: objType->getTypeArgsAsWritten(),
7646 protocols: objType->getProtocols(),
7647 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7648
7649 // If we started with an object pointer type, rebuild it.
7650 if (ptrType) {
7651 equivType = S.Context.getObjCObjectPointerType(OIT: equivType);
7652 if (auto nullability = type->getNullability()) {
7653 // We create a nullability attribute from the __kindof attribute.
7654 // Make sure that will make sense.
7655 assert(attr.getAttributeSpellingListIndex() == 0 &&
7656 "multiple spellings for __kindof?");
7657 Attr *A = createNullabilityAttr(Ctx&: S.Context, Attr&: attr, NK: *nullability);
7658 A->setImplicit(true);
7659 equivType = state.getAttributedType(A, ModifiedType: equivType, EquivType: equivType);
7660 }
7661 }
7662
7663 // Build the attributed type to record where __kindof occurred.
7664 type = state.getAttributedType(
7665 A: createSimpleAttr<ObjCKindOfAttr>(Ctx&: S.Context, AL&: attr), ModifiedType: type, EquivType: equivType);
7666 return false;
7667}
7668
7669/// Distribute a nullability type attribute that cannot be applied to
7670/// the type specifier to a pointer, block pointer, or member pointer
7671/// declarator, complaining if necessary.
7672///
7673/// \returns true if the nullability annotation was distributed, false
7674/// otherwise.
7675static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7676 QualType type, ParsedAttr &attr) {
7677 Declarator &declarator = state.getDeclarator();
7678
7679 /// Attempt to move the attribute to the specified chunk.
7680 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7681 // If there is already a nullability attribute there, don't add
7682 // one.
7683 if (hasNullabilityAttr(attrs: chunk.getAttrs()))
7684 return false;
7685
7686 // Complain about the nullability qualifier being in the wrong
7687 // place.
7688 enum {
7689 PK_Pointer,
7690 PK_BlockPointer,
7691 PK_MemberPointer,
7692 PK_FunctionPointer,
7693 PK_MemberFunctionPointer,
7694 } pointerKind
7695 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7696 : PK_Pointer)
7697 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7698 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7699
7700 auto diag = state.getSema().Diag(Loc: attr.getLoc(),
7701 DiagID: diag::warn_nullability_declspec)
7702 << DiagNullabilityKind(mapNullabilityAttrKind(kind: attr.getKind()),
7703 attr.isContextSensitiveKeywordAttribute())
7704 << type
7705 << static_cast<unsigned>(pointerKind);
7706
7707 // FIXME: MemberPointer chunks don't carry the location of the *.
7708 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7709 diag << FixItHint::CreateRemoval(RemoveRange: attr.getLoc())
7710 << FixItHint::CreateInsertion(
7711 InsertionLoc: state.getSema().getPreprocessor().getLocForEndOfToken(
7712 Loc: chunk.Loc),
7713 Code: " " + attr.getAttrName()->getName().str() + " ");
7714 }
7715
7716 moveAttrFromListToList(attr, fromList&: state.getCurrentAttributes(),
7717 toList&: chunk.getAttrs());
7718 return true;
7719 };
7720
7721 // Move it to the outermost pointer, member pointer, or block
7722 // pointer declarator.
7723 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7724 DeclaratorChunk &chunk = declarator.getTypeObject(i: i-1);
7725 switch (chunk.Kind) {
7726 case DeclaratorChunk::Pointer:
7727 case DeclaratorChunk::BlockPointer:
7728 case DeclaratorChunk::MemberPointer:
7729 return moveToChunk(chunk, false);
7730
7731 case DeclaratorChunk::Paren:
7732 case DeclaratorChunk::Array:
7733 continue;
7734
7735 case DeclaratorChunk::Function:
7736 // Try to move past the return type to a function/block/member
7737 // function pointer.
7738 if (DeclaratorChunk *dest = maybeMovePastReturnType(
7739 declarator, i,
7740 /*onlyBlockPointers=*/false)) {
7741 return moveToChunk(*dest, true);
7742 }
7743
7744 return false;
7745
7746 // Don't walk through these.
7747 case DeclaratorChunk::Reference:
7748 case DeclaratorChunk::Pipe:
7749 return false;
7750 }
7751 }
7752
7753 return false;
7754}
7755
7756static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
7757 assert(!Attr.isInvalid());
7758 switch (Attr.getKind()) {
7759 default:
7760 llvm_unreachable("not a calling convention attribute");
7761 case ParsedAttr::AT_CDecl:
7762 return createSimpleAttr<CDeclAttr>(Ctx, AL&: Attr);
7763 case ParsedAttr::AT_FastCall:
7764 return createSimpleAttr<FastCallAttr>(Ctx, AL&: Attr);
7765 case ParsedAttr::AT_StdCall:
7766 return createSimpleAttr<StdCallAttr>(Ctx, AL&: Attr);
7767 case ParsedAttr::AT_ThisCall:
7768 return createSimpleAttr<ThisCallAttr>(Ctx, AL&: Attr);
7769 case ParsedAttr::AT_RegCall:
7770 return createSimpleAttr<RegCallAttr>(Ctx, AL&: Attr);
7771 case ParsedAttr::AT_Pascal:
7772 return createSimpleAttr<PascalAttr>(Ctx, AL&: Attr);
7773 case ParsedAttr::AT_SwiftCall:
7774 return createSimpleAttr<SwiftCallAttr>(Ctx, AL&: Attr);
7775 case ParsedAttr::AT_SwiftAsyncCall:
7776 return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, AL&: Attr);
7777 case ParsedAttr::AT_VectorCall:
7778 return createSimpleAttr<VectorCallAttr>(Ctx, AL&: Attr);
7779 case ParsedAttr::AT_AArch64VectorPcs:
7780 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, AL&: Attr);
7781 case ParsedAttr::AT_AArch64SVEPcs:
7782 return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, AL&: Attr);
7783 case ParsedAttr::AT_ArmStreaming:
7784 return createSimpleAttr<ArmStreamingAttr>(Ctx, AL&: Attr);
7785 case ParsedAttr::AT_Pcs: {
7786 // The attribute may have had a fixit applied where we treated an
7787 // identifier as a string literal. The contents of the string are valid,
7788 // but the form may not be.
7789 StringRef Str;
7790 if (Attr.isArgExpr(Arg: 0))
7791 Str = cast<StringLiteral>(Val: Attr.getArgAsExpr(Arg: 0))->getString();
7792 else
7793 Str = Attr.getArgAsIdent(Arg: 0)->getIdentifierInfo()->getName();
7794 PcsAttr::PCSType Type;
7795 if (!PcsAttr::ConvertStrToPCSType(Val: Str, Out&: Type))
7796 llvm_unreachable("already validated the attribute");
7797 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7798 }
7799 case ParsedAttr::AT_IntelOclBicc:
7800 return createSimpleAttr<IntelOclBiccAttr>(Ctx, AL&: Attr);
7801 case ParsedAttr::AT_MSABI:
7802 return createSimpleAttr<MSABIAttr>(Ctx, AL&: Attr);
7803 case ParsedAttr::AT_SysVABI:
7804 return createSimpleAttr<SysVABIAttr>(Ctx, AL&: Attr);
7805 case ParsedAttr::AT_PreserveMost:
7806 return createSimpleAttr<PreserveMostAttr>(Ctx, AL&: Attr);
7807 case ParsedAttr::AT_PreserveAll:
7808 return createSimpleAttr<PreserveAllAttr>(Ctx, AL&: Attr);
7809 case ParsedAttr::AT_M68kRTD:
7810 return createSimpleAttr<M68kRTDAttr>(Ctx, AL&: Attr);
7811 case ParsedAttr::AT_PreserveNone:
7812 return createSimpleAttr<PreserveNoneAttr>(Ctx, AL&: Attr);
7813 case ParsedAttr::AT_RISCVVectorCC:
7814 return createSimpleAttr<RISCVVectorCCAttr>(Ctx, AL&: Attr);
7815 case ParsedAttr::AT_RISCVVLSCC: {
7816 // If the riscv_abi_vlen doesn't have any argument, we set set it to default
7817 // value 128.
7818 unsigned ABIVLen = 128;
7819 if (Attr.getNumArgs()) {
7820 std::optional<llvm::APSInt> MaybeABIVLen =
7821 Attr.getArgAsExpr(Arg: 0)->getIntegerConstantExpr(Ctx);
7822 if (!MaybeABIVLen)
7823 llvm_unreachable("Invalid RISC-V ABI VLEN");
7824 ABIVLen = MaybeABIVLen->getZExtValue();
7825 }
7826
7827 return ::new (Ctx) RISCVVLSCCAttr(Ctx, Attr, ABIVLen);
7828 }
7829 }
7830 llvm_unreachable("unexpected attribute kind!");
7831}
7832
7833std::optional<FunctionEffectMode>
7834Sema::ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName) {
7835 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent())
7836 return FunctionEffectMode::Dependent;
7837
7838 std::optional<llvm::APSInt> ConditionValue =
7839 CondExpr->getIntegerConstantExpr(Ctx: Context);
7840 if (!ConditionValue) {
7841 // FIXME: err_attribute_argument_type doesn't quote the attribute
7842 // name but needs to; users are inconsistent.
7843 Diag(Loc: CondExpr->getExprLoc(), DiagID: diag::err_attribute_argument_type)
7844 << AttributeName << AANT_ArgumentIntegerConstant
7845 << CondExpr->getSourceRange();
7846 return std::nullopt;
7847 }
7848 return !ConditionValue->isZero() ? FunctionEffectMode::True
7849 : FunctionEffectMode::False;
7850}
7851
7852static bool
7853handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState,
7854 ParsedAttr &PAttr, QualType &QT,
7855 FunctionTypeUnwrapper &Unwrapped) {
7856 // Delay if this is not a function type.
7857 if (!Unwrapped.isFunctionType())
7858 return false;
7859
7860 Sema &S = TPState.getSema();
7861
7862 // Require FunctionProtoType.
7863 auto *FPT = Unwrapped.get()->getAs<FunctionProtoType>();
7864 if (FPT == nullptr) {
7865 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::err_func_with_effects_no_prototype)
7866 << PAttr.getAttrName()->getName();
7867 return true;
7868 }
7869
7870 // Parse the new attribute.
7871 // non/blocking or non/allocating? Or conditional (computed)?
7872 bool IsNonBlocking = PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7873 PAttr.getKind() == ParsedAttr::AT_Blocking;
7874
7875 FunctionEffectMode NewMode = FunctionEffectMode::None;
7876 Expr *CondExpr = nullptr; // only valid if dependent
7877
7878 if (PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7879 PAttr.getKind() == ParsedAttr::AT_NonAllocating) {
7880 if (!PAttr.checkAtMostNumArgs(S, Num: 1)) {
7881 PAttr.setInvalid();
7882 return true;
7883 }
7884
7885 // Parse the condition, if any.
7886 if (PAttr.getNumArgs() == 1) {
7887 CondExpr = PAttr.getArgAsExpr(Arg: 0);
7888 std::optional<FunctionEffectMode> MaybeMode =
7889 S.ActOnEffectExpression(CondExpr, AttributeName: PAttr.getAttrName()->getName());
7890 if (!MaybeMode) {
7891 PAttr.setInvalid();
7892 return true;
7893 }
7894 NewMode = *MaybeMode;
7895 if (NewMode != FunctionEffectMode::Dependent)
7896 CondExpr = nullptr;
7897 } else {
7898 NewMode = FunctionEffectMode::True;
7899 }
7900 } else {
7901 // This is the `blocking` or `allocating` attribute.
7902 if (S.CheckAttrNoArgs(CurrAttr: PAttr)) {
7903 // The attribute has been marked invalid.
7904 return true;
7905 }
7906 NewMode = FunctionEffectMode::False;
7907 }
7908
7909 const FunctionEffect::Kind FEKind =
7910 (NewMode == FunctionEffectMode::False)
7911 ? (IsNonBlocking ? FunctionEffect::Kind::Blocking
7912 : FunctionEffect::Kind::Allocating)
7913 : (IsNonBlocking ? FunctionEffect::Kind::NonBlocking
7914 : FunctionEffect::Kind::NonAllocating);
7915 const FunctionEffectWithCondition NewEC{FunctionEffect(FEKind),
7916 EffectConditionExpr(CondExpr)};
7917
7918 if (S.diagnoseConflictingFunctionEffect(FX: FPT->getFunctionEffects(), EC: NewEC,
7919 NewAttrLoc: PAttr.getLoc())) {
7920 PAttr.setInvalid();
7921 return true;
7922 }
7923
7924 // Add the effect to the FunctionProtoType.
7925 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7926 FunctionEffectSet FX(EPI.FunctionEffects);
7927 FunctionEffectSet::Conflicts Errs;
7928 [[maybe_unused]] bool Success = FX.insert(NewEC, Errs);
7929 assert(Success && "effect conflicts should have been diagnosed above");
7930 EPI.FunctionEffects = FunctionEffectsRef(FX);
7931
7932 QualType NewType = S.Context.getFunctionType(ResultTy: FPT->getReturnType(),
7933 Args: FPT->getParamTypes(), EPI);
7934 QT = Unwrapped.wrap(S, New: NewType->getAs<FunctionType>());
7935 return true;
7936}
7937
7938static bool checkMutualExclusion(TypeProcessingState &state,
7939 const FunctionProtoType::ExtProtoInfo &EPI,
7940 ParsedAttr &Attr,
7941 AttributeCommonInfo::Kind OtherKind) {
7942 auto OtherAttr = llvm::find_if(
7943 Range&: state.getCurrentAttributes(),
7944 P: [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
7945 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid())
7946 return false;
7947
7948 Sema &S = state.getSema();
7949 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
7950 << *OtherAttr << Attr
7951 << (OtherAttr->isRegularKeywordAttribute() ||
7952 Attr.isRegularKeywordAttribute());
7953 S.Diag(Loc: OtherAttr->getLoc(), DiagID: diag::note_conflicting_attribute);
7954 Attr.setInvalid();
7955 return true;
7956}
7957
7958static bool handleArmAgnosticAttribute(Sema &S,
7959 FunctionProtoType::ExtProtoInfo &EPI,
7960 ParsedAttr &Attr) {
7961 if (!Attr.getNumArgs()) {
7962 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_missing_arm_state) << Attr;
7963 Attr.setInvalid();
7964 return true;
7965 }
7966
7967 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
7968 StringRef StateName;
7969 SourceLocation LiteralLoc;
7970 if (!S.checkStringLiteralArgumentAttr(Attr, ArgNum: I, Str&: StateName, ArgLocation: &LiteralLoc))
7971 return true;
7972
7973 if (StateName != "sme_za_state") {
7974 S.Diag(Loc: LiteralLoc, DiagID: diag::err_unknown_arm_state) << StateName;
7975 Attr.setInvalid();
7976 return true;
7977 }
7978
7979 if (EPI.AArch64SMEAttributes &
7980 (FunctionType::SME_ZAMask | FunctionType::SME_ZT0Mask)) {
7981 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_conflicting_attributes_arm_agnostic);
7982 Attr.setInvalid();
7983 return true;
7984 }
7985
7986 EPI.setArmSMEAttribute(Kind: FunctionType::SME_AgnosticZAStateMask);
7987 }
7988
7989 return false;
7990}
7991
7992static bool handleArmStateAttribute(Sema &S,
7993 FunctionProtoType::ExtProtoInfo &EPI,
7994 ParsedAttr &Attr,
7995 FunctionType::ArmStateValue State) {
7996 if (!Attr.getNumArgs()) {
7997 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_missing_arm_state) << Attr;
7998 Attr.setInvalid();
7999 return true;
8000 }
8001
8002 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
8003 StringRef StateName;
8004 SourceLocation LiteralLoc;
8005 if (!S.checkStringLiteralArgumentAttr(Attr, ArgNum: I, Str&: StateName, ArgLocation: &LiteralLoc))
8006 return true;
8007
8008 unsigned Shift;
8009 FunctionType::ArmStateValue ExistingState;
8010 if (StateName == "za") {
8011 Shift = FunctionType::SME_ZAShift;
8012 ExistingState = FunctionType::getArmZAState(AttrBits: EPI.AArch64SMEAttributes);
8013 } else if (StateName == "zt0") {
8014 Shift = FunctionType::SME_ZT0Shift;
8015 ExistingState = FunctionType::getArmZT0State(AttrBits: EPI.AArch64SMEAttributes);
8016 } else {
8017 S.Diag(Loc: LiteralLoc, DiagID: diag::err_unknown_arm_state) << StateName;
8018 Attr.setInvalid();
8019 return true;
8020 }
8021
8022 if (EPI.AArch64SMEAttributes & FunctionType::SME_AgnosticZAStateMask) {
8023 S.Diag(Loc: LiteralLoc, DiagID: diag::err_conflicting_attributes_arm_agnostic);
8024 Attr.setInvalid();
8025 return true;
8026 }
8027
8028 // __arm_in(S), __arm_out(S), __arm_inout(S) and __arm_preserves(S)
8029 // are all mutually exclusive for the same S, so check if there are
8030 // conflicting attributes.
8031 if (ExistingState != FunctionType::ARM_None && ExistingState != State) {
8032 S.Diag(Loc: LiteralLoc, DiagID: diag::err_conflicting_attributes_arm_state)
8033 << StateName;
8034 Attr.setInvalid();
8035 return true;
8036 }
8037
8038 EPI.setArmSMEAttribute(
8039 Kind: (FunctionType::AArch64SMETypeAttributes)((State << Shift)));
8040 }
8041 return false;
8042}
8043
8044/// Process an individual function attribute. Returns true to
8045/// indicate that the attribute was handled, false if it wasn't.
8046static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
8047 QualType &type, CUDAFunctionTarget CFT) {
8048 Sema &S = state.getSema();
8049
8050 FunctionTypeUnwrapper unwrapped(S, type);
8051
8052 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
8053 if (S.CheckAttrNoArgs(CurrAttr: attr))
8054 return true;
8055
8056 // Delay if this is not a function type.
8057 if (!unwrapped.isFunctionType())
8058 return false;
8059
8060 // Otherwise we can process right away.
8061 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(noReturn: true);
8062 type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8063 return true;
8064 }
8065
8066 if (attr.getKind() == ParsedAttr::AT_CFIUncheckedCallee) {
8067 // Delay if this is not a prototyped function type.
8068 if (!unwrapped.isFunctionType())
8069 return false;
8070
8071 if (!unwrapped.get()->isFunctionProtoType()) {
8072 S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_attribute_wrong_decl_type)
8073 << attr << attr.isRegularKeywordAttribute()
8074 << ExpectedFunctionWithProtoType;
8075 attr.setInvalid();
8076 return true;
8077 }
8078
8079 const auto *FPT = unwrapped.get()->getAs<FunctionProtoType>();
8080 type = S.Context.getFunctionType(
8081 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
8082 EPI: FPT->getExtProtoInfo().withCFIUncheckedCallee(CFIUncheckedCallee: true));
8083 type = unwrapped.wrap(S, New: cast<FunctionType>(Val: type.getTypePtr()));
8084 return true;
8085 }
8086
8087 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
8088 // Delay if this is not a function type.
8089 if (!unwrapped.isFunctionType())
8090 return false;
8091
8092 // Ignore if we don't have CMSE enabled.
8093 if (!S.getLangOpts().Cmse) {
8094 S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_attribute_ignored) << attr;
8095 attr.setInvalid();
8096 return true;
8097 }
8098
8099 // Otherwise we can process right away.
8100 FunctionType::ExtInfo EI =
8101 unwrapped.get()->getExtInfo().withCmseNSCall(cmseNSCall: true);
8102 type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8103 return true;
8104 }
8105
8106 // ns_returns_retained is not always a type attribute, but if we got
8107 // here, we're treating it as one right now.
8108 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
8109 if (attr.getNumArgs()) return true;
8110
8111 // Delay if this is not a function type.
8112 if (!unwrapped.isFunctionType())
8113 return false;
8114
8115 // Check whether the return type is reasonable.
8116 if (S.ObjC().checkNSReturnsRetainedReturnType(
8117 loc: attr.getLoc(), type: unwrapped.get()->getReturnType()))
8118 return true;
8119
8120 // Only actually change the underlying type in ARC builds.
8121 QualType origType = type;
8122 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
8123 FunctionType::ExtInfo EI
8124 = unwrapped.get()->getExtInfo().withProducesResult(producesResult: true);
8125 type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8126 }
8127 type = state.getAttributedType(
8128 A: createSimpleAttr<NSReturnsRetainedAttr>(Ctx&: S.Context, AL&: attr),
8129 ModifiedType: origType, EquivType: type);
8130 return true;
8131 }
8132
8133 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
8134 if (S.CheckAttrTarget(CurrAttr: attr) || S.CheckAttrNoArgs(CurrAttr: attr))
8135 return true;
8136
8137 // Delay if this is not a function type.
8138 if (!unwrapped.isFunctionType())
8139 return false;
8140
8141 FunctionType::ExtInfo EI =
8142 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(noCallerSavedRegs: true);
8143 type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8144 return true;
8145 }
8146
8147 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
8148 if (!S.getLangOpts().CFProtectionBranch) {
8149 S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_nocf_check_attribute_ignored);
8150 attr.setInvalid();
8151 return true;
8152 }
8153
8154 if (S.CheckAttrTarget(CurrAttr: attr) || S.CheckAttrNoArgs(CurrAttr: attr))
8155 return true;
8156
8157 // If this is not a function type, warning will be asserted by subject
8158 // check.
8159 if (!unwrapped.isFunctionType())
8160 return true;
8161
8162 FunctionType::ExtInfo EI =
8163 unwrapped.get()->getExtInfo().withNoCfCheck(noCfCheck: true);
8164 type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8165 return true;
8166 }
8167
8168 if (attr.getKind() == ParsedAttr::AT_Regparm) {
8169 unsigned value;
8170 if (S.CheckRegparmAttr(attr, value))
8171 return true;
8172
8173 // Delay if this is not a function type.
8174 if (!unwrapped.isFunctionType())
8175 return false;
8176
8177 // Diagnose regparm with fastcall.
8178 const FunctionType *fn = unwrapped.get();
8179 CallingConv CC = fn->getCallConv();
8180 if (CC == CC_X86FastCall) {
8181 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
8182 << FunctionType::getNameForCallConv(CC) << "regparm"
8183 << attr.isRegularKeywordAttribute();
8184 attr.setInvalid();
8185 return true;
8186 }
8187
8188 FunctionType::ExtInfo EI =
8189 unwrapped.get()->getExtInfo().withRegParm(RegParm: value);
8190 type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8191 return true;
8192 }
8193
8194 if (attr.getKind() == ParsedAttr::AT_CFISalt) {
8195 if (attr.getNumArgs() != 1)
8196 return true;
8197
8198 StringRef Argument;
8199 if (!S.checkStringLiteralArgumentAttr(Attr: attr, ArgNum: 0, Str&: Argument))
8200 return true;
8201
8202 // Delay if this is not a function type.
8203 if (!unwrapped.isFunctionType())
8204 return false;
8205
8206 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8207 if (!FnTy) {
8208 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attribute_wrong_decl_type)
8209 << attr << attr.isRegularKeywordAttribute()
8210 << ExpectedFunctionWithProtoType;
8211 attr.setInvalid();
8212 return true;
8213 }
8214
8215 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8216 EPI.ExtraAttributeInfo.CFISalt = Argument;
8217
8218 QualType newtype = S.Context.getFunctionType(ResultTy: FnTy->getReturnType(),
8219 Args: FnTy->getParamTypes(), EPI);
8220 type = unwrapped.wrap(S, New: newtype->getAs<FunctionType>());
8221 return true;
8222 }
8223
8224 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8225 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible ||
8226 attr.getKind() == ParsedAttr::AT_ArmPreserves ||
8227 attr.getKind() == ParsedAttr::AT_ArmIn ||
8228 attr.getKind() == ParsedAttr::AT_ArmOut ||
8229 attr.getKind() == ParsedAttr::AT_ArmInOut ||
8230 attr.getKind() == ParsedAttr::AT_ArmAgnostic) {
8231 if (S.CheckAttrTarget(CurrAttr: attr))
8232 return true;
8233
8234 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8235 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible)
8236 if (S.CheckAttrNoArgs(CurrAttr: attr))
8237 return true;
8238
8239 if (!unwrapped.isFunctionType())
8240 return false;
8241
8242 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8243 if (!FnTy) {
8244 // SME ACLE attributes are not supported on K&R-style unprototyped C
8245 // functions.
8246 S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_attribute_wrong_decl_type)
8247 << attr << attr.isRegularKeywordAttribute()
8248 << ExpectedFunctionWithProtoType;
8249 attr.setInvalid();
8250 return false;
8251 }
8252
8253 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8254 switch (attr.getKind()) {
8255 case ParsedAttr::AT_ArmStreaming:
8256 if (checkMutualExclusion(state, EPI, Attr&: attr,
8257 OtherKind: ParsedAttr::AT_ArmStreamingCompatible))
8258 return true;
8259 EPI.setArmSMEAttribute(Kind: FunctionType::SME_PStateSMEnabledMask);
8260 break;
8261 case ParsedAttr::AT_ArmStreamingCompatible:
8262 if (checkMutualExclusion(state, EPI, Attr&: attr, OtherKind: ParsedAttr::AT_ArmStreaming))
8263 return true;
8264 EPI.setArmSMEAttribute(Kind: FunctionType::SME_PStateSMCompatibleMask);
8265 break;
8266 case ParsedAttr::AT_ArmPreserves:
8267 if (handleArmStateAttribute(S, EPI, Attr&: attr, State: FunctionType::ARM_Preserves))
8268 return true;
8269 break;
8270 case ParsedAttr::AT_ArmIn:
8271 if (handleArmStateAttribute(S, EPI, Attr&: attr, State: FunctionType::ARM_In))
8272 return true;
8273 break;
8274 case ParsedAttr::AT_ArmOut:
8275 if (handleArmStateAttribute(S, EPI, Attr&: attr, State: FunctionType::ARM_Out))
8276 return true;
8277 break;
8278 case ParsedAttr::AT_ArmInOut:
8279 if (handleArmStateAttribute(S, EPI, Attr&: attr, State: FunctionType::ARM_InOut))
8280 return true;
8281 break;
8282 case ParsedAttr::AT_ArmAgnostic:
8283 if (handleArmAgnosticAttribute(S, EPI, Attr&: attr))
8284 return true;
8285 break;
8286 default:
8287 llvm_unreachable("Unsupported attribute");
8288 }
8289
8290 QualType newtype = S.Context.getFunctionType(ResultTy: FnTy->getReturnType(),
8291 Args: FnTy->getParamTypes(), EPI);
8292 type = unwrapped.wrap(S, New: newtype->getAs<FunctionType>());
8293 return true;
8294 }
8295
8296 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
8297 // Delay if this is not a function type.
8298 if (!unwrapped.isFunctionType())
8299 return false;
8300
8301 if (S.CheckAttrNoArgs(CurrAttr: attr)) {
8302 attr.setInvalid();
8303 return true;
8304 }
8305
8306 // Otherwise we can process right away.
8307 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
8308
8309 // MSVC ignores nothrow if it is in conflict with an explicit exception
8310 // specification.
8311 if (Proto->hasExceptionSpec()) {
8312 switch (Proto->getExceptionSpecType()) {
8313 case EST_None:
8314 llvm_unreachable("This doesn't have an exception spec!");
8315
8316 case EST_DynamicNone:
8317 case EST_BasicNoexcept:
8318 case EST_NoexceptTrue:
8319 case EST_NoThrow:
8320 // Exception spec doesn't conflict with nothrow, so don't warn.
8321 [[fallthrough]];
8322 case EST_Unparsed:
8323 case EST_Uninstantiated:
8324 case EST_DependentNoexcept:
8325 case EST_Unevaluated:
8326 // We don't have enough information to properly determine if there is a
8327 // conflict, so suppress the warning.
8328 break;
8329 case EST_Dynamic:
8330 case EST_MSAny:
8331 case EST_NoexceptFalse:
8332 S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_nothrow_attribute_ignored);
8333 break;
8334 }
8335 return true;
8336 }
8337
8338 type = unwrapped.wrap(
8339 S, New: S.Context
8340 .getFunctionTypeWithExceptionSpec(
8341 Orig: QualType{Proto, 0},
8342 ESI: FunctionProtoType::ExceptionSpecInfo{EST_NoThrow})
8343 ->getAs<FunctionType>());
8344 return true;
8345 }
8346
8347 if (attr.getKind() == ParsedAttr::AT_NonBlocking ||
8348 attr.getKind() == ParsedAttr::AT_NonAllocating ||
8349 attr.getKind() == ParsedAttr::AT_Blocking ||
8350 attr.getKind() == ParsedAttr::AT_Allocating) {
8351 return handleNonBlockingNonAllocatingTypeAttr(TPState&: state, PAttr&: attr, QT&: type, Unwrapped&: unwrapped);
8352 }
8353
8354 // Delay if the type didn't work out to a function.
8355 if (!unwrapped.isFunctionType()) return false;
8356
8357 // Otherwise, a calling convention.
8358 CallingConv CC;
8359 if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/FD: nullptr, CFT))
8360 return true;
8361
8362 const FunctionType *fn = unwrapped.get();
8363 CallingConv CCOld = fn->getCallConv();
8364 Attr *CCAttr = getCCTypeAttr(Ctx&: S.Context, Attr&: attr);
8365
8366 if (CCOld != CC) {
8367 // Error out on when there's already an attribute on the type
8368 // and the CCs don't match.
8369 if (S.getCallingConvAttributedType(T: type)) {
8370 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
8371 << FunctionType::getNameForCallConv(CC)
8372 << FunctionType::getNameForCallConv(CC: CCOld)
8373 << attr.isRegularKeywordAttribute();
8374 attr.setInvalid();
8375 return true;
8376 }
8377 }
8378
8379 // Diagnose use of variadic functions with calling conventions that
8380 // don't support them (e.g. because they're callee-cleanup).
8381 // We delay warning about this on unprototyped function declarations
8382 // until after redeclaration checking, just in case we pick up a
8383 // prototype that way. And apparently we also "delay" warning about
8384 // unprototyped function types in general, despite not necessarily having
8385 // much ability to diagnose it later.
8386 if (!supportsVariadicCall(CC)) {
8387 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(Val: fn);
8388 if (FnP && FnP->isVariadic()) {
8389 // stdcall and fastcall are ignored with a warning for GCC and MS
8390 // compatibility.
8391 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
8392 return S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_cconv_unsupported)
8393 << FunctionType::getNameForCallConv(CC)
8394 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
8395
8396 attr.setInvalid();
8397 return S.Diag(Loc: attr.getLoc(), DiagID: diag::err_cconv_varargs)
8398 << FunctionType::getNameForCallConv(CC);
8399 }
8400 }
8401
8402 // Also diagnose fastcall with regparm.
8403 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
8404 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
8405 << "regparm" << FunctionType::getNameForCallConv(CC: CC_X86FastCall)
8406 << attr.isRegularKeywordAttribute();
8407 attr.setInvalid();
8408 return true;
8409 }
8410
8411 // Modify the CC from the wrapped function type, wrap it all back, and then
8412 // wrap the whole thing in an AttributedType as written. The modified type
8413 // might have a different CC if we ignored the attribute.
8414 QualType Equivalent;
8415 if (CCOld == CC) {
8416 Equivalent = type;
8417 } else {
8418 auto EI = unwrapped.get()->getExtInfo().withCallingConv(cc: CC);
8419 Equivalent =
8420 unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8421 }
8422 type = state.getAttributedType(A: CCAttr, ModifiedType: type, EquivType: Equivalent);
8423 return true;
8424}
8425
8426bool Sema::hasExplicitCallingConv(QualType T) {
8427 const AttributedType *AT;
8428
8429 // Stop if we'd be stripping off a typedef sugar node to reach the
8430 // AttributedType.
8431 while ((AT = T->getAs<AttributedType>()) &&
8432 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
8433 if (AT->isCallingConv())
8434 return true;
8435 T = AT->getModifiedType();
8436 }
8437 return false;
8438}
8439
8440void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
8441 bool IsCtorOrDtor, SourceLocation Loc) {
8442 FunctionTypeUnwrapper Unwrapped(*this, T);
8443 const FunctionType *FT = Unwrapped.get();
8444 bool IsVariadic = (isa<FunctionProtoType>(Val: FT) &&
8445 cast<FunctionProtoType>(Val: FT)->isVariadic());
8446 CallingConv CurCC = FT->getCallConv();
8447 CallingConv ToCC =
8448 Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod: HasThisPointer);
8449
8450 if (CurCC == ToCC)
8451 return;
8452
8453 // MS compiler ignores explicit calling convention attributes on structors. We
8454 // should do the same.
8455 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
8456 // Issue a warning on ignored calling convention -- except of __stdcall.
8457 // Again, this is what MS compiler does.
8458 if (CurCC != CC_X86StdCall)
8459 Diag(Loc, DiagID: diag::warn_cconv_unsupported)
8460 << FunctionType::getNameForCallConv(CC: CurCC)
8461 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
8462 // Default adjustment.
8463 } else {
8464 // Only adjust types with the default convention. For example, on Windows
8465 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8466 // __thiscall type to __cdecl for static methods.
8467 CallingConv DefaultCC =
8468 Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod: !HasThisPointer);
8469
8470 if (CurCC != DefaultCC)
8471 return;
8472
8473 if (hasExplicitCallingConv(T))
8474 return;
8475 }
8476
8477 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: ToCC));
8478 QualType Wrapped = Unwrapped.wrap(S&: *this, New: FT);
8479 T = Context.getAdjustedType(Orig: T, New: Wrapped);
8480}
8481
8482/// HandleVectorSizeAttribute - this attribute is only applicable to integral
8483/// and float scalars, although arrays, pointers, and function return values are
8484/// allowed in conjunction with this construct. Aggregates with this attribute
8485/// are invalid, even if they are of the same size as a corresponding scalar.
8486/// The raw attribute should contain precisely 1 argument, the vector size for
8487/// the variable, measured in bytes. If curType and rawAttr are well formed,
8488/// this routine will return a new vector type.
8489static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8490 Sema &S) {
8491 // Check the attribute arguments.
8492 if (Attr.getNumArgs() != 1) {
8493 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << Attr
8494 << 1;
8495 Attr.setInvalid();
8496 return;
8497 }
8498
8499 Expr *SizeExpr = Attr.getArgAsExpr(Arg: 0);
8500 QualType T = S.BuildVectorType(CurType, SizeExpr, AttrLoc: Attr.getLoc());
8501 if (!T.isNull())
8502 CurType = T;
8503 else
8504 Attr.setInvalid();
8505}
8506
8507/// Process the OpenCL-like ext_vector_type attribute when it occurs on
8508/// a type.
8509static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8510 Sema &S) {
8511 // check the attribute arguments.
8512 if (Attr.getNumArgs() != 1) {
8513 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << Attr
8514 << 1;
8515 return;
8516 }
8517
8518 Expr *SizeExpr = Attr.getArgAsExpr(Arg: 0);
8519 QualType T = S.BuildExtVectorType(T: CurType, SizeExpr, AttrLoc: Attr.getLoc());
8520 if (!T.isNull())
8521 CurType = T;
8522}
8523
8524static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) {
8525 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8526 if (!BTy)
8527 return false;
8528
8529 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8530
8531 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8532 // now.
8533 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8534 Triple.getArch() == llvm::Triple::aarch64_32 ||
8535 Triple.getArch() == llvm::Triple::aarch64_be;
8536 if (VecKind == VectorKind::NeonPoly) {
8537 if (IsPolyUnsigned) {
8538 // AArch64 polynomial vectors are unsigned.
8539 return BTy->getKind() == BuiltinType::UChar ||
8540 BTy->getKind() == BuiltinType::UShort ||
8541 BTy->getKind() == BuiltinType::ULong ||
8542 BTy->getKind() == BuiltinType::ULongLong;
8543 } else {
8544 // AArch32 polynomial vectors are signed.
8545 return BTy->getKind() == BuiltinType::SChar ||
8546 BTy->getKind() == BuiltinType::Short ||
8547 BTy->getKind() == BuiltinType::LongLong;
8548 }
8549 }
8550
8551 // Non-polynomial vector types: the usual suspects are allowed, as well as
8552 // float64_t on AArch64.
8553 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8554 BTy->getKind() == BuiltinType::Double)
8555 return true;
8556
8557 return BTy->getKind() == BuiltinType::SChar ||
8558 BTy->getKind() == BuiltinType::UChar ||
8559 BTy->getKind() == BuiltinType::Short ||
8560 BTy->getKind() == BuiltinType::UShort ||
8561 BTy->getKind() == BuiltinType::Int ||
8562 BTy->getKind() == BuiltinType::UInt ||
8563 BTy->getKind() == BuiltinType::Long ||
8564 BTy->getKind() == BuiltinType::ULong ||
8565 BTy->getKind() == BuiltinType::LongLong ||
8566 BTy->getKind() == BuiltinType::ULongLong ||
8567 BTy->getKind() == BuiltinType::Float ||
8568 BTy->getKind() == BuiltinType::Half ||
8569 BTy->getKind() == BuiltinType::BFloat16 ||
8570 BTy->getKind() == BuiltinType::MFloat8;
8571}
8572
8573static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr,
8574 llvm::APSInt &Result) {
8575 const auto *AttrExpr = Attr.getArgAsExpr(Arg: 0);
8576 if (!AttrExpr->isTypeDependent()) {
8577 if (std::optional<llvm::APSInt> Res =
8578 AttrExpr->getIntegerConstantExpr(Ctx: S.Context)) {
8579 Result = *Res;
8580 return true;
8581 }
8582 }
8583 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_argument_type)
8584 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8585 Attr.setInvalid();
8586 return false;
8587}
8588
8589/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8590/// "neon_polyvector_type" attributes are used to create vector types that
8591/// are mangled according to ARM's ABI. Otherwise, these types are identical
8592/// to those created with the "vector_size" attribute. Unlike "vector_size"
8593/// the argument to these Neon attributes is the number of vector elements,
8594/// not the vector size in bytes. The vector width and element type must
8595/// match one of the standard Neon vector types.
8596static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8597 Sema &S, VectorKind VecKind) {
8598 bool IsTargetOffloading = S.getLangOpts().isTargetDevice();
8599
8600 // Target must have NEON (or MVE, whose vectors are similar enough
8601 // not to need a separate attribute)
8602 if (!S.Context.getTargetInfo().hasFeature(Feature: "mve") &&
8603 VecKind == VectorKind::Neon &&
8604 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8605 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_unsupported_m_profile)
8606 << Attr << "'mve'";
8607 Attr.setInvalid();
8608 return;
8609 }
8610 if (!S.Context.getTargetInfo().hasFeature(Feature: "mve") &&
8611 VecKind == VectorKind::NeonPoly &&
8612 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8613 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_unsupported_m_profile)
8614 << Attr << "'mve'";
8615 Attr.setInvalid();
8616 return;
8617 }
8618
8619 // Check the attribute arguments.
8620 if (Attr.getNumArgs() != 1) {
8621 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments)
8622 << Attr << 1;
8623 Attr.setInvalid();
8624 return;
8625 }
8626 // The number of elements must be an ICE.
8627 llvm::APSInt numEltsInt(32);
8628 if (!verifyValidIntegerConstantExpr(S, Attr, Result&: numEltsInt))
8629 return;
8630
8631 // Only certain element types are supported for Neon vectors.
8632 if (!isPermittedNeonBaseType(Ty&: CurType, VecKind, S) && !IsTargetOffloading) {
8633 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_invalid_vector_type) << CurType;
8634 Attr.setInvalid();
8635 return;
8636 }
8637
8638 // The total size of the vector must be 64 or 128 bits.
8639 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(T: CurType));
8640 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8641 unsigned vecSize = typeSize * numElts;
8642 if (vecSize != 64 && vecSize != 128) {
8643 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_bad_neon_vector_size) << CurType;
8644 Attr.setInvalid();
8645 return;
8646 }
8647
8648 CurType = S.Context.getVectorType(VectorType: CurType, NumElts: numElts, VecKind);
8649}
8650
8651/// Handle the __ptrauth qualifier.
8652static void HandlePtrAuthQualifier(ASTContext &Ctx, QualType &T,
8653 const ParsedAttr &Attr, Sema &S) {
8654
8655 assert((Attr.getNumArgs() > 0 && Attr.getNumArgs() <= 3) &&
8656 "__ptrauth qualifier takes between 1 and 3 arguments");
8657 Expr *KeyArg = Attr.getArgAsExpr(Arg: 0);
8658 Expr *IsAddressDiscriminatedArg =
8659 Attr.getNumArgs() >= 2 ? Attr.getArgAsExpr(Arg: 1) : nullptr;
8660 Expr *ExtraDiscriminatorArg =
8661 Attr.getNumArgs() >= 3 ? Attr.getArgAsExpr(Arg: 2) : nullptr;
8662
8663 unsigned Key;
8664 if (S.checkConstantPointerAuthKey(keyExpr: KeyArg, key&: Key)) {
8665 Attr.setInvalid();
8666 return;
8667 }
8668 assert(Key <= PointerAuthQualifier::MaxKey && "ptrauth key is out of range");
8669
8670 bool IsInvalid = false;
8671 unsigned IsAddressDiscriminated, ExtraDiscriminator;
8672 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(Arg: IsAddressDiscriminatedArg,
8673 Kind: PointerAuthDiscArgKind::Addr,
8674 IntVal&: IsAddressDiscriminated);
8675 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(
8676 Arg: ExtraDiscriminatorArg, Kind: PointerAuthDiscArgKind::Extra, IntVal&: ExtraDiscriminator);
8677
8678 if (IsInvalid) {
8679 Attr.setInvalid();
8680 return;
8681 }
8682
8683 if (!T->isSignableType(Ctx) && !T->isDependentType()) {
8684 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_ptrauth_qualifier_invalid_target) << T;
8685 Attr.setInvalid();
8686 return;
8687 }
8688
8689 if (T.getPointerAuth()) {
8690 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_ptrauth_qualifier_redundant) << T;
8691 Attr.setInvalid();
8692 return;
8693 }
8694
8695 if (!S.getLangOpts().PointerAuthIntrinsics) {
8696 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_ptrauth_disabled) << Attr.getRange();
8697 Attr.setInvalid();
8698 return;
8699 }
8700
8701 assert((!IsAddressDiscriminatedArg || IsAddressDiscriminated <= 1) &&
8702 "address discriminator arg should be either 0 or 1");
8703 PointerAuthQualifier Qual = PointerAuthQualifier::Create(
8704 Key, IsAddressDiscriminated, ExtraDiscriminator,
8705 AuthenticationMode: PointerAuthenticationMode::SignAndAuth, /*IsIsaPointer=*/false,
8706 /*AuthenticatesNullValues=*/false);
8707 T = S.Context.getPointerAuthType(Ty: T, PointerAuth: Qual);
8708}
8709
8710/// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8711/// used to create fixed-length versions of sizeless SVE types defined by
8712/// the ACLE, such as svint32_t and svbool_t.
8713static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr,
8714 Sema &S) {
8715 // Target must have SVE.
8716 if (!S.Context.getTargetInfo().hasFeature(Feature: "sve")) {
8717 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_unsupported) << Attr << "'sve'";
8718 Attr.setInvalid();
8719 return;
8720 }
8721
8722 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8723 // if <bits>+ syntax is used.
8724 if (!S.getLangOpts().VScaleMin ||
8725 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8726 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_arm_feature_sve_bits_unsupported)
8727 << Attr;
8728 Attr.setInvalid();
8729 return;
8730 }
8731
8732 // Check the attribute arguments.
8733 if (Attr.getNumArgs() != 1) {
8734 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments)
8735 << Attr << 1;
8736 Attr.setInvalid();
8737 return;
8738 }
8739
8740 // The vector size must be an integer constant expression.
8741 llvm::APSInt SveVectorSizeInBits(32);
8742 if (!verifyValidIntegerConstantExpr(S, Attr, Result&: SveVectorSizeInBits))
8743 return;
8744
8745 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8746
8747 // The attribute vector size must match -msve-vector-bits.
8748 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8749 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_bad_sve_vector_size)
8750 << VecSize << S.getLangOpts().VScaleMin * 128;
8751 Attr.setInvalid();
8752 return;
8753 }
8754
8755 // Attribute can only be attached to a single SVE vector or predicate type.
8756 if (!CurType->isSveVLSBuiltinType()) {
8757 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_invalid_sve_type)
8758 << Attr << CurType;
8759 Attr.setInvalid();
8760 return;
8761 }
8762
8763 const auto *BT = CurType->castAs<BuiltinType>();
8764
8765 QualType EltType = CurType->getSveEltType(Ctx: S.Context);
8766 unsigned TypeSize = S.Context.getTypeSize(T: EltType);
8767 VectorKind VecKind = VectorKind::SveFixedLengthData;
8768 if (BT->getKind() == BuiltinType::SveBool) {
8769 // Predicates are represented as i8.
8770 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8771 VecKind = VectorKind::SveFixedLengthPredicate;
8772 } else
8773 VecSize /= TypeSize;
8774 CurType = S.Context.getVectorType(VectorType: EltType, NumElts: VecSize, VecKind);
8775}
8776
8777static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8778 QualType &CurType,
8779 ParsedAttr &Attr) {
8780 const VectorType *VT = dyn_cast<VectorType>(Val&: CurType);
8781 if (!VT || VT->getVectorKind() != VectorKind::Neon) {
8782 State.getSema().Diag(Loc: Attr.getLoc(),
8783 DiagID: diag::err_attribute_arm_mve_polymorphism);
8784 Attr.setInvalid();
8785 return;
8786 }
8787
8788 CurType =
8789 State.getAttributedType(A: createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8790 Ctx&: State.getSema().Context, AL&: Attr),
8791 ModifiedType: CurType, EquivType: CurType);
8792}
8793
8794/// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8795/// used to create fixed-length versions of sizeless RVV types such as
8796/// vint8m1_t_t.
8797static void HandleRISCVRVVVectorBitsTypeAttr(QualType &CurType,
8798 ParsedAttr &Attr, Sema &S) {
8799 // Target must have vector extension.
8800 if (!S.Context.getTargetInfo().hasFeature(Feature: "zve32x")) {
8801 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_unsupported)
8802 << Attr << "'zve32x'";
8803 Attr.setInvalid();
8804 return;
8805 }
8806
8807 auto VScale = S.Context.getTargetInfo().getVScaleRange(
8808 LangOpts: S.getLangOpts(), Mode: TargetInfo::ArmStreamingKind::NotStreaming);
8809 if (!VScale || !VScale->first || VScale->first != VScale->second) {
8810 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_riscv_rvv_bits_unsupported)
8811 << Attr;
8812 Attr.setInvalid();
8813 return;
8814 }
8815
8816 // Check the attribute arguments.
8817 if (Attr.getNumArgs() != 1) {
8818 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments)
8819 << Attr << 1;
8820 Attr.setInvalid();
8821 return;
8822 }
8823
8824 // The vector size must be an integer constant expression.
8825 llvm::APSInt RVVVectorSizeInBits(32);
8826 if (!verifyValidIntegerConstantExpr(S, Attr, Result&: RVVVectorSizeInBits))
8827 return;
8828
8829 // Attribute can only be attached to a single RVV vector type.
8830 if (!CurType->isRVVVLSBuiltinType()) {
8831 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_invalid_rvv_type)
8832 << Attr << CurType;
8833 Attr.setInvalid();
8834 return;
8835 }
8836
8837 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8838
8839 ASTContext::BuiltinVectorTypeInfo Info =
8840 S.Context.getBuiltinVectorTypeInfo(VecTy: CurType->castAs<BuiltinType>());
8841 unsigned MinElts = Info.EC.getKnownMinValue();
8842
8843 VectorKind VecKind = VectorKind::RVVFixedLengthData;
8844 unsigned ExpectedSize = VScale->first * MinElts;
8845 QualType EltType = CurType->getRVVEltType(Ctx: S.Context);
8846 unsigned EltSize = S.Context.getTypeSize(T: EltType);
8847 unsigned NumElts;
8848 if (Info.ElementType == S.Context.BoolTy) {
8849 NumElts = VecSize / S.Context.getCharWidth();
8850 if (!NumElts) {
8851 NumElts = 1;
8852 switch (VecSize) {
8853 case 1:
8854 VecKind = VectorKind::RVVFixedLengthMask_1;
8855 break;
8856 case 2:
8857 VecKind = VectorKind::RVVFixedLengthMask_2;
8858 break;
8859 case 4:
8860 VecKind = VectorKind::RVVFixedLengthMask_4;
8861 break;
8862 }
8863 } else
8864 VecKind = VectorKind::RVVFixedLengthMask;
8865 } else {
8866 ExpectedSize *= EltSize;
8867 NumElts = VecSize / EltSize;
8868 }
8869
8870 // The attribute vector size must match -mrvv-vector-bits.
8871 if (VecSize != ExpectedSize) {
8872 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_bad_rvv_vector_size)
8873 << VecSize << ExpectedSize;
8874 Attr.setInvalid();
8875 return;
8876 }
8877
8878 CurType = S.Context.getVectorType(VectorType: EltType, NumElts, VecKind);
8879}
8880
8881/// Handle OpenCL Access Qualifier Attribute.
8882static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8883 Sema &S) {
8884 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8885 if (!(CurType->isImageType() || CurType->isPipeType())) {
8886 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_opencl_invalid_access_qualifier);
8887 Attr.setInvalid();
8888 return;
8889 }
8890
8891 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8892 QualType BaseTy = TypedefTy->desugar();
8893
8894 std::string PrevAccessQual;
8895 if (BaseTy->isPipeType()) {
8896 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8897 OpenCLAccessAttr *Attr =
8898 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8899 PrevAccessQual = Attr->getSpelling();
8900 } else {
8901 PrevAccessQual = "read_only";
8902 }
8903 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8904
8905 switch (ImgType->getKind()) {
8906 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8907 case BuiltinType::Id: \
8908 PrevAccessQual = #Access; \
8909 break;
8910 #include "clang/Basic/OpenCLImageTypes.def"
8911 default:
8912 llvm_unreachable("Unable to find corresponding image type.");
8913 }
8914 } else {
8915 llvm_unreachable("unexpected type");
8916 }
8917 StringRef AttrName = Attr.getAttrName()->getName();
8918 if (PrevAccessQual == AttrName.ltrim(Chars: "_")) {
8919 // Duplicated qualifiers
8920 S.Diag(Loc: Attr.getLoc(), DiagID: diag::warn_duplicate_declspec)
8921 << AttrName << Attr.getRange();
8922 } else {
8923 // Contradicting qualifiers
8924 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_opencl_multiple_access_qualifiers);
8925 }
8926
8927 S.Diag(Loc: TypedefTy->getDecl()->getBeginLoc(),
8928 DiagID: diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8929 } else if (CurType->isPipeType()) {
8930 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8931 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8932 CurType = S.Context.getWritePipeType(T: ElemType);
8933 }
8934 }
8935}
8936
8937/// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8938static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8939 Sema &S) {
8940 if (!S.getLangOpts().MatrixTypes) {
8941 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_builtin_matrix_disabled);
8942 return;
8943 }
8944
8945 if (Attr.getNumArgs() != 2) {
8946 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments)
8947 << Attr << 2;
8948 return;
8949 }
8950
8951 Expr *RowsExpr = Attr.getArgAsExpr(Arg: 0);
8952 Expr *ColsExpr = Attr.getArgAsExpr(Arg: 1);
8953 QualType T = S.BuildMatrixType(ElementTy: CurType, NumRows: RowsExpr, NumCols: ColsExpr, AttrLoc: Attr.getLoc());
8954 if (!T.isNull())
8955 CurType = T;
8956}
8957
8958static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8959 QualType &CurType, const ParsedAttr &PA) {
8960 Sema &S = State.getSema();
8961
8962 if (PA.getNumArgs() < 1) {
8963 S.Diag(Loc: PA.getLoc(), DiagID: diag::err_attribute_too_few_arguments) << PA << 1;
8964 return;
8965 }
8966
8967 // Make sure that there is a string literal as the annotation's first
8968 // argument.
8969 StringRef Str;
8970 if (!S.checkStringLiteralArgumentAttr(Attr: PA, ArgNum: 0, Str))
8971 return;
8972
8973 llvm::SmallVector<Expr *, 4> Args;
8974 Args.reserve(N: PA.getNumArgs() - 1);
8975 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
8976 assert(!PA.isArgIdent(Idx));
8977 Args.push_back(Elt: PA.getArgAsExpr(Arg: Idx));
8978 }
8979 if (!S.ConstantFoldAttrArgs(CI: PA, Args))
8980 return;
8981 auto *AnnotateTypeAttr =
8982 AnnotateTypeAttr::Create(Ctx&: S.Context, Annotation: Str, Args: Args.data(), ArgsSize: Args.size(), CommonInfo: PA);
8983 CurType = State.getAttributedType(A: AnnotateTypeAttr, ModifiedType: CurType, EquivType: CurType);
8984}
8985
8986static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8987 QualType &CurType,
8988 ParsedAttr &Attr) {
8989 if (State.getDeclarator().isDeclarationOfFunction()) {
8990 CurType = State.getAttributedType(
8991 A: createSimpleAttr<LifetimeBoundAttr>(Ctx&: State.getSema().Context, AL&: Attr),
8992 ModifiedType: CurType, EquivType: CurType);
8993 return;
8994 }
8995 State.getSema().Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_decl_type)
8996 << Attr << Attr.isRegularKeywordAttribute()
8997 << ExpectedParameterOrImplicitObjectParameter;
8998}
8999
9000static void HandleLifetimeCaptureByAttr(TypeProcessingState &State,
9001 QualType &CurType, ParsedAttr &PA) {
9002 if (State.getDeclarator().isDeclarationOfFunction()) {
9003 auto *Attr = State.getSema().ParseLifetimeCaptureByAttr(AL: PA, ParamName: "this");
9004 if (Attr)
9005 CurType = State.getAttributedType(A: Attr, ModifiedType: CurType, EquivType: CurType);
9006 }
9007}
9008
9009static void HandleHLSLParamModifierAttr(TypeProcessingState &State,
9010 QualType &CurType,
9011 const ParsedAttr &Attr, Sema &S) {
9012 // Don't apply this attribute to template dependent types. It is applied on
9013 // substitution during template instantiation. Also skip parsing this if we've
9014 // already modified the type based on an earlier attribute.
9015 if (CurType->isDependentType() || State.didParseHLSLParamMod())
9016 return;
9017 if (Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout ||
9018 Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out) {
9019 State.setParsedHLSLParamMod(true);
9020 }
9021}
9022
9023static void processTypeAttrs(TypeProcessingState &state, QualType &type,
9024 TypeAttrLocation TAL,
9025 const ParsedAttributesView &attrs,
9026 CUDAFunctionTarget CFT) {
9027
9028 state.setParsedNoDeref(false);
9029 if (attrs.empty())
9030 return;
9031
9032 // Scan through and apply attributes to this type where it makes sense. Some
9033 // attributes (such as __address_space__, __vector_size__, etc) apply to the
9034 // type, but others can be present in the type specifiers even though they
9035 // apply to the decl. Here we apply type attributes and ignore the rest.
9036
9037 // This loop modifies the list pretty frequently, but we still need to make
9038 // sure we visit every element once. Copy the attributes list, and iterate
9039 // over that.
9040 ParsedAttributesView AttrsCopy{attrs};
9041 for (ParsedAttr &attr : AttrsCopy) {
9042
9043 // Skip attributes that were marked to be invalid.
9044 if (attr.isInvalid())
9045 continue;
9046
9047 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) {
9048 // [[gnu::...]] attributes are treated as declaration attributes, so may
9049 // not appertain to a DeclaratorChunk. If we handle them as type
9050 // attributes, accept them in that position and diagnose the GCC
9051 // incompatibility.
9052 if (attr.isGNUScope()) {
9053 assert(attr.isStandardAttributeSyntax());
9054 bool IsTypeAttr = attr.isTypeAttr();
9055 if (TAL == TAL_DeclChunk) {
9056 state.getSema().Diag(Loc: attr.getLoc(),
9057 DiagID: IsTypeAttr
9058 ? diag::warn_gcc_ignores_type_attr
9059 : diag::warn_cxx11_gnu_attribute_on_type)
9060 << attr;
9061 if (!IsTypeAttr)
9062 continue;
9063 }
9064 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
9065 !attr.isTypeAttr()) {
9066 // Otherwise, only consider type processing for a C++11 attribute if
9067 // - it has actually been applied to a type (decl-specifier-seq or
9068 // declarator chunk), or
9069 // - it is a type attribute, irrespective of where it was applied (so
9070 // that we can support the legacy behavior of some type attributes
9071 // that can be applied to the declaration name).
9072 continue;
9073 }
9074 }
9075
9076 // If this is an attribute we can handle, do so now,
9077 // otherwise, add it to the FnAttrs list for rechaining.
9078 switch (attr.getKind()) {
9079 default:
9080 // A [[]] attribute on a declarator chunk must appertain to a type.
9081 if ((attr.isStandardAttributeSyntax() ||
9082 attr.isRegularKeywordAttribute()) &&
9083 TAL == TAL_DeclChunk) {
9084 state.getSema().Diag(Loc: attr.getLoc(), DiagID: diag::err_attribute_not_type_attr)
9085 << attr << attr.isRegularKeywordAttribute();
9086 attr.setUsedAsTypeAttr();
9087 }
9088 break;
9089
9090 case ParsedAttr::UnknownAttribute:
9091 if (attr.isStandardAttributeSyntax()) {
9092 state.getSema().DiagnoseUnknownAttribute(AL: attr);
9093 // Mark the attribute as invalid so we don't emit the same diagnostic
9094 // multiple times.
9095 attr.setInvalid();
9096 }
9097 break;
9098
9099 case ParsedAttr::IgnoredAttribute:
9100 break;
9101
9102 case ParsedAttr::AT_BTFTypeTag:
9103 HandleBTFTypeTagAttribute(Type&: type, Attr: attr, State&: state);
9104 attr.setUsedAsTypeAttr();
9105 break;
9106
9107 case ParsedAttr::AT_MayAlias:
9108 // FIXME: This attribute needs to actually be handled, but if we ignore
9109 // it it breaks large amounts of Linux software.
9110 attr.setUsedAsTypeAttr();
9111 break;
9112 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
9113 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
9114 state.getSema().Diag(Loc: attr.getLoc(), DiagID: diag::warn_deprecated_attribute)
9115 << attr;
9116 [[fallthrough]];
9117 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
9118 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
9119 case ParsedAttr::AT_OpenCLLocalAddressSpace:
9120 case ParsedAttr::AT_OpenCLConstantAddressSpace:
9121 case ParsedAttr::AT_OpenCLGenericAddressSpace:
9122 case ParsedAttr::AT_AddressSpace:
9123 HandleAddressSpaceTypeAttribute(Type&: type, Attr: attr, State&: state);
9124 attr.setUsedAsTypeAttr();
9125 break;
9126 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
9127 HandleAddressSpaceTypeAttribute(Type&: type, Attr: attr, State&: state);
9128 if (state.getDeclarator().getContext() == DeclaratorContext::Prototype) {
9129 if (state.getSema().getLangOpts().getHLSLVersion() <
9130 LangOptions::HLSL_202x)
9131 state.getSema().Diag(Loc: attr.getLoc(), DiagID: diag::warn_hlsl_groupshared_202x);
9132
9133 // Note: we don't check for the usage of HLSLParamModifiers in/out/inout
9134 // here because the check in the AT_HLSLParamModifier case is sufficient
9135 // regardless of the order of groupshared or in/out/inout specified in
9136 // the parameter. And checking there produces a better error message.
9137 }
9138 attr.setUsedAsTypeAttr();
9139 break;
9140 case ParsedAttr::AT_HLSLRowMajor:
9141 case ParsedAttr::AT_HLSLColumnMajor:
9142 if (Attr *A =
9143 state.getSema().HLSL().buildMatrixLayoutTypeAttr(T: type, AL: attr))
9144 type = state.getAttributedType(A, ModifiedType: type, EquivType: type);
9145 attr.setUsedAsTypeAttr();
9146 break;
9147 OBJC_POINTER_TYPE_ATTRS_CASELIST:
9148 if (!handleObjCPointerTypeAttr(state, attr, type))
9149 distributeObjCPointerTypeAttr(state, attr, type);
9150 attr.setUsedAsTypeAttr();
9151 break;
9152 case ParsedAttr::AT_VectorSize:
9153 HandleVectorSizeAttr(CurType&: type, Attr: attr, S&: state.getSema());
9154 attr.setUsedAsTypeAttr();
9155 break;
9156 case ParsedAttr::AT_ExtVectorType:
9157 HandleExtVectorTypeAttr(CurType&: type, Attr: attr, S&: state.getSema());
9158 attr.setUsedAsTypeAttr();
9159 break;
9160 case ParsedAttr::AT_NeonVectorType:
9161 HandleNeonVectorTypeAttr(CurType&: type, Attr: attr, S&: state.getSema(), VecKind: VectorKind::Neon);
9162 attr.setUsedAsTypeAttr();
9163 break;
9164 case ParsedAttr::AT_NeonPolyVectorType:
9165 HandleNeonVectorTypeAttr(CurType&: type, Attr: attr, S&: state.getSema(),
9166 VecKind: VectorKind::NeonPoly);
9167 attr.setUsedAsTypeAttr();
9168 break;
9169 case ParsedAttr::AT_ArmSveVectorBits:
9170 HandleArmSveVectorBitsTypeAttr(CurType&: type, Attr&: attr, S&: state.getSema());
9171 attr.setUsedAsTypeAttr();
9172 break;
9173 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
9174 HandleArmMveStrictPolymorphismAttr(State&: state, CurType&: type, Attr&: attr);
9175 attr.setUsedAsTypeAttr();
9176 break;
9177 }
9178 case ParsedAttr::AT_RISCVRVVVectorBits:
9179 HandleRISCVRVVVectorBitsTypeAttr(CurType&: type, Attr&: attr, S&: state.getSema());
9180 attr.setUsedAsTypeAttr();
9181 break;
9182 case ParsedAttr::AT_OpenCLAccess:
9183 HandleOpenCLAccessAttr(CurType&: type, Attr: attr, S&: state.getSema());
9184 attr.setUsedAsTypeAttr();
9185 break;
9186 case ParsedAttr::AT_PointerAuth:
9187 HandlePtrAuthQualifier(Ctx&: state.getSema().Context, T&: type, Attr: attr,
9188 S&: state.getSema());
9189 attr.setUsedAsTypeAttr();
9190 break;
9191 case ParsedAttr::AT_LifetimeBound:
9192 if (TAL == TAL_DeclChunk)
9193 HandleLifetimeBoundAttr(State&: state, CurType&: type, Attr&: attr);
9194 break;
9195 case ParsedAttr::AT_LifetimeCaptureBy:
9196 if (TAL == TAL_DeclChunk)
9197 HandleLifetimeCaptureByAttr(State&: state, CurType&: type, PA&: attr);
9198 break;
9199 case ParsedAttr::AT_OverflowBehavior:
9200 HandleOverflowBehaviorAttr(Type&: type, Attr: attr, State&: state);
9201 attr.setUsedAsTypeAttr();
9202 break;
9203
9204 case ParsedAttr::AT_NoDeref: {
9205 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
9206 // See https://github.com/llvm/llvm-project/issues/55790 for details.
9207 // For the time being, we simply emit a warning that the attribute is
9208 // ignored.
9209 if (attr.isStandardAttributeSyntax()) {
9210 state.getSema().Diag(Loc: attr.getLoc(), DiagID: diag::warn_attribute_ignored)
9211 << attr;
9212 break;
9213 }
9214 ASTContext &Ctx = state.getSema().Context;
9215 type = state.getAttributedType(A: createSimpleAttr<NoDerefAttr>(Ctx, AL&: attr),
9216 ModifiedType: type, EquivType: type);
9217 attr.setUsedAsTypeAttr();
9218 state.setParsedNoDeref(true);
9219 break;
9220 }
9221
9222 case ParsedAttr::AT_MatrixType:
9223 HandleMatrixTypeAttr(CurType&: type, Attr: attr, S&: state.getSema());
9224 attr.setUsedAsTypeAttr();
9225 break;
9226
9227 case ParsedAttr::AT_WebAssemblyFuncref: {
9228 if (!HandleWebAssemblyFuncrefAttr(State&: state, QT&: type, PAttr&: attr))
9229 attr.setUsedAsTypeAttr();
9230 break;
9231 }
9232
9233 case ParsedAttr::AT_HLSLParamModifier: {
9234 HandleHLSLParamModifierAttr(State&: state, CurType&: type, Attr: attr, S&: state.getSema());
9235 if (attrs.hasAttribute(K: ParsedAttr::AT_HLSLGroupSharedAddressSpace)) {
9236 state.getSema().Diag(Loc: attr.getLoc(), DiagID: diag::err_hlsl_attr_incompatible)
9237 << attr << "'groupshared'";
9238 attr.setInvalid();
9239 return;
9240 }
9241 attr.setUsedAsTypeAttr();
9242 break;
9243 }
9244
9245 case ParsedAttr::AT_SwiftAttr: {
9246 HandleSwiftAttr(State&: state, TAL, QT&: type, PAttr&: attr);
9247 break;
9248 }
9249
9250 MS_TYPE_ATTRS_CASELIST:
9251 if (!handleMSPointerTypeQualifierAttr(State&: state, PAttr&: attr, Type&: type))
9252 attr.setUsedAsTypeAttr();
9253 break;
9254
9255
9256 NULLABILITY_TYPE_ATTRS_CASELIST:
9257 // Either add nullability here or try to distribute it. We
9258 // don't want to distribute the nullability specifier past any
9259 // dependent type, because that complicates the user model.
9260 if (type->canHaveNullability() || type->isDependentType() ||
9261 type->isArrayType() ||
9262 !distributeNullabilityTypeAttr(state, type, attr)) {
9263 unsigned endIndex;
9264 if (TAL == TAL_DeclChunk)
9265 endIndex = state.getCurrentChunkIndex();
9266 else
9267 endIndex = state.getDeclarator().getNumTypeObjects();
9268 bool allowOnArrayType =
9269 state.getDeclarator().isPrototypeContext() &&
9270 !hasOuterPointerLikeChunk(D: state.getDeclarator(), endIndex);
9271 if (CheckNullabilityTypeSpecifier(State&: state, Type&: type, Attr&: attr,
9272 AllowOnArrayType: allowOnArrayType)) {
9273 attr.setInvalid();
9274 }
9275
9276 attr.setUsedAsTypeAttr();
9277 }
9278 break;
9279
9280 case ParsedAttr::AT_ObjCKindOf:
9281 // '__kindof' must be part of the decl-specifiers.
9282 switch (TAL) {
9283 case TAL_DeclSpec:
9284 break;
9285
9286 case TAL_DeclChunk:
9287 case TAL_DeclName:
9288 state.getSema().Diag(Loc: attr.getLoc(),
9289 DiagID: diag::err_objc_kindof_wrong_position)
9290 << FixItHint::CreateRemoval(RemoveRange: attr.getLoc())
9291 << FixItHint::CreateInsertion(
9292 InsertionLoc: state.getDeclarator().getDeclSpec().getBeginLoc(),
9293 Code: "__kindof ");
9294 break;
9295 }
9296
9297 // Apply it regardless.
9298 if (checkObjCKindOfType(state, type, attr))
9299 attr.setInvalid();
9300 break;
9301
9302 case ParsedAttr::AT_NoThrow:
9303 // Exception Specifications aren't generally supported in C mode throughout
9304 // clang, so revert to attribute-based handling for C.
9305 if (!state.getSema().getLangOpts().CPlusPlus)
9306 break;
9307 [[fallthrough]];
9308 FUNCTION_TYPE_ATTRS_CASELIST:
9309
9310 attr.setUsedAsTypeAttr();
9311
9312 // Attributes with standard syntax have strict rules for what they
9313 // appertain to and hence should not use the "distribution" logic below.
9314 if (attr.isStandardAttributeSyntax() ||
9315 attr.isRegularKeywordAttribute()) {
9316 if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
9317 diagnoseBadTypeAttribute(S&: state.getSema(), attr, type);
9318 attr.setInvalid();
9319 }
9320 break;
9321 }
9322
9323 // Never process function type attributes as part of the
9324 // declaration-specifiers.
9325 if (TAL == TAL_DeclSpec)
9326 distributeFunctionTypeAttrFromDeclSpec(state, attr, declSpecType&: type, CFT);
9327
9328 // Otherwise, handle the possible delays.
9329 else if (!handleFunctionTypeAttr(state, attr, type, CFT))
9330 distributeFunctionTypeAttr(state, attr, type);
9331 break;
9332 case ParsedAttr::AT_AcquireHandle: {
9333 if (!type->isFunctionType())
9334 return;
9335
9336 if (attr.getNumArgs() != 1) {
9337 state.getSema().Diag(Loc: attr.getLoc(),
9338 DiagID: diag::err_attribute_wrong_number_arguments)
9339 << attr << 1;
9340 attr.setInvalid();
9341 return;
9342 }
9343
9344 StringRef HandleType;
9345 if (!state.getSema().checkStringLiteralArgumentAttr(Attr: attr, ArgNum: 0, Str&: HandleType))
9346 return;
9347 type = state.getAttributedType(
9348 A: AcquireHandleAttr::Create(Ctx&: state.getSema().Context, HandleType, CommonInfo: attr),
9349 ModifiedType: type, EquivType: type);
9350 attr.setUsedAsTypeAttr();
9351 break;
9352 }
9353 case ParsedAttr::AT_AnnotateType: {
9354 HandleAnnotateTypeAttr(State&: state, CurType&: type, PA: attr);
9355 attr.setUsedAsTypeAttr();
9356 break;
9357 }
9358 case ParsedAttr::AT_HLSLResourceClass:
9359 case ParsedAttr::AT_HLSLResourceDimension:
9360 case ParsedAttr::AT_HLSLROV:
9361 case ParsedAttr::AT_HLSLRawBuffer:
9362 case ParsedAttr::AT_HLSLIsArray:
9363 case ParsedAttr::AT_HLSLContainedType: {
9364 // Only collect HLSL resource type attributes that are in
9365 // decl-specifier-seq; do not collect attributes on declarations or those
9366 // that get to slide after declaration name.
9367 if (TAL == TAL_DeclSpec &&
9368 state.getSema().HLSL().handleResourceTypeAttr(T: type, AL: attr))
9369 attr.setUsedAsTypeAttr();
9370 break;
9371 }
9372 }
9373
9374 // Handle attributes that are defined in a macro. We do not want this to be
9375 // applied to ObjC builtin attributes.
9376 if (isa<AttributedType>(Val: type) && attr.hasMacroIdentifier() &&
9377 !type.getQualifiers().hasObjCLifetime() &&
9378 !type.getQualifiers().hasObjCGCAttr() &&
9379 attr.getKind() != ParsedAttr::AT_ObjCGC &&
9380 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
9381 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
9382 type = state.getSema().Context.getMacroQualifiedType(UnderlyingTy: type, MacroII);
9383 state.setExpansionLocForMacroQualifiedType(
9384 MQT: cast<MacroQualifiedType>(Val: type.getTypePtr()),
9385 Loc: attr.getMacroExpansionLoc());
9386 }
9387 }
9388}
9389
9390void Sema::completeExprArrayBound(Expr *E) {
9391 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
9392 if (VarDecl *Var = dyn_cast<VarDecl>(Val: DRE->getDecl())) {
9393 if (isTemplateInstantiation(Kind: Var->getTemplateSpecializationKind())) {
9394 auto *Def = Var->getDefinition();
9395 if (!Def) {
9396 SourceLocation PointOfInstantiation = E->getExprLoc();
9397 runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
9398 InstantiateVariableDefinition(PointOfInstantiation, Var);
9399 });
9400 Def = Var->getDefinition();
9401
9402 // If we don't already have a point of instantiation, and we managed
9403 // to instantiate a definition, this is the point of instantiation.
9404 // Otherwise, we don't request an end-of-TU instantiation, so this is
9405 // not a point of instantiation.
9406 // FIXME: Is this really the right behavior?
9407 if (Var->getPointOfInstantiation().isInvalid() && Def) {
9408 assert(Var->getTemplateSpecializationKind() ==
9409 TSK_ImplicitInstantiation &&
9410 "explicit instantiation with no point of instantiation");
9411 Var->setTemplateSpecializationKind(
9412 TSK: Var->getTemplateSpecializationKind(), PointOfInstantiation);
9413 }
9414 }
9415
9416 // Update the type to the definition's type both here and within the
9417 // expression.
9418 if (Def) {
9419 DRE->setDecl(Def);
9420 QualType T = Def->getType();
9421 DRE->setType(T);
9422 // FIXME: Update the type on all intervening expressions.
9423 E->setType(T);
9424 }
9425
9426 // We still go on to try to complete the type independently, as it
9427 // may also require instantiations or diagnostics if it remains
9428 // incomplete.
9429 }
9430 }
9431 }
9432 if (const auto CastE = dyn_cast<ExplicitCastExpr>(Val: E)) {
9433 QualType DestType = CastE->getTypeAsWritten();
9434 if (const auto *IAT = Context.getAsIncompleteArrayType(T: DestType)) {
9435 // C++20 [expr.static.cast]p.4: ... If T is array of unknown bound,
9436 // this direct-initialization defines the type of the expression
9437 // as U[1]
9438 QualType ResultType = Context.getConstantArrayType(
9439 EltTy: IAT->getElementType(),
9440 ArySize: llvm::APInt(Context.getTypeSize(T: Context.getSizeType()), 1),
9441 /*SizeExpr=*/nullptr, ASM: ArraySizeModifier::Normal,
9442 /*IndexTypeQuals=*/0);
9443 E->setType(ResultType);
9444 }
9445 }
9446}
9447
9448QualType Sema::getCompletedType(Expr *E) {
9449 // Incomplete array types may be completed by the initializer attached to
9450 // their definitions. For static data members of class templates and for
9451 // variable templates, we need to instantiate the definition to get this
9452 // initializer and complete the type.
9453 if (E->getType()->isIncompleteArrayType())
9454 completeExprArrayBound(E);
9455
9456 // FIXME: Are there other cases which require instantiating something other
9457 // than the type to complete the type of an expression?
9458
9459 return E->getType();
9460}
9461
9462bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
9463 TypeDiagnoser &Diagnoser) {
9464 return RequireCompleteType(Loc: E->getExprLoc(), T: getCompletedType(E), Kind,
9465 Diagnoser);
9466}
9467
9468bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9469 BoundTypeDiagnoser<> Diagnoser(DiagID);
9470 return RequireCompleteExprType(E, Kind: CompleteTypeKind::Default, Diagnoser);
9471}
9472
9473bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
9474 CompleteTypeKind Kind,
9475 TypeDiagnoser &Diagnoser) {
9476 if (RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser: &Diagnoser))
9477 return true;
9478 if (auto *TD = T->getAsTagDecl(); TD && !TD->isCompleteDefinitionRequired()) {
9479 TD->setCompleteDefinitionRequired();
9480 Consumer.HandleTagDeclRequiredDefinition(D: TD);
9481 }
9482 return false;
9483}
9484
9485bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
9486 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls;
9487 if (!Suggested)
9488 return false;
9489
9490 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9491 // and isolate from other C++ specific checks.
9492 StructuralEquivalenceContext Ctx(
9493 getLangOpts(), D->getASTContext(), Suggested->getASTContext(),
9494 NonEquivalentDecls, StructuralEquivalenceKind::Default,
9495 /*StrictTypeSpelling=*/false, /*Complain=*/true,
9496 /*ErrorOnTagTypeMismatch=*/true);
9497 return Ctx.IsEquivalent(D1: D, D2: Suggested);
9498}
9499
9500bool Sema::hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
9501 AcceptableKind Kind, bool OnlyNeedComplete) {
9502 // Easy case: if we don't have modules, all declarations are visible.
9503 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9504 return true;
9505
9506 // If this definition was instantiated from a template, map back to the
9507 // pattern from which it was instantiated.
9508 if (isa<TagDecl>(Val: D) && cast<TagDecl>(Val: D)->isBeingDefined())
9509 // We're in the middle of defining it; this definition should be treated
9510 // as visible.
9511 return true;
9512
9513 auto DefinitionIsAcceptable = [&](NamedDecl *D) {
9514 // The (primary) definition might be in a visible module.
9515 if (isAcceptable(D, Kind))
9516 return true;
9517
9518 // A visible module might have a merged definition instead.
9519 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(Def: D)
9520 : hasVisibleMergedDefinition(Def: D)) {
9521 if (CodeSynthesisContexts.empty() &&
9522 !getLangOpts().ModulesLocalVisibility) {
9523 // Cache the fact that this definition is implicitly visible because
9524 // there is a visible merged definition.
9525 D->setVisibleDespiteOwningModule();
9526 }
9527 return true;
9528 }
9529
9530 return false;
9531 };
9532 auto IsDefinition = [](NamedDecl *D) {
9533 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
9534 return RD->isThisDeclarationADefinition();
9535 if (auto *ED = dyn_cast<EnumDecl>(Val: D))
9536 return ED->isThisDeclarationADefinition();
9537 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
9538 return FD->isThisDeclarationADefinition();
9539 if (auto *VD = dyn_cast<VarDecl>(Val: D))
9540 return VD->isThisDeclarationADefinition() == VarDecl::Definition;
9541 llvm_unreachable("unexpected decl type");
9542 };
9543 auto FoundAcceptableDefinition = [&](NamedDecl *D) {
9544 if (!isa<CXXRecordDecl, FunctionDecl, EnumDecl, VarDecl>(Val: D))
9545 return DefinitionIsAcceptable(D);
9546
9547 // See ASTDeclReader::attachPreviousDeclImpl. Now we still
9548 // may demote definition to declaration for decls in haeder modules,
9549 // so avoid looking at its redeclaration to save time.
9550 // NOTE: If we don't demote definition to declarations for decls
9551 // in header modules, remove the condition.
9552 if (D->getOwningModule() && D->getOwningModule()->isHeaderLikeModule())
9553 return DefinitionIsAcceptable(D);
9554
9555 for (auto *RD : D->redecls()) {
9556 auto *ND = cast<NamedDecl>(Val: RD);
9557 if (!IsDefinition(ND))
9558 continue;
9559 if (DefinitionIsAcceptable(ND)) {
9560 *Suggested = ND;
9561 return true;
9562 }
9563 }
9564
9565 return false;
9566 };
9567
9568 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
9569 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9570 RD = Pattern;
9571 D = RD->getDefinition();
9572 } else if (auto *ED = dyn_cast<EnumDecl>(Val: D)) {
9573 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9574 ED = Pattern;
9575 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9576 // If the enum has a fixed underlying type, it may have been forward
9577 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9578 // the enum and assign it the underlying type of `int`. Since we're only
9579 // looking for a complete type (not a definition), any visible declaration
9580 // of it will do.
9581 *Suggested = nullptr;
9582 for (auto *Redecl : ED->redecls()) {
9583 if (isAcceptable(D: Redecl, Kind))
9584 return true;
9585 if (Redecl->isThisDeclarationADefinition() ||
9586 (Redecl->isCanonicalDecl() && !*Suggested))
9587 *Suggested = Redecl;
9588 }
9589
9590 return false;
9591 }
9592 D = ED->getDefinition();
9593 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
9594 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9595 FD = Pattern;
9596 D = FD->getDefinition();
9597 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
9598 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9599 VD = Pattern;
9600 D = VD->getDefinition();
9601 }
9602
9603 assert(D && "missing definition for pattern of instantiated definition");
9604
9605 *Suggested = D;
9606
9607 if (FoundAcceptableDefinition(D))
9608 return true;
9609
9610 // The external source may have additional definitions of this entity that are
9611 // visible, so complete the redeclaration chain now and ask again.
9612 if (auto *Source = Context.getExternalSource()) {
9613 Source->CompleteRedeclChain(D);
9614 return FoundAcceptableDefinition(D);
9615 }
9616
9617 return false;
9618}
9619
9620/// Determine whether there is any declaration of \p D that was ever a
9621/// definition (perhaps before module merging) and is currently visible.
9622/// \param D The definition of the entity.
9623/// \param Suggested Filled in with the declaration that should be made visible
9624/// in order to provide a definition of this entity.
9625/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9626/// not defined. This only matters for enums with a fixed underlying
9627/// type, since in all other cases, a type is complete if and only if it
9628/// is defined.
9629bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
9630 bool OnlyNeedComplete) {
9631 return hasAcceptableDefinition(D, Suggested, Kind: Sema::AcceptableKind::Visible,
9632 OnlyNeedComplete);
9633}
9634
9635/// Determine whether there is any declaration of \p D that was ever a
9636/// definition (perhaps before module merging) and is currently
9637/// reachable.
9638/// \param D The definition of the entity.
9639/// \param Suggested Filled in with the declaration that should be made
9640/// reachable
9641/// in order to provide a definition of this entity.
9642/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9643/// not defined. This only matters for enums with a fixed underlying
9644/// type, since in all other cases, a type is complete if and only if it
9645/// is defined.
9646bool Sema::hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
9647 bool OnlyNeedComplete) {
9648 return hasAcceptableDefinition(D, Suggested, Kind: Sema::AcceptableKind::Reachable,
9649 OnlyNeedComplete);
9650}
9651
9652/// Locks in the inheritance model for the given class and all of its bases.
9653static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
9654 RD = RD->getMostRecentDecl();
9655 if (!RD->hasAttr<MSInheritanceAttr>()) {
9656 MSInheritanceModel IM;
9657 bool BestCase = false;
9658 switch (S.MSPointerToMemberRepresentationMethod) {
9659 case LangOptions::PPTMK_BestCase:
9660 BestCase = true;
9661 IM = RD->calculateInheritanceModel();
9662 break;
9663 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
9664 IM = MSInheritanceModel::Single;
9665 break;
9666 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
9667 IM = MSInheritanceModel::Multiple;
9668 break;
9669 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
9670 IM = MSInheritanceModel::Unspecified;
9671 break;
9672 }
9673
9674 SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid()
9675 ? S.ImplicitMSInheritanceAttrLoc
9676 : RD->getSourceRange();
9677 RD->addAttr(A: MSInheritanceAttr::CreateImplicit(
9678 Ctx&: S.getASTContext(), BestCase, Range: Loc, S: MSInheritanceAttr::Spelling(IM)));
9679 S.Consumer.AssignInheritanceModel(RD);
9680 }
9681}
9682
9683bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9684 CompleteTypeKind Kind,
9685 TypeDiagnoser *Diagnoser) {
9686 // FIXME: Add this assertion to make sure we always get instantiation points.
9687 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9688 // FIXME: Add this assertion to help us flush out problems with
9689 // checking for dependent types and type-dependent expressions.
9690 //
9691 // assert(!T->isDependentType() &&
9692 // "Can't ask whether a dependent type is complete");
9693
9694 if (const auto *MPTy = dyn_cast<MemberPointerType>(Val: T.getCanonicalType())) {
9695 if (CXXRecordDecl *RD = MPTy->getMostRecentCXXRecordDecl();
9696 RD && !RD->isDependentType()) {
9697 CanQualType T = Context.getCanonicalTagType(TD: RD);
9698 if (getLangOpts().CompleteMemberPointers && !RD->isBeingDefined() &&
9699 RequireCompleteType(Loc, T, Kind, DiagID: diag::err_memptr_incomplete))
9700 return true;
9701
9702 // We lock in the inheritance model once somebody has asked us to ensure
9703 // that a pointer-to-member type is complete.
9704 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9705 (void)isCompleteType(Loc, T);
9706 assignInheritanceModel(S&: *this, RD: MPTy->getMostRecentCXXRecordDecl());
9707 }
9708 }
9709 }
9710
9711 NamedDecl *Def = nullptr;
9712 bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless);
9713 bool Incomplete = (T->isIncompleteType(Def: &Def) ||
9714 (!AcceptSizeless && T->isSizelessBuiltinType()));
9715
9716 // Check that any necessary explicit specializations are visible. For an
9717 // enum, we just need the declaration, so don't check this.
9718 if (Def && !isa<EnumDecl>(Val: Def))
9719 checkSpecializationReachability(Loc, Spec: Def);
9720
9721 // If we have a complete type, we're done.
9722 if (!Incomplete) {
9723 NamedDecl *Suggested = nullptr;
9724 if (Def &&
9725 !hasReachableDefinition(D: Def, Suggested: &Suggested, /*OnlyNeedComplete=*/true)) {
9726 // If the user is going to see an error here, recover by making the
9727 // definition visible.
9728 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9729 if (Diagnoser && Suggested)
9730 diagnoseMissingImport(Loc, Decl: Suggested, MIK: MissingImportKind::Definition,
9731 /*Recover*/ TreatAsComplete);
9732 return !TreatAsComplete;
9733 } else if (Def && !TemplateInstCallbacks.empty()) {
9734 CodeSynthesisContext TempInst;
9735 TempInst.Kind = CodeSynthesisContext::Memoization;
9736 TempInst.Template = Def;
9737 TempInst.Entity = Def;
9738 TempInst.PointOfInstantiation = Loc;
9739 atTemplateBegin(Callbacks&: TemplateInstCallbacks, TheSema: *this, Inst: TempInst);
9740 atTemplateEnd(Callbacks&: TemplateInstCallbacks, TheSema: *this, Inst: TempInst);
9741 }
9742
9743 return false;
9744 }
9745
9746 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: Def);
9747 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Val: Def);
9748
9749 // Give the external source a chance to provide a definition of the type.
9750 // This is kept separate from completing the redeclaration chain so that
9751 // external sources such as LLDB can avoid synthesizing a type definition
9752 // unless it's actually needed.
9753 if (Tag || IFace) {
9754 // Avoid diagnosing invalid decls as incomplete.
9755 if (Def->isInvalidDecl())
9756 return true;
9757
9758 // Give the external AST source a chance to complete the type.
9759 if (auto *Source = Context.getExternalSource()) {
9760 if (Tag && Tag->hasExternalLexicalStorage())
9761 Source->CompleteType(Tag);
9762 if (IFace && IFace->hasExternalLexicalStorage())
9763 Source->CompleteType(Class: IFace);
9764 // If the external source completed the type, go through the motions
9765 // again to ensure we're allowed to use the completed type.
9766 if (!T->isIncompleteType())
9767 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9768 }
9769 }
9770
9771 // If we have a class template specialization or a class member of a
9772 // class template specialization, or an array with known size of such,
9773 // try to instantiate it.
9774 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Val: Tag)) {
9775 bool Instantiated = false;
9776 bool Diagnosed = false;
9777 if (RD->isDependentContext()) {
9778 // Don't try to instantiate a dependent class (eg, a member template of
9779 // an instantiated class template specialization).
9780 // FIXME: Can this ever happen?
9781 } else if (auto *ClassTemplateSpec =
9782 dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) {
9783 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9784 runWithSufficientStackSpace(Loc, Fn: [&] {
9785 Diagnosed = InstantiateClassTemplateSpecialization(
9786 PointOfInstantiation: Loc, ClassTemplateSpec, TSK: TSK_ImplicitInstantiation,
9787 /*Complain=*/Diagnoser, PrimaryStrictPackMatch: ClassTemplateSpec->hasStrictPackMatch());
9788 });
9789 Instantiated = true;
9790 }
9791 } else {
9792 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9793 if (!RD->isBeingDefined() && Pattern) {
9794 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9795 assert(MSI && "Missing member specialization information?");
9796 // This record was instantiated from a class within a template.
9797 if (MSI->getTemplateSpecializationKind() !=
9798 TSK_ExplicitSpecialization) {
9799 runWithSufficientStackSpace(Loc, Fn: [&] {
9800 Diagnosed = InstantiateClass(PointOfInstantiation: Loc, Instantiation: RD, Pattern,
9801 TemplateArgs: getTemplateInstantiationArgs(D: RD),
9802 TSK: TSK_ImplicitInstantiation,
9803 /*Complain=*/Diagnoser);
9804 });
9805 Instantiated = true;
9806 }
9807 }
9808 }
9809
9810 if (Instantiated) {
9811 // Instantiate* might have already complained that the template is not
9812 // defined, if we asked it to.
9813 if (Diagnoser && Diagnosed)
9814 return true;
9815 // If we instantiated a definition, check that it's usable, even if
9816 // instantiation produced an error, so that repeated calls to this
9817 // function give consistent answers.
9818 if (!T->isIncompleteType())
9819 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9820 }
9821 }
9822
9823 // FIXME: If we didn't instantiate a definition because of an explicit
9824 // specialization declaration, check that it's visible.
9825
9826 if (!Diagnoser)
9827 return true;
9828
9829 Diagnoser->diagnose(S&: *this, Loc, T);
9830
9831 // If the type was a forward declaration of a class/struct/union
9832 // type, produce a note.
9833 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9834 Diag(Loc: Tag->getLocation(), DiagID: Tag->isBeingDefined()
9835 ? diag::note_type_being_defined
9836 : diag::note_forward_declaration)
9837 << Context.getCanonicalTagType(TD: Tag);
9838
9839 // If the Objective-C class was a forward declaration, produce a note.
9840 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9841 Diag(Loc: IFace->getLocation(), DiagID: diag::note_forward_class);
9842
9843 // If we have external information that we can use to suggest a fix,
9844 // produce a note.
9845 if (ExternalSource)
9846 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9847
9848 return true;
9849}
9850
9851bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
9852 CompleteTypeKind Kind, unsigned DiagID) {
9853 BoundTypeDiagnoser<> Diagnoser(DiagID);
9854 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9855}
9856
9857/// Get diagnostic %select index for tag kind for
9858/// literal type diagnostic message.
9859/// WARNING: Indexes apply to particular diagnostics only!
9860///
9861/// \returns diagnostic %select index.
9862static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
9863 switch (Tag) {
9864 case TagTypeKind::Struct:
9865 return 0;
9866 case TagTypeKind::Interface:
9867 return 1;
9868 case TagTypeKind::Class:
9869 return 2;
9870 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9871 }
9872}
9873
9874bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
9875 TypeDiagnoser &Diagnoser) {
9876 assert(!T->isDependentType() && "type should not be dependent");
9877
9878 QualType ElemType = Context.getBaseElementType(QT: T);
9879 if ((isCompleteType(Loc, T: ElemType) || ElemType->isVoidType()) &&
9880 T->isLiteralType(Ctx: Context))
9881 return false;
9882
9883 Diagnoser.diagnose(S&: *this, Loc, T);
9884
9885 if (T->isVariableArrayType())
9886 return true;
9887
9888 if (!ElemType->isRecordType())
9889 return true;
9890
9891 // A partially-defined class type can't be a literal type, because a literal
9892 // class type must have a trivial destructor (which can't be checked until
9893 // the class definition is complete).
9894 if (RequireCompleteType(Loc, T: ElemType, DiagID: diag::note_non_literal_incomplete, Args: T))
9895 return true;
9896
9897 const auto *RD = ElemType->castAsCXXRecordDecl();
9898 // [expr.prim.lambda]p3:
9899 // This class type is [not] a literal type.
9900 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9901 Diag(Loc: RD->getLocation(), DiagID: diag::note_non_literal_lambda);
9902 return true;
9903 }
9904
9905 // If the class has virtual base classes, then it's not an aggregate, and
9906 // cannot have any constexpr constructors or a trivial default constructor,
9907 // so is non-literal. This is better to diagnose than the resulting absence
9908 // of constexpr constructors.
9909 if (RD->getNumVBases()) {
9910 Diag(Loc: RD->getLocation(), DiagID: diag::note_non_literal_virtual_base)
9911 << getLiteralDiagFromTagKind(Tag: RD->getTagKind()) << RD->getNumVBases();
9912 for (const auto &I : RD->vbases())
9913 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here)
9914 << I.getSourceRange();
9915 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9916 !RD->hasTrivialDefaultConstructor()) {
9917 Diag(Loc: RD->getLocation(), DiagID: diag::note_non_literal_no_constexpr_ctors) << RD;
9918 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9919 for (const auto &I : RD->bases()) {
9920 if (!I.getType()->isLiteralType(Ctx: Context)) {
9921 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_non_literal_base_class)
9922 << RD << I.getType() << I.getSourceRange();
9923 return true;
9924 }
9925 }
9926 for (const auto *I : RD->fields()) {
9927 if (!I->getType()->isLiteralType(Ctx: Context) ||
9928 I->getType().isVolatileQualified()) {
9929 Diag(Loc: I->getLocation(), DiagID: diag::note_non_literal_field)
9930 << RD << I << I->getType()
9931 << I->getType().isVolatileQualified();
9932 return true;
9933 }
9934 }
9935 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
9936 : !RD->hasTrivialDestructor()) {
9937 // All fields and bases are of literal types, so have trivial or constexpr
9938 // destructors. If this class's destructor is non-trivial / non-constexpr,
9939 // it must be user-declared.
9940 CXXDestructorDecl *Dtor = RD->getDestructor();
9941 assert(Dtor && "class has literal fields and bases but no dtor?");
9942 if (!Dtor)
9943 return true;
9944
9945 if (getLangOpts().CPlusPlus20) {
9946 Diag(Loc: Dtor->getLocation(), DiagID: diag::note_non_literal_non_constexpr_dtor)
9947 << RD;
9948 } else {
9949 Diag(Loc: Dtor->getLocation(), DiagID: Dtor->isUserProvided()
9950 ? diag::note_non_literal_user_provided_dtor
9951 : diag::note_non_literal_nontrivial_dtor)
9952 << RD;
9953 if (!Dtor->isUserProvided())
9954 SpecialMemberIsTrivial(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor,
9955 TAH: TrivialABIHandling::IgnoreTrivialABI,
9956 /*Diagnose*/ true);
9957 }
9958 }
9959
9960 return true;
9961}
9962
9963bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
9964 BoundTypeDiagnoser<> Diagnoser(DiagID);
9965 return RequireLiteralType(Loc, T, Diagnoser);
9966}
9967
9968QualType Sema::BuildTypeofExprType(Expr *E, TypeOfKind Kind) {
9969 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9970
9971 if (!getLangOpts().CPlusPlus && E->refersToBitField())
9972 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield)
9973 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
9974
9975 if (!E->isTypeDependent()) {
9976 QualType T = E->getType();
9977 if (const TagType *TT = T->getAs<TagType>())
9978 DiagnoseUseOfDecl(D: TT->getDecl(), Locs: E->getExprLoc());
9979 }
9980 return Context.getTypeOfExprType(E, Kind);
9981}
9982
9983static void
9984BuildTypeCoupledDecls(Expr *E,
9985 llvm::SmallVectorImpl<TypeCoupledDeclRefInfo> &Decls) {
9986 // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl.
9987 auto *CountDecl = cast<DeclRefExpr>(Val: E)->getDecl();
9988 Decls.push_back(Elt: TypeCoupledDeclRefInfo(CountDecl, /*IsDref*/ false));
9989}
9990
9991QualType Sema::BuildCountAttributedArrayOrPointerType(QualType WrappedTy,
9992 Expr *CountExpr,
9993 bool CountInBytes,
9994 bool OrNull) {
9995 assert(WrappedTy->isIncompleteArrayType() || WrappedTy->isPointerType());
9996
9997 llvm::SmallVector<TypeCoupledDeclRefInfo, 1> Decls;
9998 BuildTypeCoupledDecls(E: CountExpr, Decls);
9999 /// When the resulting expression is invalid, we still create the AST using
10000 /// the original count expression for the sake of AST dump.
10001 return Context.getCountAttributedType(T: WrappedTy, CountExpr, CountInBytes,
10002 OrNull, DependentDecls: Decls);
10003}
10004
10005/// getDecltypeForExpr - Given an expr, will return the decltype for
10006/// that expression, according to the rules in C++11
10007/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
10008QualType Sema::getDecltypeForExpr(Expr *E) {
10009
10010 Expr *IDExpr = E;
10011 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(Val: E))
10012 IDExpr = ImplCastExpr->getSubExpr();
10013
10014 if (auto *PackExpr = dyn_cast<PackIndexingExpr>(Val: E)) {
10015 if (E->isInstantiationDependent())
10016 IDExpr = PackExpr->getPackIdExpression();
10017 else
10018 IDExpr = PackExpr->getSelectedExpr();
10019 }
10020
10021 if (E->isTypeDependent())
10022 return Context.DependentTy;
10023
10024 // C++11 [dcl.type.simple]p4:
10025 // The type denoted by decltype(e) is defined as follows:
10026
10027 // C++20:
10028 // - if E is an unparenthesized id-expression naming a non-type
10029 // template-parameter (13.2), decltype(E) is the type of the
10030 // template-parameter after performing any necessary type deduction
10031 // Note that this does not pick up the implicit 'const' for a template
10032 // parameter object. This rule makes no difference before C++20 so we apply
10033 // it unconditionally.
10034 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(Val: IDExpr))
10035 IDExpr = SNTTPE->getReplacement();
10036
10037 // - if e is an unparenthesized id-expression or an unparenthesized class
10038 // member access (5.2.5), decltype(e) is the type of the entity named
10039 // by e. If there is no such entity, or if e names a set of overloaded
10040 // functions, the program is ill-formed;
10041 //
10042 // We apply the same rules for Objective-C ivar and property references.
10043 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: IDExpr)) {
10044 const ValueDecl *VD = DRE->getDecl();
10045 QualType T = VD->getType();
10046 return isa<TemplateParamObjectDecl>(Val: VD) ? T.getUnqualifiedType() : T;
10047 }
10048 if (const auto *ME = dyn_cast<MemberExpr>(Val: IDExpr)) {
10049 if (const auto *VD = ME->getMemberDecl())
10050 if (isa<FieldDecl>(Val: VD) || isa<VarDecl>(Val: VD))
10051 return VD->getType();
10052 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(Val: IDExpr)) {
10053 return IR->getDecl()->getType();
10054 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(Val: IDExpr)) {
10055 if (PR->isExplicitProperty())
10056 return PR->getExplicitProperty()->getType();
10057 } else if (const auto *PE = dyn_cast<PredefinedExpr>(Val: IDExpr)) {
10058 return PE->getType();
10059 }
10060
10061 // C++11 [expr.lambda.prim]p18:
10062 // Every occurrence of decltype((x)) where x is a possibly
10063 // parenthesized id-expression that names an entity of automatic
10064 // storage duration is treated as if x were transformed into an
10065 // access to a corresponding data member of the closure type that
10066 // would have been declared if x were an odr-use of the denoted
10067 // entity.
10068 if (getCurLambda() && isa<ParenExpr>(Val: IDExpr)) {
10069 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: IDExpr->IgnoreParens())) {
10070 if (auto *Var = dyn_cast<VarDecl>(Val: DRE->getDecl())) {
10071 QualType T = getCapturedDeclRefType(Var, Loc: DRE->getLocation());
10072 if (!T.isNull())
10073 return Context.getLValueReferenceType(T);
10074 }
10075 }
10076 }
10077
10078 return Context.getReferenceQualifiedType(e: E);
10079}
10080
10081QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
10082 assert(!E->hasPlaceholderType() && "unexpected placeholder");
10083
10084 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
10085 !E->isInstantiationDependent() && E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false)) {
10086 // The expression operand for decltype is in an unevaluated expression
10087 // context, so side effects could result in unintended consequences.
10088 // Exclude instantiation-dependent expressions, because 'decltype' is often
10089 // used to build SFINAE gadgets.
10090 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
10091 }
10092 return Context.getDecltypeType(e: E, UnderlyingType: getDecltypeForExpr(E));
10093}
10094
10095QualType Sema::ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
10096 SourceLocation Loc,
10097 SourceLocation EllipsisLoc) {
10098 if (!IndexExpr)
10099 return QualType();
10100
10101 // Diagnose unexpanded packs but continue to improve recovery.
10102 if (!Pattern->containsUnexpandedParameterPack())
10103 Diag(Loc, DiagID: diag::err_expected_name_of_pack) << Pattern;
10104
10105 QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc, EllipsisLoc);
10106
10107 if (!Type.isNull())
10108 Diag(Loc, DiagID: getLangOpts().CPlusPlus26 ? diag::warn_cxx23_pack_indexing
10109 : diag::ext_pack_indexing);
10110 return Type;
10111}
10112
10113QualType Sema::BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
10114 SourceLocation Loc,
10115 SourceLocation EllipsisLoc,
10116 bool FullySubstituted,
10117 ArrayRef<QualType> Expansions) {
10118
10119 UnsignedOrNone Index = std::nullopt;
10120 if (!IndexExpr->isInstantiationDependent()) {
10121 llvm::APSInt Value;
10122 ExprResult Res = CheckConvertedConstantExpression(
10123 From: IndexExpr, T: Context.getSizeType(), Value, CCE: CCEKind::PackIndex);
10124
10125 if (!Res.isUsable() || !Value.isRepresentableByInt64())
10126 return QualType();
10127
10128 IndexExpr = Res.get();
10129 uint64_t V = Value.getZExtValue();
10130 if (FullySubstituted && (V < 0 || V >= Expansions.size())) {
10131 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_pack_index_out_of_bound)
10132 << V << Pattern << Expansions.size();
10133 return QualType();
10134 }
10135 Index = static_cast<unsigned>(V);
10136 }
10137
10138 return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted,
10139 Expansions, Index);
10140}
10141
10142static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType,
10143 SourceLocation Loc) {
10144 assert(BaseType->isEnumeralType());
10145 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
10146
10147 S.DiagnoseUseOfDecl(D: ED, Locs: Loc);
10148
10149 QualType Underlying = ED->getIntegerType();
10150 if (Underlying.isNull()) {
10151 Underlying = ED->getDefinition()->getIntegerType();
10152 assert(!Underlying.isNull());
10153 }
10154
10155 return Underlying;
10156}
10157
10158QualType Sema::BuiltinEnumUnderlyingType(QualType BaseType,
10159 SourceLocation Loc) {
10160 if (!BaseType->isEnumeralType()) {
10161 Diag(Loc, DiagID: diag::err_only_enums_have_underlying_types);
10162 return QualType();
10163 }
10164
10165 // The enum could be incomplete if we're parsing its definition or
10166 // recovering from an error.
10167 NamedDecl *FwdDecl = nullptr;
10168 if (BaseType->isIncompleteType(Def: &FwdDecl)) {
10169 Diag(Loc, DiagID: diag::err_underlying_type_of_incomplete_enum) << BaseType;
10170 Diag(Loc: FwdDecl->getLocation(), DiagID: diag::note_forward_declaration) << FwdDecl;
10171 return QualType();
10172 }
10173
10174 return GetEnumUnderlyingType(S&: *this, BaseType, Loc);
10175}
10176
10177QualType Sema::BuiltinAddPointer(QualType BaseType, SourceLocation Loc) {
10178 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
10179 ? BuildPointerType(T: BaseType.getNonReferenceType(), Loc,
10180 Entity: DeclarationName())
10181 : BaseType;
10182
10183 return Pointer.isNull() ? QualType() : Pointer;
10184}
10185
10186QualType Sema::BuiltinRemovePointer(QualType BaseType, SourceLocation Loc) {
10187 if (!BaseType->isAnyPointerType())
10188 return BaseType;
10189
10190 return BaseType->getPointeeType();
10191}
10192
10193QualType Sema::BuiltinDecay(QualType BaseType, SourceLocation Loc) {
10194 QualType Underlying = BaseType.getNonReferenceType();
10195 if (Underlying->isArrayType())
10196 return Context.getDecayedType(T: Underlying);
10197
10198 if (Underlying->isFunctionType())
10199 return BuiltinAddPointer(BaseType, Loc);
10200
10201 SplitQualType Split = Underlying.getSplitUnqualifiedType();
10202 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
10203 // in the same group of qualifiers as 'const' and 'volatile', we're extending
10204 // '__decay(T)' so that it removes all qualifiers.
10205 Split.Quals.removeCVRQualifiers();
10206 return Context.getQualifiedType(split: Split);
10207}
10208
10209QualType Sema::BuiltinAddReference(QualType BaseType, UTTKind UKind,
10210 SourceLocation Loc) {
10211 assert(LangOpts.CPlusPlus);
10212 QualType Reference =
10213 BaseType.isReferenceable()
10214 ? BuildReferenceType(T: BaseType,
10215 SpelledAsLValue: UKind == UnaryTransformType::AddLvalueReference,
10216 Loc, Entity: DeclarationName())
10217 : BaseType;
10218 return Reference.isNull() ? QualType() : Reference;
10219}
10220
10221QualType Sema::BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
10222 SourceLocation Loc) {
10223 if (UKind == UnaryTransformType::RemoveAllExtents)
10224 return Context.getBaseElementType(QT: BaseType);
10225
10226 if (const auto *AT = Context.getAsArrayType(T: BaseType))
10227 return AT->getElementType();
10228
10229 return BaseType;
10230}
10231
10232QualType Sema::BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
10233 SourceLocation Loc) {
10234 assert(LangOpts.CPlusPlus);
10235 QualType T = BaseType.getNonReferenceType();
10236 if (UKind == UTTKind::RemoveCVRef &&
10237 (T.isConstQualified() || T.isVolatileQualified())) {
10238 Qualifiers Quals;
10239 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
10240 Quals.removeConst();
10241 Quals.removeVolatile();
10242 T = Context.getQualifiedType(T: Unqual, Qs: Quals);
10243 }
10244 return T;
10245}
10246
10247QualType Sema::BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
10248 SourceLocation Loc) {
10249 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
10250 BaseType->isFunctionType())
10251 return BaseType;
10252
10253 Qualifiers Quals;
10254 QualType Unqual = Context.getUnqualifiedArrayType(T: BaseType, Quals);
10255
10256 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
10257 Quals.removeConst();
10258 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
10259 Quals.removeVolatile();
10260 if (UKind == UTTKind::RemoveRestrict)
10261 Quals.removeRestrict();
10262
10263 return Context.getQualifiedType(T: Unqual, Qs: Quals);
10264}
10265
10266static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType,
10267 bool IsMakeSigned,
10268 SourceLocation Loc) {
10269 if (BaseType->isEnumeralType()) {
10270 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
10271 if (auto *BitInt = dyn_cast<BitIntType>(Val&: Underlying)) {
10272 unsigned int Bits = BitInt->getNumBits();
10273 if (Bits > 1)
10274 return S.Context.getBitIntType(Unsigned: !IsMakeSigned, NumBits: Bits);
10275
10276 S.Diag(Loc, DiagID: diag::err_make_signed_integral_only)
10277 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
10278 return QualType();
10279 }
10280 if (Underlying->isBooleanType()) {
10281 S.Diag(Loc, DiagID: diag::err_make_signed_integral_only)
10282 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
10283 << Underlying;
10284 return QualType();
10285 }
10286 }
10287
10288 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
10289 std::array<CanQualType *, 6> AllSignedIntegers = {
10290 &S.Context.SignedCharTy, &S.Context.ShortTy, &S.Context.IntTy,
10291 &S.Context.LongTy, &S.Context.LongLongTy, &S.Context.Int128Ty};
10292 ArrayRef<CanQualType *> AvailableSignedIntegers(
10293 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
10294 std::array<CanQualType *, 6> AllUnsignedIntegers = {
10295 &S.Context.UnsignedCharTy, &S.Context.UnsignedShortTy,
10296 &S.Context.UnsignedIntTy, &S.Context.UnsignedLongTy,
10297 &S.Context.UnsignedLongLongTy, &S.Context.UnsignedInt128Ty};
10298 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
10299 AllUnsignedIntegers.size() -
10300 Int128Unsupported);
10301 ArrayRef<CanQualType *> *Consider =
10302 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
10303
10304 uint64_t BaseSize = S.Context.getTypeSize(T: BaseType);
10305 auto *Result =
10306 llvm::find_if(Range&: *Consider, P: [&S, BaseSize](const CanQual<Type> *T) {
10307 return BaseSize == S.Context.getTypeSize(T: T->getTypePtr());
10308 });
10309
10310 assert(Result != Consider->end());
10311 return QualType((*Result)->getTypePtr(), 0);
10312}
10313
10314QualType Sema::BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
10315 SourceLocation Loc) {
10316 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
10317 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
10318 BaseType->isBooleanType() ||
10319 (BaseType->isBitIntType() &&
10320 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
10321 Diag(Loc, DiagID: diag::err_make_signed_integral_only)
10322 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
10323 return QualType();
10324 }
10325
10326 bool IsNonIntIntegral =
10327 BaseType->isChar16Type() || BaseType->isChar32Type() ||
10328 BaseType->isWideCharType() || BaseType->isEnumeralType();
10329
10330 QualType Underlying =
10331 IsNonIntIntegral
10332 ? ChangeIntegralSignedness(S&: *this, BaseType, IsMakeSigned, Loc)
10333 : IsMakeSigned ? Context.getCorrespondingSignedType(T: BaseType)
10334 : Context.getCorrespondingUnsignedType(T: BaseType);
10335 if (Underlying.isNull())
10336 return Underlying;
10337 return Context.getQualifiedType(T: Underlying, Qs: BaseType.getQualifiers());
10338}
10339
10340QualType Sema::BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
10341 SourceLocation Loc) {
10342 if (BaseType->isDependentType())
10343 return Context.getUnaryTransformType(BaseType, UnderlyingType: BaseType, UKind);
10344 QualType Result;
10345 switch (UKind) {
10346 case UnaryTransformType::EnumUnderlyingType: {
10347 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
10348 break;
10349 }
10350 case UnaryTransformType::AddPointer: {
10351 Result = BuiltinAddPointer(BaseType, Loc);
10352 break;
10353 }
10354 case UnaryTransformType::RemovePointer: {
10355 Result = BuiltinRemovePointer(BaseType, Loc);
10356 break;
10357 }
10358 case UnaryTransformType::Decay: {
10359 Result = BuiltinDecay(BaseType, Loc);
10360 break;
10361 }
10362 case UnaryTransformType::AddLvalueReference:
10363 case UnaryTransformType::AddRvalueReference: {
10364 Result = BuiltinAddReference(BaseType, UKind, Loc);
10365 break;
10366 }
10367 case UnaryTransformType::RemoveAllExtents:
10368 case UnaryTransformType::RemoveExtent: {
10369 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
10370 break;
10371 }
10372 case UnaryTransformType::RemoveCVRef:
10373 case UnaryTransformType::RemoveReference: {
10374 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
10375 break;
10376 }
10377 case UnaryTransformType::RemoveConst:
10378 case UnaryTransformType::RemoveCV:
10379 case UnaryTransformType::RemoveRestrict:
10380 case UnaryTransformType::RemoveVolatile: {
10381 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
10382 break;
10383 }
10384 case UnaryTransformType::MakeSigned:
10385 case UnaryTransformType::MakeUnsigned: {
10386 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
10387 break;
10388 }
10389 }
10390
10391 return !Result.isNull()
10392 ? Context.getUnaryTransformType(BaseType, UnderlyingType: Result, UKind)
10393 : Result;
10394}
10395
10396QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
10397 if (!isDependentOrGNUAutoType(T)) {
10398 // FIXME: It isn't entirely clear whether incomplete atomic types
10399 // are allowed or not; for simplicity, ban them for the moment.
10400 if (RequireCompleteType(Loc, T, DiagID: diag::err_atomic_specifier_bad_type, Args: 0))
10401 return QualType();
10402
10403 int DisallowedKind = -1;
10404 if (T->isArrayType())
10405 DisallowedKind = 1;
10406 else if (T->isFunctionType())
10407 DisallowedKind = 2;
10408 else if (T->isReferenceType())
10409 DisallowedKind = 3;
10410 else if (T->isAtomicType())
10411 DisallowedKind = 4;
10412 else if (T.hasQualifiers())
10413 DisallowedKind = 5;
10414 else if (T->isSizelessType())
10415 DisallowedKind = 6;
10416 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus)
10417 // Some other non-trivially-copyable type (probably a C++ class)
10418 DisallowedKind = 7;
10419 else if (T->isBitIntType())
10420 DisallowedKind = 8;
10421 else if (getLangOpts().C23 && T->isUndeducedAutoType())
10422 // _Atomic auto is prohibited in C23
10423 DisallowedKind = 9;
10424
10425 if (DisallowedKind != -1) {
10426 Diag(Loc, DiagID: diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
10427 return QualType();
10428 }
10429
10430 // FIXME: Do we need any handling for ARC here?
10431 }
10432
10433 // Build the pointer type.
10434 return Context.getAtomicType(T);
10435}
10436