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