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