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