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