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