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