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