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

Provided by KDAB

Privacy Policy
Learn to use CMake with our Intro Training
Find out more

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