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

source code of clang/lib/Sema/SemaType.cpp