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