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