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