clang 23.0.0git
SemaType.cpp
Go to the documentation of this file.
1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements type-related semantic analysis.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprObjC.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLoc.h"
33#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Lookup.h"
39#include "clang/Sema/SemaCUDA.h"
40#include "clang/Sema/SemaHLSL.h"
41#include "clang/Sema/SemaObjC.h"
43#include "clang/Sema/Template.h"
45#include "llvm/ADT/ArrayRef.h"
46#include "llvm/ADT/STLForwardCompat.h"
47#include "llvm/ADT/StringExtras.h"
48#include "llvm/IR/DerivedTypes.h"
49#include "llvm/Support/ErrorHandling.h"
50#include <bitset>
51#include <optional>
52
53using namespace clang;
54
60
61/// isOmittedBlockReturnType - Return true if this declarator is missing a
62/// return type because this is a omitted return type on a block literal.
63static bool isOmittedBlockReturnType(const Declarator &D) {
66 return false;
67
68 if (D.getNumTypeObjects() == 0)
69 return true; // ^{ ... }
70
71 if (D.getNumTypeObjects() == 1 &&
73 return true; // ^(int X, float Y) { ... }
74
75 return false;
76}
77
78/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
79/// doesn't apply to the given type.
81 QualType type) {
82 TypeDiagSelector WhichType;
83 bool useExpansionLoc = true;
84 switch (attr.getKind()) {
85 case ParsedAttr::AT_ObjCGC:
86 WhichType = TDS_Pointer;
87 break;
88 case ParsedAttr::AT_ObjCOwnership:
89 WhichType = TDS_ObjCObjOrBlock;
90 break;
91 default:
92 // Assume everything else was a function attribute.
93 WhichType = TDS_Function;
94 useExpansionLoc = false;
95 break;
96 }
97
98 SourceLocation loc = attr.getLoc();
99 StringRef name = attr.getAttrName()->getName();
100
101 // The GC attributes are usually written with macros; special-case them.
102 IdentifierInfo *II =
103 attr.isArgIdent(0) ? attr.getArgAsIdent(0)->getIdentifierInfo() : nullptr;
104 if (useExpansionLoc && loc.isMacroID() && II) {
105 if (II->isStr("strong")) {
106 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
107 } else if (II->isStr("weak")) {
108 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
109 }
110 }
111
112 S.Diag(loc, attr.isRegularKeywordAttribute()
113 ? diag::err_type_attribute_wrong_type
114 : diag::warn_type_attribute_wrong_type)
115 << name << WhichType << type;
116}
117
118// objc_gc applies to Objective-C pointers or, otherwise, to the
119// smallest available pointer type (i.e. 'void*' in 'void**').
120#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
121 case ParsedAttr::AT_ObjCGC: \
122 case ParsedAttr::AT_ObjCOwnership
123
124// Calling convention attributes.
125#define CALLING_CONV_ATTRS_CASELIST \
126 case ParsedAttr::AT_CDecl: \
127 case ParsedAttr::AT_FastCall: \
128 case ParsedAttr::AT_StdCall: \
129 case ParsedAttr::AT_ThisCall: \
130 case ParsedAttr::AT_RegCall: \
131 case ParsedAttr::AT_Pascal: \
132 case ParsedAttr::AT_SwiftCall: \
133 case ParsedAttr::AT_SwiftAsyncCall: \
134 case ParsedAttr::AT_VectorCall: \
135 case ParsedAttr::AT_AArch64VectorPcs: \
136 case ParsedAttr::AT_AArch64SVEPcs: \
137 case ParsedAttr::AT_MSABI: \
138 case ParsedAttr::AT_SysVABI: \
139 case ParsedAttr::AT_Pcs: \
140 case ParsedAttr::AT_IntelOclBicc: \
141 case ParsedAttr::AT_PreserveMost: \
142 case ParsedAttr::AT_PreserveAll: \
143 case ParsedAttr::AT_M68kRTD: \
144 case ParsedAttr::AT_PreserveNone: \
145 case ParsedAttr::AT_RISCVVectorCC: \
146 case ParsedAttr::AT_RISCVVLSCC
147
148// Function type attributes.
149#define FUNCTION_TYPE_ATTRS_CASELIST \
150 case ParsedAttr::AT_NSReturnsRetained: \
151 case ParsedAttr::AT_NoReturn: \
152 case ParsedAttr::AT_NonBlocking: \
153 case ParsedAttr::AT_NonAllocating: \
154 case ParsedAttr::AT_Blocking: \
155 case ParsedAttr::AT_Allocating: \
156 case ParsedAttr::AT_Regparm: \
157 case ParsedAttr::AT_CFIUncheckedCallee: \
158 case ParsedAttr::AT_CFISalt: \
159 case ParsedAttr::AT_CmseNSCall: \
160 case ParsedAttr::AT_ArmStreaming: \
161 case ParsedAttr::AT_ArmStreamingCompatible: \
162 case ParsedAttr::AT_ArmPreserves: \
163 case ParsedAttr::AT_ArmIn: \
164 case ParsedAttr::AT_ArmOut: \
165 case ParsedAttr::AT_ArmInOut: \
166 case ParsedAttr::AT_ArmAgnostic: \
167 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
168 case ParsedAttr::AT_AnyX86NoCfCheck: \
169 CALLING_CONV_ATTRS_CASELIST
170
171// Microsoft-specific type qualifiers.
172#define MS_TYPE_ATTRS_CASELIST \
173 case ParsedAttr::AT_Ptr32: \
174 case ParsedAttr::AT_Ptr64: \
175 case ParsedAttr::AT_SPtr: \
176 case ParsedAttr::AT_UPtr
177
178// Nullability qualifiers.
179#define NULLABILITY_TYPE_ATTRS_CASELIST \
180 case ParsedAttr::AT_TypeNonNull: \
181 case ParsedAttr::AT_TypeNullable: \
182 case ParsedAttr::AT_TypeNullableResult: \
183 case ParsedAttr::AT_TypeNullUnspecified
184
185namespace {
186 /// An object which stores processing state for the entire
187 /// GetTypeForDeclarator process.
188 class TypeProcessingState {
189 Sema &sema;
190
191 /// The declarator being processed.
192 Declarator &declarator;
193
194 /// The index of the declarator chunk we're currently processing.
195 /// May be the total number of valid chunks, indicating the
196 /// DeclSpec.
197 unsigned chunkIndex;
198
199 /// The original set of attributes on the DeclSpec.
201
202 /// A list of attributes to diagnose the uselessness of when the
203 /// processing is complete.
204 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
205
206 /// Attributes corresponding to AttributedTypeLocs that we have not yet
207 /// populated.
208 // FIXME: The two-phase mechanism by which we construct Types and fill
209 // their TypeLocs makes it hard to correctly assign these. We keep the
210 // attributes in creation order as an attempt to make them line up
211 // properly.
212 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
213 SmallVector<TypeAttrPair, 8> AttrsForTypes;
214 bool AttrsForTypesSorted = true;
215
216 /// MacroQualifiedTypes mapping to macro expansion locations that will be
217 /// stored in a MacroQualifiedTypeLoc.
218 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
219
220 /// Flag to indicate we parsed a noderef attribute. This is used for
221 /// validating that noderef was used on a pointer or array.
222 bool parsedNoDeref;
223
224 // Flag to indicate that we already parsed a HLSL parameter modifier
225 // attribute. This prevents double-mutating the type.
226 bool ParsedHLSLParamMod;
227
228 public:
229 TypeProcessingState(Sema &sema, Declarator &declarator)
230 : sema(sema), declarator(declarator),
231 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false),
232 ParsedHLSLParamMod(false) {}
233
234 Sema &getSema() const {
235 return sema;
236 }
237
238 Declarator &getDeclarator() const {
239 return declarator;
240 }
241
242 bool isProcessingDeclSpec() const {
243 return chunkIndex == declarator.getNumTypeObjects();
244 }
245
246 unsigned getCurrentChunkIndex() const {
247 return chunkIndex;
248 }
249
250 void setCurrentChunkIndex(unsigned idx) {
251 assert(idx <= declarator.getNumTypeObjects());
252 chunkIndex = idx;
253 }
254
255 ParsedAttributesView &getCurrentAttributes() const {
256 if (isProcessingDeclSpec())
257 return getMutableDeclSpec().getAttributes();
258 return declarator.getTypeObject(chunkIndex).getAttrs();
259 }
260
261 /// Save the current set of attributes on the DeclSpec.
262 void saveDeclSpecAttrs() {
263 // Don't try to save them multiple times.
264 if (!savedAttrs.empty())
265 return;
266
267 DeclSpec &spec = getMutableDeclSpec();
268 llvm::append_range(savedAttrs,
269 llvm::make_pointer_range(spec.getAttributes()));
270 }
271
272 /// Record that we had nowhere to put the given type attribute.
273 /// We will diagnose such attributes later.
274 void addIgnoredTypeAttr(ParsedAttr &attr) {
275 ignoredTypeAttrs.push_back(&attr);
276 }
277
278 /// Diagnose all the ignored type attributes, given that the
279 /// declarator worked out to the given type.
280 void diagnoseIgnoredTypeAttrs(QualType type) const {
281 for (auto *Attr : ignoredTypeAttrs)
282 diagnoseBadTypeAttribute(getSema(), *Attr, type);
283 }
284
285 /// Get an attributed type for the given attribute, and remember the Attr
286 /// object so that we can attach it to the AttributedTypeLoc.
287 QualType getAttributedType(Attr *A, QualType ModifiedType,
288 QualType EquivType) {
289 QualType T =
290 sema.Context.getAttributedType(A, ModifiedType, EquivType);
291 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
292 AttrsForTypesSorted = false;
293 return T;
294 }
295
296 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
297 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
298 QualType WrappedType) {
299 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
300 }
301
302 /// Get a OverflowBehaviorType type for the overflow_behavior type
303 /// attribute.
305 getOverflowBehaviorType(OverflowBehaviorType::OverflowBehaviorKind Kind,
306 QualType UnderlyingType) {
307 return sema.Context.getOverflowBehaviorType(Kind, UnderlyingType);
308 }
309
310 /// Completely replace the \c auto in \p TypeWithAuto by
311 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
312 /// necessary.
313 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
314 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
315 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
316 // Attributed type still should be an attributed type after replacement.
317 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
318 for (TypeAttrPair &A : AttrsForTypes) {
319 if (A.first == AttrTy)
320 A.first = NewAttrTy;
321 }
322 AttrsForTypesSorted = false;
323 }
324 return T;
325 }
326
327 /// Extract and remove the Attr* for a given attributed type.
328 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
329 if (!AttrsForTypesSorted) {
330 llvm::stable_sort(AttrsForTypes, llvm::less_first());
331 AttrsForTypesSorted = true;
332 }
333
334 // FIXME: This is quadratic if we have lots of reuses of the same
335 // attributed type.
336 for (auto It = llvm::partition_point(
337 AttrsForTypes,
338 [=](const TypeAttrPair &A) { return A.first < AT; });
339 It != AttrsForTypes.end() && It->first == AT; ++It) {
340 if (It->second) {
341 const Attr *Result = It->second;
342 It->second = nullptr;
343 return Result;
344 }
345 }
346
347 llvm_unreachable("no Attr* for AttributedType*");
348 }
349
351 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
352 auto FoundLoc = LocsForMacros.find(MQT);
353 assert(FoundLoc != LocsForMacros.end() &&
354 "Unable to find macro expansion location for MacroQualifedType");
355 return FoundLoc->second;
356 }
357
358 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
359 SourceLocation Loc) {
360 LocsForMacros[MQT] = Loc;
361 }
362
363 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
364
365 bool didParseNoDeref() const { return parsedNoDeref; }
366
367 void setParsedHLSLParamMod(bool Parsed) { ParsedHLSLParamMod = Parsed; }
368
369 bool didParseHLSLParamMod() const { return ParsedHLSLParamMod; }
370
371 ~TypeProcessingState() {
372 if (savedAttrs.empty())
373 return;
374
375 getMutableDeclSpec().getAttributes().clearListOnly();
376 for (ParsedAttr *AL : savedAttrs)
377 getMutableDeclSpec().getAttributes().addAtEnd(AL);
378 }
379
380 private:
381 DeclSpec &getMutableDeclSpec() const {
382 return const_cast<DeclSpec&>(declarator.getDeclSpec());
383 }
384 };
385} // end anonymous namespace
386
388 ParsedAttributesView &fromList,
389 ParsedAttributesView &toList) {
390 fromList.remove(&attr);
391 toList.addAtEnd(&attr);
392}
393
394/// The location of a type attribute.
396 /// The attribute is in the decl-specifier-seq.
398 /// The attribute is part of a DeclaratorChunk.
400 /// The attribute is immediately after the declaration's name.
402};
403
404static void
405processTypeAttrs(TypeProcessingState &state, QualType &type,
406 TypeAttrLocation TAL, const ParsedAttributesView &attrs,
408
409static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
411
412static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
414
415static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
416 QualType &type);
417
418static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
420
421static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
423 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
424 return handleObjCGCTypeAttr(state, attr, type);
425 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
426 return handleObjCOwnershipTypeAttr(state, attr, type);
427}
428
429/// Given the index of a declarator chunk, check whether that chunk
430/// directly specifies the return type of a function and, if so, find
431/// an appropriate place for it.
432///
433/// \param i - a notional index which the search will start
434/// immediately inside
435///
436/// \param onlyBlockPointers Whether we should only look into block
437/// pointer types (vs. all pointer types).
439 unsigned i,
440 bool onlyBlockPointers) {
441 assert(i <= declarator.getNumTypeObjects());
442
443 DeclaratorChunk *result = nullptr;
444
445 // First, look inwards past parens for a function declarator.
446 for (; i != 0; --i) {
447 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
448 switch (fnChunk.Kind) {
450 continue;
451
452 // If we find anything except a function, bail out.
459 return result;
460
461 // If we do find a function declarator, scan inwards from that,
462 // looking for a (block-)pointer declarator.
464 for (--i; i != 0; --i) {
465 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
466 switch (ptrChunk.Kind) {
472 continue;
473
476 if (onlyBlockPointers)
477 continue;
478
479 [[fallthrough]];
480
482 result = &ptrChunk;
483 goto continue_outer;
484 }
485 llvm_unreachable("bad declarator chunk kind");
486 }
487
488 // If we run out of declarators doing that, we're done.
489 return result;
490 }
491 llvm_unreachable("bad declarator chunk kind");
492
493 // Okay, reconsider from our new point.
494 continue_outer: ;
495 }
496
497 // Ran out of chunks, bail out.
498 return result;
499}
500
501/// Given that an objc_gc attribute was written somewhere on a
502/// declaration *other* than on the declarator itself (for which, use
503/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
504/// didn't apply in whatever position it was written in, try to move
505/// it to a more appropriate position.
506static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
508 Declarator &declarator = state.getDeclarator();
509
510 // Move it to the outermost normal or block pointer declarator.
511 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
512 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
513 switch (chunk.Kind) {
516 // But don't move an ARC ownership attribute to the return type
517 // of a block.
518 DeclaratorChunk *destChunk = nullptr;
519 if (state.isProcessingDeclSpec() &&
520 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
521 destChunk = maybeMovePastReturnType(declarator, i - 1,
522 /*onlyBlockPointers=*/true);
523 if (!destChunk) destChunk = &chunk;
524
525 moveAttrFromListToList(attr, state.getCurrentAttributes(),
526 destChunk->getAttrs());
527 return;
528 }
529
532 continue;
533
534 // We may be starting at the return type of a block.
536 if (state.isProcessingDeclSpec() &&
537 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
539 declarator, i,
540 /*onlyBlockPointers=*/true)) {
541 moveAttrFromListToList(attr, state.getCurrentAttributes(),
542 dest->getAttrs());
543 return;
544 }
545 }
546 goto error;
547
548 // Don't walk through these.
552 goto error;
553 }
554 }
555 error:
556
557 diagnoseBadTypeAttribute(state.getSema(), attr, type);
558}
559
560/// Distribute an objc_gc type attribute that was written on the
561/// declarator.
563 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
564 Declarator &declarator = state.getDeclarator();
565
566 // objc_gc goes on the innermost pointer to something that's not a
567 // pointer.
568 unsigned innermost = -1U;
569 bool considerDeclSpec = true;
570 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
571 DeclaratorChunk &chunk = declarator.getTypeObject(i);
572 switch (chunk.Kind) {
575 innermost = i;
576 continue;
577
583 continue;
584
586 considerDeclSpec = false;
587 goto done;
588 }
589 }
590 done:
591
592 // That might actually be the decl spec if we weren't blocked by
593 // anything in the declarator.
594 if (considerDeclSpec) {
595 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
596 // Splice the attribute into the decl spec. Prevents the
597 // attribute from being applied multiple times and gives
598 // the source-location-filler something to work with.
599 state.saveDeclSpecAttrs();
601 declarator.getAttributes(), &attr);
602 return;
603 }
604 }
605
606 // Otherwise, if we found an appropriate chunk, splice the attribute
607 // into it.
608 if (innermost != -1U) {
610 declarator.getTypeObject(innermost).getAttrs());
611 return;
612 }
613
614 // Otherwise, diagnose when we're done building the type.
615 declarator.getAttributes().remove(&attr);
616 state.addIgnoredTypeAttr(attr);
617}
618
619/// A function type attribute was written somewhere in a declaration
620/// *other* than on the declarator itself or in the decl spec. Given
621/// that it didn't apply in whatever position it was written in, try
622/// to move it to a more appropriate position.
623static void distributeFunctionTypeAttr(TypeProcessingState &state,
625 Declarator &declarator = state.getDeclarator();
626
627 // Try to push the attribute from the return type of a function to
628 // the function itself.
629 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
630 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
631 switch (chunk.Kind) {
633 moveAttrFromListToList(attr, state.getCurrentAttributes(),
634 chunk.getAttrs());
635 return;
636
644 continue;
645 }
646 }
647
648 diagnoseBadTypeAttribute(state.getSema(), attr, type);
649}
650
651/// Try to distribute a function type attribute to the innermost
652/// function chunk or type. Returns true if the attribute was
653/// distributed, false if no location was found.
655 TypeProcessingState &state, ParsedAttr &attr,
656 ParsedAttributesView &attrList, QualType &declSpecType,
657 CUDAFunctionTarget CFT) {
658 Declarator &declarator = state.getDeclarator();
659
660 // Put it on the innermost function chunk, if there is one.
661 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
662 DeclaratorChunk &chunk = declarator.getTypeObject(i);
663 if (chunk.Kind != DeclaratorChunk::Function) continue;
664
665 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
666 return true;
667 }
668
669 return handleFunctionTypeAttr(state, attr, declSpecType, CFT);
670}
671
672/// A function type attribute was written in the decl spec. Try to
673/// apply it somewhere.
674static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
676 QualType &declSpecType,
677 CUDAFunctionTarget CFT) {
678 state.saveDeclSpecAttrs();
679
680 // Try to distribute to the innermost.
682 state, attr, state.getCurrentAttributes(), declSpecType, CFT))
683 return;
684
685 // If that failed, diagnose the bad attribute when the declarator is
686 // fully built.
687 state.addIgnoredTypeAttr(attr);
688}
689
690/// A function type attribute was written on the declarator or declaration.
691/// Try to apply it somewhere.
692/// `Attrs` is the attribute list containing the declaration (either of the
693/// declarator or the declaration).
694static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
696 QualType &declSpecType,
697 CUDAFunctionTarget CFT) {
698 Declarator &declarator = state.getDeclarator();
699
700 // Try to distribute to the innermost.
702 state, attr, declarator.getAttributes(), declSpecType, CFT))
703 return;
704
705 // If that failed, diagnose the bad attribute when the declarator is
706 // fully built.
707 declarator.getAttributes().remove(&attr);
708 state.addIgnoredTypeAttr(attr);
709}
710
711/// Given that there are attributes written on the declarator or declaration
712/// itself, try to distribute any type attributes to the appropriate
713/// declarator chunk.
714///
715/// These are attributes like the following:
716/// int f ATTR;
717/// int (f ATTR)();
718/// but not necessarily this:
719/// int f() ATTR;
720///
721/// `Attrs` is the attribute list containing the declaration (either of the
722/// declarator or the declaration).
723static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
724 QualType &declSpecType,
725 CUDAFunctionTarget CFT) {
726 // The called functions in this loop actually remove things from the current
727 // list, so iterating over the existing list isn't possible. Instead, make a
728 // non-owning copy and iterate over that.
729 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
730 for (ParsedAttr &attr : AttrsCopy) {
731 // Do not distribute [[]] attributes. They have strict rules for what
732 // they appertain to.
733 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute())
734 continue;
735
736 switch (attr.getKind()) {
739 break;
740
742 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT);
743 break;
744
746 // Microsoft type attributes cannot go after the declarator-id.
747 continue;
748
750 // Nullability specifiers cannot go after the declarator-id.
751
752 // Objective-C __kindof does not get distributed.
753 case ParsedAttr::AT_ObjCKindOf:
754 continue;
755
756 default:
757 break;
758 }
759 }
760}
761
762/// Add a synthetic '()' to a block-literal declarator if it is
763/// required, given the return type.
764static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
765 QualType declSpecType) {
766 Declarator &declarator = state.getDeclarator();
767
768 // First, check whether the declarator would produce a function,
769 // i.e. whether the innermost semantic chunk is a function.
770 if (declarator.isFunctionDeclarator()) {
771 // If so, make that declarator a prototyped declarator.
772 declarator.getFunctionTypeInfo().hasPrototype = true;
773 return;
774 }
775
776 // If there are any type objects, the type as written won't name a
777 // function, regardless of the decl spec type. This is because a
778 // block signature declarator is always an abstract-declarator, and
779 // abstract-declarators can't just be parentheses chunks. Therefore
780 // we need to build a function chunk unless there are no type
781 // objects and the decl spec type is a function.
782 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
783 return;
784
785 // Note that there *are* cases with invalid declarators where
786 // declarators consist solely of parentheses. In general, these
787 // occur only in failed efforts to make function declarators, so
788 // faking up the function chunk is still the right thing to do.
789
790 // Otherwise, we need to fake up a function declarator.
791 SourceLocation loc = declarator.getBeginLoc();
792
793 // ...and *prepend* it to the declarator.
794 SourceLocation NoLoc;
796 /*HasProto=*/true,
797 /*IsAmbiguous=*/false,
798 /*LParenLoc=*/NoLoc,
799 /*ArgInfo=*/nullptr,
800 /*NumParams=*/0,
801 /*EllipsisLoc=*/NoLoc,
802 /*RParenLoc=*/NoLoc,
803 /*RefQualifierIsLvalueRef=*/true,
804 /*RefQualifierLoc=*/NoLoc,
805 /*MutableLoc=*/NoLoc, EST_None,
806 /*ESpecRange=*/SourceRange(),
807 /*Exceptions=*/nullptr,
808 /*ExceptionRanges=*/nullptr,
809 /*NumExceptions=*/0,
810 /*NoexceptExpr=*/nullptr,
811 /*ExceptionSpecTokens=*/nullptr,
812 /*DeclsInPrototype=*/{}, loc, loc, declarator));
813
814 // For consistency, make sure the state still has us as processing
815 // the decl spec.
816 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
817 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
818}
819
821 unsigned &TypeQuals,
822 QualType TypeSoFar,
823 unsigned RemoveTQs,
824 unsigned DiagID) {
825 // If this occurs outside a template instantiation, warn the user about
826 // it; they probably didn't mean to specify a redundant qualifier.
827 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
828 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
831 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
832 if (!(RemoveTQs & Qual.first))
833 continue;
834
835 if (!S.inTemplateInstantiation()) {
836 if (TypeQuals & Qual.first)
837 S.Diag(Qual.second, DiagID)
838 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
839 << FixItHint::CreateRemoval(Qual.second);
840 }
841
842 TypeQuals &= ~Qual.first;
843 }
844}
845
846/// Return true if this is omitted block return type. Also check type
847/// attributes and type qualifiers when returning true.
848static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
850 if (!isOmittedBlockReturnType(declarator))
851 return false;
852
853 // Warn if we see type attributes for omitted return type on a block literal.
855 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
856 if (AL.isInvalid() || !AL.isTypeAttr())
857 continue;
858 S.Diag(AL.getLoc(),
859 diag::warn_block_literal_attributes_on_omitted_return_type)
860 << AL;
861 ToBeRemoved.push_back(&AL);
862 }
863 // Remove bad attributes from the list.
864 for (ParsedAttr *AL : ToBeRemoved)
865 declarator.getMutableDeclSpec().getAttributes().remove(AL);
866
867 // Warn if we see type qualifiers for omitted return type on a block literal.
868 const DeclSpec &DS = declarator.getDeclSpec();
869 unsigned TypeQuals = DS.getTypeQualifiers();
870 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
871 diag::warn_block_literal_qualifiers_on_omitted_return_type);
873
874 return true;
875}
876
877static OpenCLAccessAttr::Spelling
879 for (const ParsedAttr &AL : Attrs)
880 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
881 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
882 return OpenCLAccessAttr::Keyword_read_only;
883}
884
885static UnaryTransformType::UTTKind
887 switch (SwitchTST) {
888#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
889 case TST_##Trait: \
890 return UnaryTransformType::Enum;
891#include "clang/Basic/TransformTypeTraits.def"
892 default:
893 llvm_unreachable("attempted to parse a non-unary transform builtin");
894 }
895}
896
897/// Convert the specified declspec to the appropriate type
898/// object.
899/// \param state Specifies the declarator containing the declaration specifier
900/// to be converted, along with other associated processing state.
901/// \returns The type described by the declaration specifiers. This function
902/// never returns null.
903static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
904 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
905 // checking.
906
907 Sema &S = state.getSema();
908 Declarator &declarator = state.getDeclarator();
909 DeclSpec &DS = declarator.getMutableDeclSpec();
910 SourceLocation DeclLoc = declarator.getIdentifierLoc();
911 if (DeclLoc.isInvalid())
912 DeclLoc = DS.getBeginLoc();
913
914 ASTContext &Context = S.Context;
915
917 switch (DS.getTypeSpecType()) {
919 Result = Context.VoidTy;
920 break;
923 Result = Context.CharTy;
925 Result = Context.SignedCharTy;
926 else {
928 "Unknown TSS value");
929 Result = Context.UnsignedCharTy;
930 }
931 break;
934 Result = Context.WCharTy;
936 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
938 Context.getPrintingPolicy());
939 Result = Context.getSignedWCharType();
940 } else {
942 "Unknown TSS value");
943 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
945 Context.getPrintingPolicy());
946 Result = Context.getUnsignedWCharType();
947 }
948 break;
951 "Unknown TSS value");
952 Result = Context.Char8Ty;
953 break;
956 "Unknown TSS value");
957 Result = Context.Char16Ty;
958 break;
961 "Unknown TSS value");
962 Result = Context.Char32Ty;
963 break;
965 // If this is a missing declspec in a block literal return context, then it
966 // is inferred from the return statements inside the block.
967 // The declspec is always missing in a lambda expr context; it is either
968 // specified with a trailing return type or inferred.
969 if (S.getLangOpts().CPlusPlus14 &&
971 // In C++1y, a lambda's implicit return type is 'auto'.
972 Result = Context.getAutoDeductType();
973 break;
974 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
975 checkOmittedBlockReturnType(S, declarator,
976 Context.DependentTy)) {
977 Result = Context.DependentTy;
978 break;
979 }
980
981 // Unspecified typespec defaults to int in C90. However, the C90 grammar
982 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
983 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
984 // Note that the one exception to this is function definitions, which are
985 // allowed to be completely missing a declspec. This is handled in the
986 // parser already though by it pretending to have seen an 'int' in this
987 // case.
989 // Only emit the diagnostic for the first declarator in a DeclGroup, as
990 // the warning is always implied for all subsequent declarators, and the
991 // fix must only be applied exactly once as well.
992 if (declarator.isFirstDeclarator()) {
993 S.Diag(DeclLoc, diag::warn_missing_type_specifier)
994 << DS.getSourceRange()
996 }
997 } else if (!DS.hasTypeSpecifier()) {
998 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
999 // "At least one type specifier shall be given in the declaration
1000 // specifiers in each declaration, and in the specifier-qualifier list
1001 // in each struct declaration and type name."
1002 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
1003 if (declarator.isFirstDeclarator()) {
1004 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1005 << DS.getSourceRange();
1006 }
1007
1008 // When this occurs, often something is very broken with the value
1009 // being declared, poison it as invalid so we don't get chains of
1010 // errors.
1011 declarator.setInvalidType(true);
1012 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1013 DS.isTypeSpecPipe()) {
1014 if (declarator.isFirstDeclarator()) {
1015 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1016 << DS.getSourceRange();
1017 }
1018 declarator.setInvalidType(true);
1019 } else if (declarator.isFirstDeclarator()) {
1020 assert(S.getLangOpts().isImplicitIntAllowed() &&
1021 "implicit int is disabled?");
1022 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1023 << DS.getSourceRange()
1024 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int ");
1025 }
1026 }
1027
1028 [[fallthrough]];
1029 case DeclSpec::TST_int: {
1031 switch (DS.getTypeSpecWidth()) {
1033 Result = Context.IntTy;
1034 break;
1036 Result = Context.ShortTy;
1037 break;
1039 Result = Context.LongTy;
1040 break;
1042 Result = Context.LongLongTy;
1043
1044 if (S.getLangOpts().OpenCL) {
1045 // OpenCL v3.0 s6.3.4: 'long long' is a reserved data type.
1046 S.Diag(DS.getTypeSpecWidthLoc(), diag::warn_opencl_longlong);
1047 } else if (!S.getLangOpts().C99) {
1048 // 'long long' is a C99 or C++11 feature.
1049 if (S.getLangOpts().CPlusPlus)
1051 S.getLangOpts().CPlusPlus11 ?
1052 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1053 else
1054 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1055 }
1056 break;
1057 }
1058 } else {
1059 switch (DS.getTypeSpecWidth()) {
1061 Result = Context.UnsignedIntTy;
1062 break;
1064 Result = Context.UnsignedShortTy;
1065 break;
1067 Result = Context.UnsignedLongTy;
1068 break;
1070 Result = Context.UnsignedLongLongTy;
1071
1072 if (S.getLangOpts().OpenCL) {
1073 // OpenCL v3.0 s6.3.4: 'long long' is a reserved data type.
1074 S.Diag(DS.getTypeSpecWidthLoc(), diag::warn_opencl_longlong);
1075 } else if (!S.getLangOpts().C99) {
1076 // 'long long' is a C99 or C++11 feature.
1077 if (S.getLangOpts().CPlusPlus)
1079 S.getLangOpts().CPlusPlus11 ?
1080 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1081 else
1082 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1083 }
1084 break;
1085 }
1086 }
1087 break;
1088 }
1089 case DeclSpec::TST_bitint: {
1091 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1092 Result =
1094 DS.getRepAsExpr(), DS.getBeginLoc());
1095 if (Result.isNull()) {
1096 Result = Context.IntTy;
1097 declarator.setInvalidType(true);
1098 }
1099 break;
1100 }
1101 case DeclSpec::TST_accum: {
1102 switch (DS.getTypeSpecWidth()) {
1104 Result = Context.ShortAccumTy;
1105 break;
1107 Result = Context.AccumTy;
1108 break;
1110 Result = Context.LongAccumTy;
1111 break;
1113 llvm_unreachable("Unable to specify long long as _Accum width");
1114 }
1115
1117 Result = Context.getCorrespondingUnsignedType(Result);
1118
1119 if (DS.isTypeSpecSat())
1120 Result = Context.getCorrespondingSaturatedType(Result);
1121
1122 break;
1123 }
1124 case DeclSpec::TST_fract: {
1125 switch (DS.getTypeSpecWidth()) {
1127 Result = Context.ShortFractTy;
1128 break;
1130 Result = Context.FractTy;
1131 break;
1133 Result = Context.LongFractTy;
1134 break;
1136 llvm_unreachable("Unable to specify long long as _Fract width");
1137 }
1138
1140 Result = Context.getCorrespondingUnsignedType(Result);
1141
1142 if (DS.isTypeSpecSat())
1143 Result = Context.getCorrespondingSaturatedType(Result);
1144
1145 break;
1146 }
1148 if (!S.Context.getTargetInfo().hasInt128Type() &&
1149 !(S.getLangOpts().isTargetDevice()))
1150 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1151 << "__int128";
1153 Result = Context.UnsignedInt128Ty;
1154 else
1155 Result = Context.Int128Ty;
1156 break;
1158 // CUDA host and device may have different _Float16 support, therefore
1159 // do not diagnose _Float16 usage to avoid false alarm.
1160 // ToDo: more precise diagnostics for CUDA.
1161 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1162 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1163 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1164 << "_Float16";
1165 Result = Context.Float16Ty;
1166 break;
1167 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1170 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) &&
1171 !S.getLangOpts().SYCLIsDevice)
1172 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16";
1173 Result = Context.BFloat16Ty;
1174 break;
1175 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1178 Result = Context.LongDoubleTy;
1179 else
1180 Result = Context.DoubleTy;
1181 if (S.getLangOpts().OpenCL) {
1182 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1183 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1184 << 0 << Result
1185 << (S.getLangOpts().getOpenCLCompatibleVersion() == 300
1186 ? "cl_khr_fp64 and __opencl_c_fp64"
1187 : "cl_khr_fp64");
1188 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1189 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1190 }
1191 break;
1195 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1196 << "__float128";
1197 Result = Context.Float128Ty;
1198 break;
1200 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1201 !S.getLangOpts().SYCLIsDevice &&
1202 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1203 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1204 Result = Context.Ibm128Ty;
1205 break;
1206 case DeclSpec::TST_bool:
1207 Result = Context.BoolTy; // _Bool or bool
1208 break;
1209 case DeclSpec::TST_decimal32: // _Decimal32
1210 case DeclSpec::TST_decimal64: // _Decimal64
1211 case DeclSpec::TST_decimal128: // _Decimal128
1212 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1213 Result = Context.IntTy;
1214 declarator.setInvalidType(true);
1215 break;
1217 case DeclSpec::TST_enum:
1221 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1222 if (!D) {
1223 // This can happen in C++ with ambiguous lookups.
1224 Result = Context.IntTy;
1225 declarator.setInvalidType(true);
1226 break;
1227 }
1228
1229 // If the type is deprecated or unavailable, diagnose it.
1231
1233 DS.getTypeSpecComplex() == 0 &&
1235 "No qualifiers on tag names!");
1236
1239 // TypeQuals handled by caller.
1240 Result = Context.getTagType(Keyword, DS.getTypeSpecScope().getScopeRep(), D,
1241 DS.isTypeSpecOwned());
1242 break;
1243 }
1246 DS.getTypeSpecComplex() == 0 &&
1248 "Can't handle qualifiers on typedef names yet!");
1250 if (Result.isNull()) {
1251 declarator.setInvalidType(true);
1252 }
1253
1254 // TypeQuals handled by caller.
1255 break;
1256 }
1259 // FIXME: Preserve type source info.
1261 assert(!Result.isNull() && "Didn't get a type for typeof?");
1262 if (!Result->isDependentType())
1263 if (const auto *TT = Result->getAs<TagType>())
1264 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1265 // TypeQuals handled by caller.
1266 Result = Context.getTypeOfType(
1270 break;
1273 Expr *E = DS.getRepAsExpr();
1274 assert(E && "Didn't get an expression for typeof?");
1275 // TypeQuals handled by caller.
1280 if (Result.isNull()) {
1281 Result = Context.IntTy;
1282 declarator.setInvalidType(true);
1283 }
1284 break;
1285 }
1287 Expr *E = DS.getRepAsExpr();
1288 assert(E && "Didn't get an expression for decltype?");
1289 // TypeQuals handled by caller.
1291 if (Result.isNull()) {
1292 Result = Context.IntTy;
1293 declarator.setInvalidType(true);
1294 }
1295 break;
1296 }
1298 Expr *E = DS.getPackIndexingExpr();
1299 assert(E && "Didn't get an expression for pack indexing");
1300 QualType Pattern = S.GetTypeFromParser(DS.getRepAsType());
1301 Result = S.BuildPackIndexingType(Pattern, E, DS.getBeginLoc(),
1302 DS.getEllipsisLoc());
1303 if (Result.isNull()) {
1304 declarator.setInvalidType(true);
1305 Result = Context.IntTy;
1306 }
1307 break;
1308 }
1309
1310#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1311#include "clang/Basic/TransformTypeTraits.def"
1313 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1316 DS.getTypeSpecTypeLoc());
1317 if (Result.isNull()) {
1318 Result = Context.IntTy;
1319 declarator.setInvalidType(true);
1320 }
1321 break;
1322
1323 case DeclSpec::TST_auto:
1325 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1328
1329 TemplateDecl *TypeConstraintConcept = nullptr;
1331 if (DS.isConstrainedAuto()) {
1332 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1333 TypeConstraintConcept =
1334 cast<TemplateDecl>(TemplateId->Template.get().getAsTemplateDecl());
1335 TemplateArgumentListInfo TemplateArgsInfo;
1336 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1337 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1338 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1339 TemplateId->NumArgs);
1340 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1341 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1342 TemplateArgs.push_back(ArgLoc.getArgument());
1343 } else {
1344 declarator.setInvalidType(true);
1345 }
1346 }
1348 TypeConstraintConcept, TemplateArgs);
1349 break;
1350 }
1351
1353 Result = Context.getAutoType(DeducedKind::Undeduced, QualType(),
1355 break;
1356
1358 Result = Context.UnknownAnyTy;
1359 break;
1360
1363 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1365 if (Result.isNull()) {
1366 Result = Context.IntTy;
1367 declarator.setInvalidType(true);
1368 }
1369 break;
1370
1371#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1372 case DeclSpec::TST_##ImgType##_t: \
1373 switch (getImageAccess(DS.getAttributes())) { \
1374 case OpenCLAccessAttr::Keyword_write_only: \
1375 Result = Context.Id##WOTy; \
1376 break; \
1377 case OpenCLAccessAttr::Keyword_read_write: \
1378 Result = Context.Id##RWTy; \
1379 break; \
1380 case OpenCLAccessAttr::Keyword_read_only: \
1381 Result = Context.Id##ROTy; \
1382 break; \
1383 case OpenCLAccessAttr::SpellingNotCalculated: \
1384 llvm_unreachable("Spelling not yet calculated"); \
1385 } \
1386 break;
1387#include "clang/Basic/OpenCLImageTypes.def"
1388
1389#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1390 case DeclSpec::TST_##Name: \
1391 Result = Context.SingletonId; \
1392 break;
1393#include "clang/Basic/HLSLIntangibleTypes.def"
1394
1396 Result = Context.IntTy;
1397 declarator.setInvalidType(true);
1398 break;
1399 }
1400
1401 // FIXME: we want resulting declarations to be marked invalid, but claiming
1402 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1403 // a null type.
1404 if (Result->containsErrors())
1405 declarator.setInvalidType();
1406
1407 if (S.getLangOpts().OpenCL) {
1408 const auto &OpenCLOptions = S.getOpenCLOptions();
1409 bool IsOpenCLC30Compatible =
1411 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1412 // support.
1413 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1414 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1415 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1416 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1417 // only when the optional feature is supported
1418 if ((Result->isImageType() || Result->isSamplerT()) &&
1419 (IsOpenCLC30Compatible &&
1420 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1421 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1422 << 0 << Result << "__opencl_c_images";
1423 declarator.setInvalidType();
1424 } else if (Result->isOCLImage3dWOType() &&
1425 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1426 S.getLangOpts())) {
1427 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1428 << 0 << Result
1429 << (IsOpenCLC30Compatible
1430 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1431 : "cl_khr_3d_image_writes");
1432 declarator.setInvalidType();
1433 }
1434 }
1435
1436 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1438
1439 // Only fixed point types can be saturated
1440 if (DS.isTypeSpecSat() && !IsFixedPointType)
1441 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1443 Context.getPrintingPolicy());
1444
1445 // Handle complex types.
1447 if (S.getLangOpts().Freestanding)
1448 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1449 Result = Context.getComplexType(Result);
1450 } else if (DS.isTypeAltiVecVector()) {
1451 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1452 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1454 if (DS.isTypeAltiVecPixel())
1455 VecKind = VectorKind::AltiVecPixel;
1456 else if (DS.isTypeAltiVecBool())
1457 VecKind = VectorKind::AltiVecBool;
1458 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1459 }
1460
1461 // _Imaginary was a feature of C99 through C23 but was never supported in
1462 // Clang. The feature was removed in C2y, but we retain the unsupported
1463 // diagnostic for an improved user experience.
1465 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1466
1467 // Before we process any type attributes, synthesize a block literal
1468 // function declarator if necessary.
1469 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1471
1472 // Apply any type attributes from the decl spec. This may cause the
1473 // list of type attributes to be temporarily saved while the type
1474 // attributes are pushed around.
1475 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1476 if (!DS.isTypeSpecPipe()) {
1477 // We also apply declaration attributes that "slide" to the decl spec.
1478 // Ordering can be important for attributes. The decalaration attributes
1479 // come syntactically before the decl spec attributes, so we process them
1480 // in that order.
1481 ParsedAttributesView SlidingAttrs;
1482 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1483 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1484 SlidingAttrs.addAtEnd(&AL);
1485
1486 // For standard syntax attributes, which would normally appertain to the
1487 // declaration here, suggest moving them to the type instead. But only
1488 // do this for our own vendor attributes; moving other vendors'
1489 // attributes might hurt portability.
1490 // There's one special case that we need to deal with here: The
1491 // `MatrixType` attribute may only be used in a typedef declaration. If
1492 // it's being used anywhere else, don't output the warning as
1493 // ProcessDeclAttributes() will output an error anyway.
1494 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1495 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1497 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1498 << AL;
1499 }
1500 }
1501 }
1502 // During this call to processTypeAttrs(),
1503 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1504 // reference to the DeclSpec attributes, rather than the declaration
1505 // attributes. However, this doesn't matter, as getCurrentAttributes()
1506 // is only called when distributing attributes from one attribute list
1507 // to another. Declaration attributes are always C++11 attributes, and these
1508 // are never distributed.
1509 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1511 }
1512
1513 // Apply const/volatile/restrict qualifiers to T.
1514 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1515 // Warn about CV qualifiers on function types.
1516 // C99 6.7.3p8:
1517 // If the specification of a function type includes any type qualifiers,
1518 // the behavior is undefined.
1519 // C2y changed this behavior to be implementation-defined. Clang defines
1520 // the behavior in all cases to ignore the qualifier, as in C++.
1521 // C++11 [dcl.fct]p7:
1522 // The effect of a cv-qualifier-seq in a function declarator is not the
1523 // same as adding cv-qualification on top of the function type. In the
1524 // latter case, the cv-qualifiers are ignored.
1525 if (Result->isFunctionType()) {
1526 unsigned DiagId = diag::warn_typecheck_function_qualifiers_ignored;
1527 if (!S.getLangOpts().CPlusPlus && !S.getLangOpts().C2y)
1528 DiagId = diag::ext_typecheck_function_qualifiers_unspecified;
1530 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1531 DiagId);
1532 // No diagnostic for 'restrict' or '_Atomic' applied to a
1533 // function type; we'll diagnose those later, in BuildQualifiedType.
1534 }
1535
1536 // C++11 [dcl.ref]p1:
1537 // Cv-qualified references are ill-formed except when the
1538 // cv-qualifiers are introduced through the use of a typedef-name
1539 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1540 //
1541 // There don't appear to be any other contexts in which a cv-qualified
1542 // reference type could be formed, so the 'ill-formed' clause here appears
1543 // to never happen.
1544 if (TypeQuals && Result->isReferenceType()) {
1546 S, DS, TypeQuals, Result,
1548 diag::warn_typecheck_reference_qualifiers);
1549 }
1550
1551 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1552 // than once in the same specifier-list or qualifier-list, either directly
1553 // or via one or more typedefs."
1554 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1555 && TypeQuals & Result.getCVRQualifiers()) {
1556 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1557 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1558 << "const";
1559 }
1560
1561 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1562 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1563 << "volatile";
1564 }
1565
1566 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1567 // produce a warning in this case.
1568 }
1569
1570 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1571
1572 // If adding qualifiers fails, just use the unqualified type.
1573 if (Qualified.isNull())
1574 declarator.setInvalidType(true);
1575 else
1576 Result = Qualified;
1577 }
1578
1579 // Check for __ob_wrap and __ob_trap
1580 if (DS.isOverflowBehaviorSpecified() &&
1581 S.getLangOpts().OverflowBehaviorTypes) {
1582 if (!Result->isIntegerType()) {
1584 StringRef SpecifierName =
1586 S.Diag(Loc, diag::err_overflow_behavior_non_integer_type)
1587 << SpecifierName << Result.getAsString() << 1;
1588 } else {
1589 OverflowBehaviorType::OverflowBehaviorKind Kind =
1590 DS.isWrapSpecified()
1591 ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
1592 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
1593 Result = state.getOverflowBehaviorType(Kind, Result);
1594 }
1595 }
1596
1597 if (S.getLangOpts().HLSL)
1599
1600 assert(!Result.isNull() && "This function should not return a null type");
1601 return Result;
1602}
1603
1604static std::string getPrintableNameForEntity(DeclarationName Entity) {
1605 if (Entity)
1606 return Entity.getAsString();
1607
1608 return "type name";
1609}
1610
1612 if (T->isDependentType())
1613 return true;
1614
1615 const auto *AT = dyn_cast<AutoType>(T);
1616 return AT && AT->isGNUAutoType();
1617}
1618
1620 Qualifiers Qs, const DeclSpec *DS) {
1621 if (T.isNull())
1622 return QualType();
1623
1624 // Ignore any attempt to form a cv-qualified reference.
1625 if (T->isReferenceType()) {
1626 Qs.removeConst();
1627 Qs.removeVolatile();
1628 }
1629
1630 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1631 // object or incomplete types shall not be restrict-qualified."
1632 if (Qs.hasRestrict()) {
1633 unsigned DiagID = 0;
1634 QualType EltTy = Context.getBaseElementType(T);
1635
1636 if (EltTy->isAnyPointerType() || EltTy->isReferenceType() ||
1637 EltTy->isMemberPointerType()) {
1638
1639 if (const auto *PTy = EltTy->getAs<MemberPointerType>())
1640 EltTy = PTy->getPointeeType();
1641 else
1642 EltTy = EltTy->getPointeeType();
1643
1644 // If we have a pointer or reference, the pointee must have an object
1645 // incomplete type.
1646 if (!EltTy->isIncompleteOrObjectType())
1647 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1648
1649 } else if (!isDependentOrGNUAutoType(T)) {
1650 // For an __auto_type variable, we may not have seen the initializer yet
1651 // and so have no idea whether the underlying type is a pointer type or
1652 // not.
1653 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1654 EltTy = T;
1655 }
1656
1657 Loc = DS ? DS->getRestrictSpecLoc() : Loc;
1658 if (DiagID) {
1659 Diag(Loc, DiagID) << EltTy;
1660 Qs.removeRestrict();
1661 } else {
1662 if (T->isArrayType())
1663 Diag(Loc, getLangOpts().C23
1664 ? diag::warn_c23_compat_restrict_on_array_of_pointers
1665 : diag::ext_restrict_on_array_of_pointers_c23);
1666 }
1667 }
1668
1669 return Context.getQualifiedType(T, Qs);
1670}
1671
1673 unsigned CVRAU, const DeclSpec *DS) {
1674 if (T.isNull())
1675 return QualType();
1676
1677 // Ignore any attempt to form a cv-qualified reference.
1678 if (T->isReferenceType())
1679 CVRAU &=
1681
1682 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1683 // TQ_unaligned;
1684 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1685
1686 // C11 6.7.3/5:
1687 // If the same qualifier appears more than once in the same
1688 // specifier-qualifier-list, either directly or via one or more typedefs,
1689 // the behavior is the same as if it appeared only once.
1690 //
1691 // It's not specified what happens when the _Atomic qualifier is applied to
1692 // a type specified with the _Atomic specifier, but we assume that this
1693 // should be treated as if the _Atomic qualifier appeared multiple times.
1694 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1695 // C11 6.7.3/5:
1696 // If other qualifiers appear along with the _Atomic qualifier in a
1697 // specifier-qualifier-list, the resulting type is the so-qualified
1698 // atomic type.
1699 //
1700 // Don't need to worry about array types here, since _Atomic can't be
1701 // applied to such types.
1702 SplitQualType Split = T.getSplitUnqualifiedType();
1703 T = BuildAtomicType(QualType(Split.Ty, 0),
1704 DS ? DS->getAtomicSpecLoc() : Loc);
1705 if (T.isNull())
1706 return T;
1707 Split.Quals.addCVRQualifiers(CVR);
1708 return BuildQualifiedType(T, Loc, Split.Quals);
1709 }
1710
1713 return BuildQualifiedType(T, Loc, Q, DS);
1714}
1715
1717 return Context.getParenType(T);
1718}
1719
1720/// Given that we're building a pointer or reference to the given
1722 SourceLocation loc,
1723 bool isReference) {
1724 // Bail out if retention is unrequired or already specified.
1725 if (!type->isObjCLifetimeType() ||
1726 type.getObjCLifetime() != Qualifiers::OCL_None)
1727 return type;
1728
1730
1731 // If the object type is const-qualified, we can safely use
1732 // __unsafe_unretained. This is safe (because there are no read
1733 // barriers), and it'll be safe to coerce anything but __weak* to
1734 // the resulting type.
1735 if (type.isConstQualified()) {
1736 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1737
1738 // Otherwise, check whether the static type does not require
1739 // retaining. This currently only triggers for Class (possibly
1740 // protocol-qualifed, and arrays thereof).
1741 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1742 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1743
1744 // If we are in an unevaluated context, like sizeof, skip adding a
1745 // qualification.
1746 } else if (S.isUnevaluatedContext()) {
1747 return type;
1748
1749 // If that failed, give an error and recover using __strong. __strong
1750 // is the option most likely to prevent spurious second-order diagnostics,
1751 // like when binding a reference to a field.
1752 } else {
1753 // These types can show up in private ivars in system headers, so
1754 // we need this to not be an error in those cases. Instead we
1755 // want to delay.
1759 diag::err_arc_indirect_no_ownership, type, isReference));
1760 } else {
1761 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1762 }
1763 implicitLifetime = Qualifiers::OCL_Strong;
1764 }
1765 assert(implicitLifetime && "didn't infer any lifetime!");
1766
1767 Qualifiers qs;
1768 qs.addObjCLifetime(implicitLifetime);
1769 return S.Context.getQualifiedType(type, qs);
1770}
1771
1772static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1773 std::string Quals = FnTy->getMethodQuals().getAsString();
1774
1775 switch (FnTy->getRefQualifier()) {
1776 case RQ_None:
1777 break;
1778
1779 case RQ_LValue:
1780 if (!Quals.empty())
1781 Quals += ' ';
1782 Quals += '&';
1783 break;
1784
1785 case RQ_RValue:
1786 if (!Quals.empty())
1787 Quals += ' ';
1788 Quals += "&&";
1789 break;
1790 }
1791
1792 return Quals;
1793}
1794
1795namespace {
1796/// Kinds of declarator that cannot contain a qualified function type.
1797///
1798/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1799/// a function type with a cv-qualifier or a ref-qualifier can only appear
1800/// at the topmost level of a type.
1801///
1802/// Parens and member pointers are permitted. We don't diagnose array and
1803/// function declarators, because they don't allow function types at all.
1804///
1805/// The values of this enum are used in diagnostics.
1806enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1807} // end anonymous namespace
1808
1809/// Check whether the type T is a qualified function type, and if it is,
1810/// diagnose that it cannot be contained within the given kind of declarator.
1812 QualifiedFunctionKind QFK) {
1813 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1814 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1815 if (!FPT ||
1816 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1817 return false;
1818
1819 S.Diag(Loc, diag::err_compound_qualified_function_type)
1820 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1822 return true;
1823}
1824
1826 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1827 if (!FPT ||
1828 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1829 return false;
1830
1831 Diag(Loc, diag::err_qualified_function_typeid)
1832 << T << getFunctionQualifiersAsString(FPT);
1833 return true;
1834}
1835
1836// Helper to deduce addr space of a pointee type in OpenCL mode.
1838 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
1839 !PointeeType->isSamplerT() &&
1840 !PointeeType.hasAddressSpace())
1841 PointeeType = S.getASTContext().getAddrSpaceQualType(
1843 return PointeeType;
1844}
1845
1847 SourceLocation Loc, DeclarationName Entity) {
1848 if (T->isReferenceType()) {
1849 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1850 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1851 << getPrintableNameForEntity(Entity) << T;
1852 return QualType();
1853 }
1854
1855 if (T->isFunctionType() && getLangOpts().OpenCL &&
1856 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1857 getLangOpts())) {
1858 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
1859 return QualType();
1860 }
1861
1862 if (getLangOpts().HLSL && Loc.isValid()) {
1863 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
1864 return QualType();
1865 }
1866
1867 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1868 return QualType();
1869
1870 if (T->isObjCObjectType())
1871 return Context.getObjCObjectPointerType(T);
1872
1873 // In ARC, it is forbidden to build pointers to unqualified pointers.
1874 if (getLangOpts().ObjCAutoRefCount)
1875 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1876
1877 if (getLangOpts().OpenCL)
1878 T = deduceOpenCLPointeeAddrSpace(*this, T);
1879
1880 // In WebAssembly, pointers to reference types and pointers to tables are
1881 // illegal.
1882 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
1883 if (T.isWebAssemblyReferenceType()) {
1884 Diag(Loc, diag::err_wasm_reference_pr) << 0;
1885 return QualType();
1886 }
1887
1888 // We need to desugar the type here in case T is a ParenType.
1889 if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
1890 Diag(Loc, diag::err_wasm_table_pr) << 0;
1891 return QualType();
1892 }
1893 }
1894
1895 // Build the pointer type.
1896 return Context.getPointerType(T);
1897}
1898
1900 SourceLocation Loc,
1901 DeclarationName Entity) {
1902 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1903 "Unresolved overloaded function type");
1904
1905 // C++0x [dcl.ref]p6:
1906 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1907 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1908 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1909 // the type "lvalue reference to T", while an attempt to create the type
1910 // "rvalue reference to cv TR" creates the type TR.
1911 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1912
1913 // C++ [dcl.ref]p4: There shall be no references to references.
1914 //
1915 // According to C++ DR 106, references to references are only
1916 // diagnosed when they are written directly (e.g., "int & &"),
1917 // but not when they happen via a typedef:
1918 //
1919 // typedef int& intref;
1920 // typedef intref& intref2;
1921 //
1922 // Parser::ParseDeclaratorInternal diagnoses the case where
1923 // references are written directly; here, we handle the
1924 // collapsing of references-to-references as described in C++0x.
1925 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1926
1927 // C++ [dcl.ref]p1:
1928 // A declarator that specifies the type "reference to cv void"
1929 // is ill-formed.
1930 if (T->isVoidType()) {
1931 Diag(Loc, diag::err_reference_to_void);
1932 return QualType();
1933 }
1934
1935 if (getLangOpts().HLSL && Loc.isValid()) {
1936 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
1937 return QualType();
1938 }
1939
1940 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1941 return QualType();
1942
1943 if (T->isFunctionType() && getLangOpts().OpenCL &&
1944 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1945 getLangOpts())) {
1946 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
1947 return QualType();
1948 }
1949
1950 // In ARC, it is forbidden to build references to unqualified pointers.
1951 if (getLangOpts().ObjCAutoRefCount)
1952 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1953
1954 if (getLangOpts().OpenCL)
1955 T = deduceOpenCLPointeeAddrSpace(*this, T);
1956
1957 // In WebAssembly, references to reference types and tables are illegal.
1958 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
1959 T.isWebAssemblyReferenceType()) {
1960 Diag(Loc, diag::err_wasm_reference_pr) << 1;
1961 return QualType();
1962 }
1963 if (T->isWebAssemblyTableType()) {
1964 Diag(Loc, diag::err_wasm_table_pr) << 1;
1965 return QualType();
1966 }
1967
1968 // Handle restrict on references.
1969 if (LValueRef)
1970 return Context.getLValueReferenceType(T, SpelledAsLValue);
1971 return Context.getRValueReferenceType(T);
1972}
1973
1975 return Context.getReadPipeType(T);
1976}
1977
1979 return Context.getWritePipeType(T);
1980}
1981
1982QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
1983 SourceLocation Loc) {
1984 if (BitWidth->isInstantiationDependent())
1985 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
1986
1987 llvm::APSInt Bits(32);
1989 BitWidth, &Bits, /*FIXME*/ AllowFoldKind::Allow);
1990
1991 if (ICE.isInvalid())
1992 return QualType();
1993
1994 size_t NumBits = Bits.getZExtValue();
1995 if (!IsUnsigned && NumBits < 2) {
1996 Diag(Loc, diag::err_bit_int_bad_size) << 0;
1997 return QualType();
1998 }
1999
2000 if (IsUnsigned && NumBits < 1) {
2001 Diag(Loc, diag::err_bit_int_bad_size) << 1;
2002 return QualType();
2003 }
2004
2005 const TargetInfo &TI = getASTContext().getTargetInfo();
2006 if (NumBits > TI.getMaxBitIntWidth()) {
2007 Diag(Loc, diag::err_bit_int_max_size)
2008 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2009 return QualType();
2010 }
2011
2012 return Context.getBitIntType(IsUnsigned, NumBits);
2013}
2014
2015/// Check whether the specified array bound can be evaluated using the relevant
2016/// language rules. If so, returns the possibly-converted expression and sets
2017/// SizeVal to the size. If not, but the expression might be a VLA bound,
2018/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2019/// ExprError().
2020static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2021 llvm::APSInt &SizeVal, unsigned VLADiag,
2022 bool VLAIsError) {
2023 if (S.getLangOpts().CPlusPlus14 &&
2024 (VLAIsError ||
2025 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2026 // C++14 [dcl.array]p1:
2027 // The constant-expression shall be a converted constant expression of
2028 // type std::size_t.
2029 //
2030 // Don't apply this rule if we might be forming a VLA: in that case, we
2031 // allow non-constant expressions and constant-folding. We only need to use
2032 // the converted constant expression rules (to properly convert the source)
2033 // when the source expression is of class type.
2035 ArraySize, S.Context.getSizeType(), SizeVal, CCEKind::ArrayBound);
2036 }
2037
2038 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2039 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2040 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2041 public:
2042 unsigned VLADiag;
2043 bool VLAIsError;
2044 bool IsVLA = false;
2045
2046 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2047 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2048
2049 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2050 QualType T) override {
2051 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2052 }
2053
2054 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2055 SourceLocation Loc) override {
2056 IsVLA = !VLAIsError;
2057 return S.Diag(Loc, VLADiag);
2058 }
2059
2060 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2061 SourceLocation Loc) override {
2062 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2063 }
2064 } Diagnoser(VLADiag, VLAIsError);
2065
2066 ExprResult R =
2067 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2068 if (Diagnoser.IsVLA)
2069 return ExprResult();
2070 return R;
2071}
2072
2074 EltTy = Context.getBaseElementType(EltTy);
2075 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2076 EltTy->isUndeducedType())
2077 return true;
2078
2079 CharUnits Size = Context.getTypeSizeInChars(EltTy);
2080 CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2081
2082 if (Size.isMultipleOf(Alignment))
2083 return true;
2084
2085 Diag(Loc, diag::err_array_element_alignment)
2086 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2087 return false;
2088}
2089
2091 Expr *ArraySize, unsigned Quals,
2092 SourceRange Brackets, DeclarationName Entity) {
2093
2094 SourceLocation Loc = Brackets.getBegin();
2095 if (getLangOpts().CPlusPlus) {
2096 // C++ [dcl.array]p1:
2097 // T is called the array element type; this type shall not be a reference
2098 // type, the (possibly cv-qualified) type void, a function type or an
2099 // abstract class type.
2100 //
2101 // C++ [dcl.array]p3:
2102 // When several "array of" specifications are adjacent, [...] only the
2103 // first of the constant expressions that specify the bounds of the arrays
2104 // may be omitted.
2105 //
2106 // Note: function types are handled in the common path with C.
2107 if (T->isReferenceType()) {
2108 Diag(Loc, diag::err_illegal_decl_array_of_references)
2109 << getPrintableNameForEntity(Entity) << T;
2110 return QualType();
2111 }
2112
2113 if (T->isVoidType() || T->isIncompleteArrayType()) {
2114 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2115 return QualType();
2116 }
2117
2118 if (RequireNonAbstractType(Brackets.getBegin(), T,
2119 diag::err_array_of_abstract_type))
2120 return QualType();
2121
2122 // Mentioning a member pointer type for an array type causes us to lock in
2123 // an inheritance model, even if it's inside an unused typedef.
2124 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2125 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2126 if (!MPTy->getQualifier().isDependent())
2127 (void)isCompleteType(Loc, T);
2128
2129 } else {
2130 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2131 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2132 if (!T.isWebAssemblyReferenceType() &&
2134 diag::err_array_incomplete_or_sizeless_type))
2135 return QualType();
2136 }
2137
2138 // Multi-dimensional arrays of WebAssembly references are not allowed.
2139 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2140 const auto *ATy = dyn_cast<ArrayType>(T);
2141 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2142 Diag(Loc, diag::err_wasm_reftype_multidimensional_array);
2143 return QualType();
2144 }
2145 }
2146
2147 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2148 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2149 return QualType();
2150 }
2151
2152 if (T->isFunctionType()) {
2153 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2154 << getPrintableNameForEntity(Entity) << T;
2155 return QualType();
2156 }
2157
2158 if (const auto *RD = T->getAsRecordDecl()) {
2159 // If the element type is a struct or union that contains a variadic
2160 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2161 if (RD->hasFlexibleArrayMember())
2162 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2163 } else if (T->isObjCObjectType()) {
2164 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2165 return QualType();
2166 }
2167
2168 if (!checkArrayElementAlignment(T, Loc))
2169 return QualType();
2170
2171 // Do placeholder conversions on the array size expression.
2172 if (ArraySize && ArraySize->hasPlaceholderType()) {
2174 if (Result.isInvalid()) return QualType();
2175 ArraySize = Result.get();
2176 }
2177
2178 // Do lvalue-to-rvalue conversions on the array size expression.
2179 if (ArraySize && !ArraySize->isPRValue()) {
2181 if (Result.isInvalid())
2182 return QualType();
2183
2184 ArraySize = Result.get();
2185 }
2186
2187 // C99 6.7.5.2p1: The size expression shall have integer type.
2188 // C++11 allows contextual conversions to such types.
2189 if (!getLangOpts().CPlusPlus11 &&
2190 ArraySize && !ArraySize->isTypeDependent() &&
2192 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2193 << ArraySize->getType() << ArraySize->getSourceRange();
2194 return QualType();
2195 }
2196
2197 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2198 if (!ArraySize)
2199 return false;
2200
2201 // If the array size expression is a conditional expression whose branches
2202 // are both integer constant expressions, one negative and one positive,
2203 // then it's assumed to be like an old-style static assertion. e.g.,
2204 // int old_style_assert[expr ? 1 : -1];
2205 // We will accept any integer constant expressions instead of assuming the
2206 // values 1 and -1 are always used.
2207 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2208 ArraySize->IgnoreParenImpCasts())) {
2209 std::optional<llvm::APSInt> LHS =
2210 CondExpr->getLHS()->getIntegerConstantExpr(Context);
2211 std::optional<llvm::APSInt> RHS =
2212 CondExpr->getRHS()->getIntegerConstantExpr(Context);
2213 return LHS && RHS && LHS->isNegative() != RHS->isNegative();
2214 }
2215 return false;
2216 };
2217
2218 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2219 unsigned VLADiag;
2220 bool VLAIsError;
2221 if (getLangOpts().OpenCL) {
2222 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2223 VLADiag = diag::err_opencl_vla;
2224 VLAIsError = true;
2225 } else if (getLangOpts().C99) {
2226 VLADiag = diag::warn_vla_used;
2227 VLAIsError = false;
2228 } else if (isSFINAEContext()) {
2229 VLADiag = diag::err_vla_in_sfinae;
2230 VLAIsError = true;
2231 } else if (getLangOpts().OpenMP && OpenMP().isInOpenMPTaskUntiedContext()) {
2232 VLADiag = diag::err_openmp_vla_in_task_untied;
2233 VLAIsError = true;
2234 } else if (getLangOpts().CPlusPlus) {
2235 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context))
2236 VLADiag = getLangOpts().GNUMode
2237 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2238 : diag::ext_vla_cxx_static_assert;
2239 else
2240 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode
2241 : diag::ext_vla_cxx;
2242 VLAIsError = false;
2243 } else {
2244 VLADiag = diag::ext_vla;
2245 VLAIsError = false;
2246 }
2247
2248 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2249 if (!ArraySize) {
2250 if (ASM == ArraySizeModifier::Star) {
2251 Diag(Loc, VLADiag);
2252 if (VLAIsError)
2253 return QualType();
2254
2255 T = Context.getVariableArrayType(T, nullptr, ASM, Quals);
2256 } else {
2257 T = Context.getIncompleteArrayType(T, ASM, Quals);
2258 }
2259 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2260 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals);
2261 } else {
2262 ExprResult R =
2263 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2264 if (R.isInvalid())
2265 return QualType();
2266
2267 if (!R.isUsable()) {
2268 // C99: an array with a non-ICE size is a VLA. We accept any expression
2269 // that we can fold to a non-zero positive value as a non-VLA as an
2270 // extension.
2271 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
2272 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2273 !T->isConstantSizeType()) {
2274 // C99: an array with an element type that has a non-constant-size is a
2275 // VLA.
2276 // FIXME: Add a note to explain why this isn't a VLA.
2277 Diag(Loc, VLADiag);
2278 if (VLAIsError)
2279 return QualType();
2280 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
2281 } else {
2282 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2283 // have a value greater than zero.
2284 // In C++, this follows from narrowing conversions being disallowed.
2285 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2286 if (Entity)
2287 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2288 << getPrintableNameForEntity(Entity)
2289 << ArraySize->getSourceRange();
2290 else
2291 Diag(ArraySize->getBeginLoc(),
2292 diag::err_typecheck_negative_array_size)
2293 << ArraySize->getSourceRange();
2294 return QualType();
2295 }
2296 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2297 if (getLangOpts().OpenCL) {
2298 Diag(ArraySize->getBeginLoc(), diag::err_typecheck_zero_array_size)
2299 << 3 << ArraySize->getSourceRange();
2300 return QualType();
2301 }
2302
2303 // GCC accepts zero sized static arrays. We allow them when
2304 // we're not in a SFINAE context.
2305 Diag(ArraySize->getBeginLoc(),
2306 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2307 : diag::ext_typecheck_zero_array_size)
2308 << 0 << ArraySize->getSourceRange();
2309 if (isSFINAEContext())
2310 return QualType();
2311 }
2312
2313 // Is the array too large?
2314 unsigned ActiveSizeBits =
2315 (!T->isDependentType() && !T->isVariablyModifiedType() &&
2316 !T->isIncompleteType() && !T->isUndeducedType())
2318 : ConstVal.getActiveBits();
2319 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2320 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2321 << toString(ConstVal, 10, ConstVal.isSigned(),
2322 /*formatAsCLiteral=*/false, /*UpperCase=*/false,
2323 /*InsertSeparators=*/true)
2324 << ArraySize->getSourceRange();
2325 return QualType();
2326 }
2327
2328 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2329 }
2330 }
2331
2332 if (T->isVariableArrayType()) {
2333 if (!Context.getTargetInfo().isVLASupported()) {
2334 // CUDA device code and some other targets don't support VLAs.
2335 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2336 targetDiag(Loc,
2337 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2338 << (IsCUDADevice ? llvm::to_underlying(CUDA().CurrentTarget()) : 0);
2339 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2340 // VLAs are supported on this target, but we may need to do delayed
2341 // checking that the VLA is not being used within a coroutine.
2342 FSI->setHasVLA(Loc);
2343 }
2344 }
2345
2346 // If this is not C99, diagnose array size modifiers on non-VLAs.
2347 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2348 (ASM != ArraySizeModifier::Normal || Quals != 0)) {
2349 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2350 : diag::ext_c99_array_usage)
2351 << ASM;
2352 }
2353
2354 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2355 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2356 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2357 if (getLangOpts().OpenCL) {
2358 const QualType ArrType = Context.getBaseElementType(T);
2359 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2360 ArrType->isSamplerT() || ArrType->isImageType()) {
2361 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2362 return QualType();
2363 }
2364 }
2365
2366 return T;
2367}
2368
2370 const BitIntType *BIT,
2371 bool ForMatrixType = false) {
2372 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2373 unsigned NumBits = BIT->getNumBits();
2374 if (!llvm::isPowerOf2_32(NumBits))
2375 return S.Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2376 << ForMatrixType;
2377 return false;
2378}
2379
2381 SourceLocation AttrLoc) {
2382 // The base type must be integer (not Boolean or enumeration) or float, and
2383 // can't already be a vector.
2384 if ((!CurType->isDependentType() &&
2385 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2386 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2387 !CurType->isBitIntType()) ||
2388 CurType->isArrayType()) {
2389 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2390 return QualType();
2391 }
2392
2393 if (const auto *BIT = CurType->getAs<BitIntType>();
2394 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2395 return QualType();
2396
2397 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2398 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2400
2401 std::optional<llvm::APSInt> VecSize =
2403 if (!VecSize) {
2404 Diag(AttrLoc, diag::err_attribute_argument_type)
2405 << "vector_size" << AANT_ArgumentIntegerConstant
2406 << SizeExpr->getSourceRange();
2407 return QualType();
2408 }
2409
2410 if (VecSize->isNegative()) {
2411 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2412 return QualType();
2413 }
2414
2415 if (CurType->isDependentType())
2416 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2418
2419 // vecSize is specified in bytes - convert to bits.
2420 if (!VecSize->isIntN(61)) {
2421 // Bit size will overflow uint64.
2422 Diag(AttrLoc, diag::err_attribute_size_too_large)
2423 << SizeExpr->getSourceRange() << "vector";
2424 return QualType();
2425 }
2426 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2427 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2428
2429 if (VectorSizeBits == 0) {
2430 Diag(AttrLoc, diag::err_attribute_zero_size)
2431 << SizeExpr->getSourceRange() << "vector";
2432 return QualType();
2433 }
2434
2435 if (!TypeSize || VectorSizeBits % TypeSize) {
2436 Diag(AttrLoc, diag::err_attribute_invalid_size)
2437 << SizeExpr->getSourceRange();
2438 return QualType();
2439 }
2440
2441 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2442 Diag(AttrLoc, diag::err_attribute_size_too_large)
2443 << SizeExpr->getSourceRange() << "vector";
2444 return QualType();
2445 }
2446
2447 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2449}
2450
2452 SourceLocation AttrLoc) {
2453 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2454 // in conjunction with complex types (pointers, arrays, functions, etc.).
2455 //
2456 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2457 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2458 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2459 // of bool aren't allowed.
2460 //
2461 // We explicitly allow bool elements in ext_vector_type for C/C++.
2462 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2463 if ((!T->isDependentType() && !T->isIntegerType() &&
2464 !T->isRealFloatingType()) ||
2465 (IsNoBoolVecLang && T->isBooleanType())) {
2466 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2467 return QualType();
2468 }
2469
2470 if (const auto *BIT = T->getAs<BitIntType>();
2471 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2472 return QualType();
2473
2474 if (!SizeExpr->isTypeDependent() && !SizeExpr->isValueDependent()) {
2475 std::optional<llvm::APSInt> VecSize =
2477 if (!VecSize) {
2478 Diag(AttrLoc, diag::err_attribute_argument_type)
2479 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2480 << SizeExpr->getSourceRange();
2481 return QualType();
2482 }
2483
2484 if (VecSize->isNegative()) {
2485 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2486 return QualType();
2487 }
2488
2489 if (!VecSize->isIntN(32)) {
2490 Diag(AttrLoc, diag::err_attribute_size_too_large)
2491 << SizeExpr->getSourceRange() << "vector";
2492 return QualType();
2493 }
2494 // Unlike gcc's vector_size attribute, the size is specified as the
2495 // number of elements, not the number of bytes.
2496 unsigned VectorSize = static_cast<unsigned>(VecSize->getZExtValue());
2497
2498 if (VectorSize == 0) {
2499 Diag(AttrLoc, diag::err_attribute_zero_size)
2500 << SizeExpr->getSourceRange() << "vector";
2501 return QualType();
2502 }
2503
2504 return Context.getExtVectorType(T, VectorSize);
2505 }
2506
2507 return Context.getDependentSizedExtVectorType(T, SizeExpr, AttrLoc);
2508}
2509
2510QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2511 SourceLocation AttrLoc) {
2512 assert(Context.getLangOpts().MatrixTypes &&
2513 "Should never build a matrix type when it is disabled");
2514
2515 // Check element type, if it is not dependent.
2516 if (!ElementTy->isDependentType() &&
2518 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2519 return QualType();
2520 }
2521
2522 if (const auto *BIT = ElementTy->getAs<BitIntType>();
2523 BIT &&
2524 CheckBitIntElementType(*this, AttrLoc, BIT, /*ForMatrixType=*/true))
2525 return QualType();
2526
2527 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2528 NumRows->isValueDependent() || NumCols->isValueDependent())
2529 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2530 AttrLoc);
2531
2532 std::optional<llvm::APSInt> ValueRows =
2534 std::optional<llvm::APSInt> ValueColumns =
2536
2537 auto const RowRange = NumRows->getSourceRange();
2538 auto const ColRange = NumCols->getSourceRange();
2539
2540 // Both are row and column expressions are invalid.
2541 if (!ValueRows && !ValueColumns) {
2542 Diag(AttrLoc, diag::err_attribute_argument_type)
2543 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2544 << ColRange;
2545 return QualType();
2546 }
2547
2548 // Only the row expression is invalid.
2549 if (!ValueRows) {
2550 Diag(AttrLoc, diag::err_attribute_argument_type)
2551 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2552 return QualType();
2553 }
2554
2555 // Only the column expression is invalid.
2556 if (!ValueColumns) {
2557 Diag(AttrLoc, diag::err_attribute_argument_type)
2558 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2559 return QualType();
2560 }
2561
2562 // Check the matrix dimensions.
2563 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2564 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2565 if (MatrixRows == 0 && MatrixColumns == 0) {
2566 Diag(AttrLoc, diag::err_attribute_zero_size)
2567 << "matrix" << RowRange << ColRange;
2568 return QualType();
2569 }
2570 if (MatrixRows == 0) {
2571 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2572 return QualType();
2573 }
2574 if (MatrixColumns == 0) {
2575 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2576 return QualType();
2577 }
2578 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension &&
2579 MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2580 Diag(AttrLoc, diag::err_attribute_size_too_large)
2581 << RowRange << ColRange << "matrix row and column";
2582 return QualType();
2583 }
2584 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension) {
2585 Diag(AttrLoc, diag::err_attribute_size_too_large)
2586 << RowRange << "matrix row";
2587 return QualType();
2588 }
2589 if (MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2590 Diag(AttrLoc, diag::err_attribute_size_too_large)
2591 << ColRange << "matrix column";
2592 return QualType();
2593 }
2594 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2595}
2596
2598 if ((T->isArrayType() && !getLangOpts().allowArrayReturnTypes()) ||
2599 T->isFunctionType()) {
2600 Diag(Loc, diag::err_func_returning_array_function)
2601 << T->isFunctionType() << T;
2602 return true;
2603 }
2604
2605 // Functions cannot return half FP.
2606 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2607 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2608 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2610 return true;
2611 }
2612
2613 // Methods cannot return interface types. All ObjC objects are
2614 // passed by reference.
2615 if (T->isObjCObjectType()) {
2616 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2617 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2618 return true;
2619 }
2620
2621 // __ptrauth is illegal on a function return type.
2622 if (T.getPointerAuth()) {
2623 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
2624 return true;
2625 }
2626
2627 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2628 T.hasNonTrivialToPrimitiveCopyCUnion())
2631
2632 // C++2a [dcl.fct]p12:
2633 // A volatile-qualified return type is deprecated
2634 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2635 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2636
2637 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2638 return true;
2639 return false;
2640}
2641
2642/// Check the extended parameter information. Most of the necessary
2643/// checking should occur when applying the parameter attribute; the
2644/// only other checks required are positional restrictions.
2647 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2648 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2649
2650 bool emittedError = false;
2651 auto actualCC = EPI.ExtInfo.getCC();
2652 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2653 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2654 bool isCompatible =
2655 (required == RequiredCC::OnlySwift)
2656 ? (actualCC == CC_Swift)
2657 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2658 if (isCompatible || emittedError)
2659 return;
2660 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2662 << (required == RequiredCC::OnlySwift);
2663 emittedError = true;
2664 };
2665 for (size_t paramIndex = 0, numParams = paramTypes.size();
2666 paramIndex != numParams; ++paramIndex) {
2667 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2668 // Nothing interesting to check for orindary-ABI parameters.
2672 continue;
2673
2674 // swift_indirect_result parameters must be a prefix of the function
2675 // arguments.
2677 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2678 if (paramIndex != 0 &&
2679 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2681 S.Diag(getParamLoc(paramIndex),
2682 diag::err_swift_indirect_result_not_first);
2683 }
2684 continue;
2685
2687 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2688 continue;
2689
2690 // SwiftAsyncContext is not limited to swiftasynccall functions.
2692 continue;
2693
2694 // swift_error parameters must be preceded by a swift_context parameter.
2696 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2697 if (paramIndex == 0 ||
2698 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2700 S.Diag(getParamLoc(paramIndex),
2701 diag::err_swift_error_result_not_after_swift_context);
2702 }
2703 continue;
2704 }
2705 llvm_unreachable("bad ABI kind");
2706 }
2707}
2708
2710 MutableArrayRef<QualType> ParamTypes,
2711 SourceLocation Loc, DeclarationName Entity,
2713 bool Invalid = false;
2714
2716
2717 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2718 // FIXME: Loc is too inprecise here, should use proper locations for args.
2719 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2720 if (ParamType->isVoidType()) {
2721 Diag(Loc, diag::err_param_with_void_type);
2722 Invalid = true;
2723 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2724 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2725 // Disallow half FP arguments.
2726 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2728 Invalid = true;
2729 } else if (ParamType->isWebAssemblyTableType()) {
2730 Diag(Loc, diag::err_wasm_table_as_function_parameter);
2731 Invalid = true;
2732 } else if (ParamType.getPointerAuth()) {
2733 // __ptrauth is illegal on a function return type.
2734 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 1;
2735 Invalid = true;
2736 }
2737
2738 // C++2a [dcl.fct]p4:
2739 // A parameter with volatile-qualified type is deprecated
2740 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2741 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2742
2743 ParamTypes[Idx] = ParamType;
2744 }
2745
2746 if (EPI.ExtParameterInfos) {
2747 checkExtParameterInfos(*this, ParamTypes, EPI,
2748 [=](unsigned i) { return Loc; });
2749 }
2750
2751 if (EPI.ExtInfo.getProducesResult()) {
2752 // This is just a warning, so we can't fail to build if we see it.
2754 }
2755
2756 if (Invalid)
2757 return QualType();
2758
2759 return Context.getFunctionType(T, ParamTypes, EPI);
2760}
2761
2763 CXXRecordDecl *Cls, SourceLocation Loc,
2764 DeclarationName Entity) {
2765 if (!Cls && !isDependentScopeSpecifier(SS)) {
2766 Cls = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS));
2767 if (!Cls) {
2768 auto D =
2769 Diag(SS.getBeginLoc(), diag::err_illegal_decl_mempointer_in_nonclass)
2770 << SS.getRange();
2771 if (const IdentifierInfo *II = Entity.getAsIdentifierInfo())
2772 D << II;
2773 else
2774 D << "member pointer";
2775 return QualType();
2776 }
2777 }
2778
2779 // Verify that we're not building a pointer to pointer to function with
2780 // exception specification.
2782 Diag(Loc, diag::err_distant_exception_spec);
2783 return QualType();
2784 }
2785
2786 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2787 // with reference type, or "cv void."
2788 if (T->isReferenceType()) {
2789 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2790 << getPrintableNameForEntity(Entity) << T;
2791 return QualType();
2792 }
2793
2794 if (T->isVoidType()) {
2795 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2796 << getPrintableNameForEntity(Entity);
2797 return QualType();
2798 }
2799
2800 if (T->isFunctionType() && getLangOpts().OpenCL &&
2801 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2802 getLangOpts())) {
2803 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2804 return QualType();
2805 }
2806
2807 if (getLangOpts().HLSL && Loc.isValid()) {
2808 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2809 return QualType();
2810 }
2811
2812 // Adjust the default free function calling convention to the default method
2813 // calling convention.
2814 bool IsCtorOrDtor =
2817 if (T->isFunctionType())
2818 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
2819
2820 return Context.getMemberPointerType(T, SS.getScopeRep(), Cls);
2821}
2822
2824 SourceLocation Loc,
2825 DeclarationName Entity) {
2826 if (!T->isFunctionType()) {
2827 Diag(Loc, diag::err_nonfunction_block_type);
2828 return QualType();
2829 }
2830
2831 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2832 return QualType();
2833
2834 if (getLangOpts().OpenCL)
2835 T = deduceOpenCLPointeeAddrSpace(*this, T);
2836
2837 return Context.getBlockPointerType(T);
2838}
2839
2841 QualType QT = Ty.get();
2842 if (QT.isNull()) {
2843 if (TInfo) *TInfo = nullptr;
2844 return QualType();
2845 }
2846
2847 TypeSourceInfo *TSI = nullptr;
2848 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2849 QT = LIT->getType();
2850 TSI = LIT->getTypeSourceInfo();
2851 }
2852
2853 if (TInfo)
2854 *TInfo = TSI;
2855 return QT;
2856}
2857
2858static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2859 Qualifiers::ObjCLifetime ownership,
2860 unsigned chunkIndex);
2861
2862/// Given that this is the declaration of a parameter under ARC,
2863/// attempt to infer attributes and such for pointer-to-whatever
2864/// types.
2865static void inferARCWriteback(TypeProcessingState &state,
2866 QualType &declSpecType) {
2867 Sema &S = state.getSema();
2868 Declarator &declarator = state.getDeclarator();
2869
2870 // TODO: should we care about decl qualifiers?
2871
2872 // Check whether the declarator has the expected form. We walk
2873 // from the inside out in order to make the block logic work.
2874 unsigned outermostPointerIndex = 0;
2875 bool isBlockPointer = false;
2876 unsigned numPointers = 0;
2877 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2878 unsigned chunkIndex = i;
2879 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2880 switch (chunk.Kind) {
2882 // Ignore parens.
2883 break;
2884
2887 // Count the number of pointers. Treat references
2888 // interchangeably as pointers; if they're mis-ordered, normal
2889 // type building will discover that.
2890 outermostPointerIndex = chunkIndex;
2891 numPointers++;
2892 break;
2893
2895 // If we have a pointer to block pointer, that's an acceptable
2896 // indirect reference; anything else is not an application of
2897 // the rules.
2898 if (numPointers != 1) return;
2899 numPointers++;
2900 outermostPointerIndex = chunkIndex;
2901 isBlockPointer = true;
2902
2903 // We don't care about pointer structure in return values here.
2904 goto done;
2905
2906 case DeclaratorChunk::Array: // suppress if written (id[])?
2910 return;
2911 }
2912 }
2913 done:
2914
2915 // If we have *one* pointer, then we want to throw the qualifier on
2916 // the declaration-specifiers, which means that it needs to be a
2917 // retainable object type.
2918 if (numPointers == 1) {
2919 // If it's not a retainable object type, the rule doesn't apply.
2920 if (!declSpecType->isObjCRetainableType()) return;
2921
2922 // If it already has lifetime, don't do anything.
2923 if (declSpecType.getObjCLifetime()) return;
2924
2925 // Otherwise, modify the type in-place.
2926 Qualifiers qs;
2927
2928 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2930 else
2932 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2933
2934 // If we have *two* pointers, then we want to throw the qualifier on
2935 // the outermost pointer.
2936 } else if (numPointers == 2) {
2937 // If we don't have a block pointer, we need to check whether the
2938 // declaration-specifiers gave us something that will turn into a
2939 // retainable object pointer after we slap the first pointer on it.
2940 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2941 return;
2942
2943 // Look for an explicit lifetime attribute there.
2944 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2945 if (chunk.Kind != DeclaratorChunk::Pointer &&
2947 return;
2948 for (const ParsedAttr &AL : chunk.getAttrs())
2949 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2950 return;
2951
2953 outermostPointerIndex);
2954
2955 // Any other number of pointers/references does not trigger the rule.
2956 } else return;
2957
2958 // TODO: mark whether we did this inference?
2959}
2960
2961void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2962 SourceLocation FallbackLoc,
2963 SourceLocation ConstQualLoc,
2964 SourceLocation VolatileQualLoc,
2965 SourceLocation RestrictQualLoc,
2966 SourceLocation AtomicQualLoc,
2967 SourceLocation UnalignedQualLoc) {
2968 if (!Quals)
2969 return;
2970
2971 struct Qual {
2972 const char *Name;
2973 unsigned Mask;
2974 SourceLocation Loc;
2975 } const QualKinds[5] = {
2976 { "const", DeclSpec::TQ_const, ConstQualLoc },
2977 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2978 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2979 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2980 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2981 };
2982
2983 SmallString<32> QualStr;
2984 unsigned NumQuals = 0;
2985 SourceLocation Loc;
2986 FixItHint FixIts[5];
2987
2988 // Build a string naming the redundant qualifiers.
2989 for (auto &E : QualKinds) {
2990 if (Quals & E.Mask) {
2991 if (!QualStr.empty()) QualStr += ' ';
2992 QualStr += E.Name;
2993
2994 // If we have a location for the qualifier, offer a fixit.
2995 SourceLocation QualLoc = E.Loc;
2996 if (QualLoc.isValid()) {
2997 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2998 if (Loc.isInvalid() ||
2999 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
3000 Loc = QualLoc;
3001 }
3002
3003 ++NumQuals;
3004 }
3005 }
3006
3007 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3008 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3009}
3010
3011// Diagnose pointless type qualifiers on the return type of a function.
3013 Declarator &D,
3014 unsigned FunctionChunkIndex) {
3016 D.getTypeObject(FunctionChunkIndex).Fun;
3017 if (FTI.hasTrailingReturnType()) {
3018 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3019 RetTy.getLocalCVRQualifiers(),
3021 return;
3022 }
3023
3024 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3025 End = D.getNumTypeObjects();
3026 OuterChunkIndex != End; ++OuterChunkIndex) {
3027 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3028 switch (OuterChunk.Kind) {
3030 continue;
3031
3033 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3035 diag::warn_qual_return_type,
3036 PTI.TypeQuals,
3038 PTI.ConstQualLoc,
3039 PTI.VolatileQualLoc,
3040 PTI.RestrictQualLoc,
3041 PTI.AtomicQualLoc,
3042 PTI.UnalignedQualLoc);
3043 return;
3044 }
3045
3052 // FIXME: We can't currently provide an accurate source location and a
3053 // fix-it hint for these.
3054 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3055 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3056 RetTy.getCVRQualifiers() | AtomicQual,
3057 D.getIdentifierLoc());
3058 return;
3059 }
3060
3061 llvm_unreachable("unknown declarator chunk kind");
3062 }
3063
3064 // If the qualifiers come from a conversion function type, don't diagnose
3065 // them -- they're not necessarily redundant, since such a conversion
3066 // operator can be explicitly called as "x.operator const int()".
3068 return;
3069
3070 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3071 // which are present there.
3072 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3074 D.getIdentifierLoc(),
3080}
3081
3082static std::pair<QualType, TypeSourceInfo *>
3083InventTemplateParameter(TypeProcessingState &state, QualType T,
3084 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3086 Sema &S = state.getSema();
3087 Declarator &D = state.getDeclarator();
3088
3089 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3090 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3091 const bool IsParameterPack = D.hasEllipsis();
3092
3093 // If auto is mentioned in a lambda parameter or abbreviated function
3094 // template context, convert it to a template parameter type.
3095
3096 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3097 // template parameter type. Template parameters are temporarily added
3098 // to the TU until the associated TemplateDecl is created.
3099 TemplateTypeParmDecl *InventedTemplateParam =
3102 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3103 /*NameLoc=*/D.getIdentifierLoc(),
3104 TemplateParameterDepth, AutoParameterPosition,
3106 D.getIdentifier(), AutoParameterPosition), false,
3107 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3108 InventedTemplateParam->setImplicit();
3109 Info.TemplateParams.push_back(InventedTemplateParam);
3110
3111 // Attach type constraints to the new parameter.
3112 if (Auto->isConstrained()) {
3113 if (TrailingTSI) {
3114 // The 'auto' appears in a trailing return type we've already built;
3115 // extract its type constraints to attach to the template parameter.
3116 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3117 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3118 bool Invalid = false;
3119 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3120 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3123 Invalid = true;
3124 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3125 }
3126
3127 if (!Invalid) {
3129 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3130 AutoLoc.getNamedConcept(), /*FoundDecl=*/AutoLoc.getFoundDecl(),
3131 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3132 InventedTemplateParam, D.getEllipsisLoc());
3133 }
3134 } else {
3135 // The 'auto' appears in the decl-specifiers; we've not finished forming
3136 // TypeSourceInfo for it yet.
3138 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
3139 TemplateId->RAngleLoc);
3140 bool Invalid = false;
3141 if (TemplateId->LAngleLoc.isValid()) {
3142 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3143 TemplateId->NumArgs);
3144 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3145
3146 if (D.getEllipsisLoc().isInvalid()) {
3147 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3150 Invalid = true;
3151 break;
3152 }
3153 }
3154 }
3155 }
3156 if (!Invalid) {
3157 UsingShadowDecl *USD =
3158 TemplateId->Template.get().getAsUsingShadowDecl();
3159 TemplateDecl *CD = TemplateId->Template.get().getAsTemplateDecl();
3163 TemplateId->TemplateNameLoc),
3164 CD,
3165 /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
3166 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3167 InventedTemplateParam, D.getEllipsisLoc());
3168 }
3169 }
3170 }
3171
3172 // Replace the 'auto' in the function parameter with this invented
3173 // template type parameter.
3174 // FIXME: Retain some type sugar to indicate that this was written
3175 // as 'auto'?
3176 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3177 QualType NewT = state.ReplaceAutoType(T, Replacement);
3178 TypeSourceInfo *NewTSI =
3179 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3180 : nullptr;
3181 return {NewT, NewTSI};
3182}
3183
3184static TypeSourceInfo *
3185GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3186 QualType T, TypeSourceInfo *ReturnTypeInfo);
3187
3188static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3189 TypeSourceInfo *&ReturnTypeInfo) {
3190 Sema &SemaRef = state.getSema();
3191 Declarator &D = state.getDeclarator();
3192 QualType T;
3193 ReturnTypeInfo = nullptr;
3194
3195 // The TagDecl owned by the DeclSpec.
3196 TagDecl *OwnedTagDecl = nullptr;
3197
3198 switch (D.getName().getKind()) {
3204 T = ConvertDeclSpecToType(state);
3205
3206 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3207 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3208 // Owned declaration is embedded in declarator.
3209 OwnedTagDecl->setEmbeddedInDeclarator(true);
3210 }
3211 break;
3212
3216 // Constructors and destructors don't have return types. Use
3217 // "void" instead.
3218 T = SemaRef.Context.VoidTy;
3221 break;
3222
3224 // Deduction guides have a trailing return type and no type in their
3225 // decl-specifier sequence. Use a placeholder return type for now.
3226 T = SemaRef.Context.DependentTy;
3227 break;
3228
3230 // The result type of a conversion function is the type that it
3231 // converts to.
3233 &ReturnTypeInfo);
3234 break;
3235 }
3236
3237 // Note: We don't need to distribute declaration attributes (i.e.
3238 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3239 // and those don't get distributed.
3241 state, T, SemaRef.CUDA().IdentifyTarget(D.getAttributes()));
3242
3243 // Find the deduced type in this type. Look in the trailing return type if we
3244 // have one, otherwise in the DeclSpec type.
3245 // FIXME: The standard wording doesn't currently describe this.
3246 DeducedType *Deduced = T->getContainedDeducedType();
3247 bool DeducedIsTrailingReturnType = false;
3250 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3251 DeducedIsTrailingReturnType = true;
3252 }
3253
3254 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3255 if (Deduced) {
3256 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3257 int Error = -1;
3258
3259 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3260 // class template argument deduction)?
3261 bool IsCXXAutoType =
3262 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3263 bool IsDeducedReturnType = false;
3264
3265 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3267 AutoRange = D.getName().getSourceRange();
3268
3269 switch (D.getContext()) {
3271 // Declared return type of a lambda-declarator is implicit and is always
3272 // 'auto'.
3273 break;
3276 Error = 0;
3277 break;
3279 Error = 22;
3280 break;
3283 InventedTemplateParameterInfo *Info = nullptr;
3285 // With concepts we allow 'auto' in function parameters.
3286 if (!SemaRef.getLangOpts().CPlusPlus || !Auto ||
3287 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3288 Error = 0;
3289 break;
3290 }
3291
3292 if (!SemaRef.getLangOpts().CPlusPlus20)
3293 SemaRef.DiagCompat(AutoRange.getBegin(), diag_compat::auto_param);
3294
3295 if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3296 Error = 21;
3297 break;
3298 }
3299
3300 Info = &SemaRef.InventedParameterInfos.back();
3301 } else {
3302 // In C++14, generic lambdas allow 'auto' in their parameters.
3303 if (!SemaRef.getLangOpts().CPlusPlus14 && Auto &&
3304 Auto->getKeyword() == AutoTypeKeyword::Auto) {
3305 Error = 25; // auto not allowed in lambda parameter (before C++14)
3306 break;
3307 } else if (!Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) {
3308 Error = 16; // __auto_type or decltype(auto) not allowed in lambda
3309 // parameter
3310 break;
3311 }
3312 Info = SemaRef.getCurLambda();
3313 assert(Info && "No LambdaScopeInfo on the stack!");
3314 }
3315
3316 // We'll deal with inventing template parameters for 'auto' in trailing
3317 // return types when we pick up the trailing return type when processing
3318 // the function chunk.
3319 if (!DeducedIsTrailingReturnType)
3320 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3321 break;
3322 }
3324 if (D.isStaticMember() || D.isFunctionDeclarator())
3325 break;
3326 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3327 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3328 Error = 6; // Interface member.
3329 } else {
3330 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3331 case TagTypeKind::Enum:
3332 llvm_unreachable("unhandled tag kind");
3334 Error = Cxx ? 1 : 2; /* Struct member */
3335 break;
3336 case TagTypeKind::Union:
3337 Error = Cxx ? 3 : 4; /* Union member */
3338 break;
3339 case TagTypeKind::Class:
3340 Error = 5; /* Class member */
3341 break;
3343 Error = 6; /* Interface member */
3344 break;
3345 }
3346 }
3348 Error = 20; // Friend type
3349 break;
3350 }
3353 Error = 7; // Exception declaration
3354 break;
3357 !SemaRef.getLangOpts().CPlusPlus20)
3358 Error = 19; // Template parameter (until C++20)
3359 else if (!SemaRef.getLangOpts().CPlusPlus17)
3360 Error = 8; // Template parameter (until C++17)
3361 break;
3363 Error = 9; // Block literal
3364 break;
3366 // Within a template argument list, a deduced template specialization
3367 // type will be reinterpreted as a template template argument.
3369 !D.getNumTypeObjects() &&
3371 break;
3372 [[fallthrough]];
3374 Error = 10; // Template type argument
3375 break;
3378 Error = 12; // Type alias
3379 break;
3382 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3383 Error = 13; // Function return type
3384 IsDeducedReturnType = true;
3385 break;
3387 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3388 Error = 14; // conversion-type-id
3389 IsDeducedReturnType = true;
3390 break;
3393 break;
3394 if (SemaRef.getLangOpts().CPlusPlus23 && IsCXXAutoType &&
3395 !Auto->isDecltypeAuto())
3396 break; // auto(x)
3397 [[fallthrough]];
3400 Error = 15; // Generic
3401 break;
3407 // FIXME: P0091R3 (erroneously) does not permit class template argument
3408 // deduction in conditions, for-init-statements, and other declarations
3409 // that are not simple-declarations.
3410 break;
3412 // FIXME: P0091R3 does not permit class template argument deduction here,
3413 // but we follow GCC and allow it anyway.
3414 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3415 Error = 17; // 'new' type
3416 break;
3418 Error = 18; // K&R function parameter
3419 break;
3420 }
3421
3423 Error = 11;
3424
3425 // In Objective-C it is an error to use 'auto' on a function declarator
3426 // (and everywhere for '__auto_type').
3427 if (D.isFunctionDeclarator() &&
3428 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3429 Error = 13;
3430
3431 if (Error != -1) {
3432 unsigned Kind;
3433 if (Auto) {
3434 switch (Auto->getKeyword()) {
3435 case AutoTypeKeyword::Auto: Kind = 0; break;
3436 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3437 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3438 }
3439 } else {
3441 "unknown auto type");
3442 Kind = 3;
3443 }
3444
3445 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3446 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3447
3448 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3449 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3450 << QualType(Deduced, 0) << AutoRange;
3451 if (auto *TD = TN.getAsTemplateDecl())
3452 SemaRef.NoteTemplateLocation(*TD);
3453
3454 T = SemaRef.Context.IntTy;
3455 D.setInvalidType(true);
3456 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3457 // If there was a trailing return type, we already got
3458 // warn_cxx98_compat_trailing_return_type in the parser.
3459 // If there was a decltype(auto), we already got
3460 // warn_cxx11_compat_decltype_auto_type_specifier.
3461 unsigned DiagId = 0;
3463 DiagId = diag::warn_cxx11_compat_generic_lambda;
3464 else if (IsDeducedReturnType)
3465 DiagId = diag::warn_cxx11_compat_deduced_return_type;
3466 else if (Auto->getKeyword() == AutoTypeKeyword::Auto)
3467 DiagId = diag::warn_cxx98_compat_auto_type_specifier;
3468
3469 if (DiagId)
3470 SemaRef.Diag(AutoRange.getBegin(), DiagId) << AutoRange;
3471 }
3472 }
3473
3474 if (SemaRef.getLangOpts().CPlusPlus &&
3475 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3476 // Check the contexts where C++ forbids the declaration of a new class
3477 // or enumeration in a type-specifier-seq.
3478 unsigned DiagID = 0;
3479 switch (D.getContext()) {
3482 // Class and enumeration definitions are syntactically not allowed in
3483 // trailing return types.
3484 llvm_unreachable("parser should not have allowed this");
3485 break;
3493 // C++11 [dcl.type]p3:
3494 // A type-specifier-seq shall not define a class or enumeration unless
3495 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3496 // the declaration of a template-declaration.
3498 break;
3500 DiagID = diag::err_type_defined_in_alias_template;
3501 break;
3512 DiagID = diag::err_type_defined_in_type_specifier;
3513 break;
3520 // C++ [dcl.fct]p6:
3521 // Types shall not be defined in return or parameter types.
3522 DiagID = diag::err_type_defined_in_param_type;
3523 break;
3525 // C++ 6.4p2:
3526 // The type-specifier-seq shall not contain typedef and shall not declare
3527 // a new class or enumeration.
3528 DiagID = diag::err_type_defined_in_condition;
3529 break;
3530 }
3531
3532 if (DiagID != 0) {
3533 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3534 << SemaRef.Context.getCanonicalTagType(OwnedTagDecl);
3535 D.setInvalidType(true);
3536 }
3537 }
3538
3539 assert(!T.isNull() && "This function should not return a null type");
3540 return T;
3541}
3542
3543/// Produce an appropriate diagnostic for an ambiguity between a function
3544/// declarator and a C++ direct-initializer.
3546 DeclaratorChunk &DeclType, QualType RT) {
3547 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3548 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3549
3550 // If the return type is void there is no ambiguity.
3551 if (RT->isVoidType())
3552 return;
3553
3554 // An initializer for a non-class type can have at most one argument.
3555 if (!RT->isRecordType() && FTI.NumParams > 1)
3556 return;
3557
3558 // An initializer for a reference must have exactly one argument.
3559 if (RT->isReferenceType() && FTI.NumParams != 1)
3560 return;
3561
3562 // Only warn if this declarator is declaring a function at block scope, and
3563 // doesn't have a storage class (such as 'extern') specified.
3564 if (!D.isFunctionDeclarator() ||
3568 return;
3569
3570 // Inside a condition, a direct initializer is not permitted. We allow one to
3571 // be parsed in order to give better diagnostics in condition parsing.
3573 return;
3574
3575 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3576
3577 S.Diag(DeclType.Loc,
3578 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3579 : diag::warn_empty_parens_are_function_decl)
3580 << ParenRange;
3581
3582 // If the declaration looks like:
3583 // T var1,
3584 // f();
3585 // and name lookup finds a function named 'f', then the ',' was
3586 // probably intended to be a ';'.
3587 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3588 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3590 if (Comma.getFileID() != Name.getFileID() ||
3591 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3594 if (S.LookupName(Result, S.getCurScope()))
3595 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3597 << D.getIdentifier();
3598 Result.suppressDiagnostics();
3599 }
3600 }
3601
3602 if (FTI.NumParams > 0) {
3603 // For a declaration with parameters, eg. "T var(T());", suggest adding
3604 // parens around the first parameter to turn the declaration into a
3605 // variable declaration.
3606 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3607 SourceLocation B = Range.getBegin();
3608 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3609 // FIXME: Maybe we should suggest adding braces instead of parens
3610 // in C++11 for classes that don't have an initializer_list constructor.
3611 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3613 << FixItHint::CreateInsertion(E, ")");
3614 } else {
3615 // For a declaration without parameters, eg. "T var();", suggest replacing
3616 // the parens with an initializer to turn the declaration into a variable
3617 // declaration.
3618 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3619
3620 // Empty parens mean value-initialization, and no parens mean
3621 // default initialization. These are equivalent if the default
3622 // constructor is user-provided or if zero-initialization is a
3623 // no-op.
3624 if (RD && RD->hasDefinition() &&
3626 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3627 << FixItHint::CreateRemoval(ParenRange);
3628 else {
3629 std::string Init =
3630 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3631 if (Init.empty() && S.LangOpts.CPlusPlus11)
3632 Init = "{}";
3633 if (!Init.empty())
3634 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3635 << FixItHint::CreateReplacement(ParenRange, Init);
3636 }
3637 }
3638}
3639
3640/// Produce an appropriate diagnostic for a declarator with top-level
3641/// parentheses.
3644 assert(Paren.Kind == DeclaratorChunk::Paren &&
3645 "do not have redundant top-level parentheses");
3646
3647 // This is a syntactic check; we're not interested in cases that arise
3648 // during template instantiation.
3650 return;
3651
3652 // Check whether this could be intended to be a construction of a temporary
3653 // object in C++ via a function-style cast.
3654 bool CouldBeTemporaryObject =
3655 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3656 !D.isInvalidType() && D.getIdentifier() &&
3658 (T->isRecordType() || T->isDependentType()) &&
3660
3661 bool StartsWithDeclaratorId = true;
3662 for (auto &C : D.type_objects()) {
3663 switch (C.Kind) {
3665 if (&C == &Paren)
3666 continue;
3667 [[fallthrough]];
3669 StartsWithDeclaratorId = false;
3670 continue;
3671
3673 if (!C.Arr.NumElts)
3674 CouldBeTemporaryObject = false;
3675 continue;
3676
3678 // FIXME: Suppress the warning here if there is no initializer; we're
3679 // going to give an error anyway.
3680 // We assume that something like 'T (&x) = y;' is highly likely to not
3681 // be intended to be a temporary object.
3682 CouldBeTemporaryObject = false;
3683 StartsWithDeclaratorId = false;
3684 continue;
3685
3687 // In a new-type-id, function chunks require parentheses.
3689 return;
3690 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3691 // redundant-parens warning, but we don't know whether the function
3692 // chunk was syntactically valid as an expression here.
3693 CouldBeTemporaryObject = false;
3694 continue;
3695
3699 // These cannot appear in expressions.
3700 CouldBeTemporaryObject = false;
3701 StartsWithDeclaratorId = false;
3702 continue;
3703 }
3704 }
3705
3706 // FIXME: If there is an initializer, assume that this is not intended to be
3707 // a construction of a temporary object.
3708
3709 // Check whether the name has already been declared; if not, this is not a
3710 // function-style cast.
3711 if (CouldBeTemporaryObject) {
3714 if (!S.LookupName(Result, S.getCurScope()))
3715 CouldBeTemporaryObject = false;
3716 Result.suppressDiagnostics();
3717 }
3718
3719 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3720
3721 if (!CouldBeTemporaryObject) {
3722 // If we have A (::B), the parentheses affect the meaning of the program.
3723 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3724 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3725 // formally unambiguous.
3726 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3728 for (;;) {
3729 switch (NNS.getKind()) {
3731 return;
3733 NNS = NNS.getAsType()->getPrefix();
3734 continue;
3736 NNS = NNS.getAsNamespaceAndPrefix().Prefix;
3737 continue;
3738 default:
3739 goto out;
3740 }
3741 }
3742 out:;
3743 }
3744
3745 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3746 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3748 return;
3749 }
3750
3751 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3752 << ParenRange << D.getIdentifier();
3753 auto *RD = T->getAsCXXRecordDecl();
3754 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3755 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3756 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3757 << D.getIdentifier();
3758 // FIXME: A cast to void is probably a better suggestion in cases where it's
3759 // valid (when there is no initializer and we're not in a condition).
3760 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3763 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3766}
3767
3768/// Helper for figuring out the default CC for a function declarator type. If
3769/// this is the outermost chunk, then we can determine the CC from the
3770/// declarator context. If not, then this could be either a member function
3771/// type or normal function type.
3773 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3774 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3775 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3776
3777 // Check for an explicit CC attribute.
3778 for (const ParsedAttr &AL : AttrList) {
3779 switch (AL.getKind()) {
3781 // Ignore attributes that don't validate or can't apply to the
3782 // function type. We'll diagnose the failure to apply them in
3783 // handleFunctionTypeAttr.
3784 CallingConv CC;
3785 if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr,
3786 S.CUDA().IdentifyTarget(D.getAttributes())) &&
3787 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3788 return CC;
3789 }
3790 break;
3791 }
3792
3793 default:
3794 break;
3795 }
3796 }
3797
3798 bool IsCXXInstanceMethod = false;
3799
3800 if (S.getLangOpts().CPlusPlus) {
3801 // Look inwards through parentheses to see if this chunk will form a
3802 // member pointer type or if we're the declarator. Any type attributes
3803 // between here and there will override the CC we choose here.
3804 unsigned I = ChunkIndex;
3805 bool FoundNonParen = false;
3806 while (I && !FoundNonParen) {
3807 --I;
3809 FoundNonParen = true;
3810 }
3811
3812 if (FoundNonParen) {
3813 // If we're not the declarator, we're a regular function type unless we're
3814 // in a member pointer.
3815 IsCXXInstanceMethod =
3817 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3818 // This can only be a call operator for a lambda, which is an instance
3819 // method, unless explicitly specified as 'static'.
3820 IsCXXInstanceMethod =
3822 } else {
3823 // We're the innermost decl chunk, so must be a function declarator.
3824 assert(D.isFunctionDeclarator());
3825
3826 // If we're inside a record, we're declaring a method, but it could be
3827 // explicitly or implicitly static.
3828 IsCXXInstanceMethod =
3831 !D.isStaticMember();
3832 }
3833 }
3834
3836 IsCXXInstanceMethod);
3837
3838 if (S.getLangOpts().CUDA) {
3839 // If we're compiling CUDA/HIP code and targeting HIPSPV we need to make
3840 // sure the kernels will be marked with the right calling convention so that
3841 // they will be visible by the APIs that ingest SPIR-V. We do not do this
3842 // when targeting AMDGCNSPIRV, as it does not rely on OpenCL.
3843 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
3844 if (Triple.isSPIRV() && Triple.getVendor() != llvm::Triple::AMD) {
3845 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3846 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
3847 CC = CC_DeviceKernel;
3848 break;
3849 }
3850 }
3851 }
3852 }
3853
3854 for (const ParsedAttr &AL : llvm::concat<ParsedAttr>(
3857 if (AL.getKind() == ParsedAttr::AT_DeviceKernel) {
3858 CC = CC_DeviceKernel;
3859 break;
3860 }
3861 }
3862 return CC;
3863}
3864
3865namespace {
3866 /// A simple notion of pointer kinds, which matches up with the various
3867 /// pointer declarators.
3868 enum class SimplePointerKind {
3869 Pointer,
3870 BlockPointer,
3871 MemberPointer,
3872 Array,
3873 };
3874} // end anonymous namespace
3875
3877 switch (nullability) {
3879 if (!Ident__Nonnull)
3880 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3881 return Ident__Nonnull;
3882
3884 if (!Ident__Nullable)
3885 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3886 return Ident__Nullable;
3887
3889 if (!Ident__Nullable_result)
3890 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
3891 return Ident__Nullable_result;
3892
3894 if (!Ident__Null_unspecified)
3895 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3896 return Ident__Null_unspecified;
3897 }
3898 llvm_unreachable("Unknown nullability kind.");
3899}
3900
3901/// Check whether there is a nullability attribute of any kind in the given
3902/// attribute list.
3903static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3904 for (const ParsedAttr &AL : attrs) {
3905 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3906 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3907 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
3908 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3909 return true;
3910 }
3911
3912 return false;
3913}
3914
3915namespace {
3916 /// Describes the kind of a pointer a declarator describes.
3917 enum class PointerDeclaratorKind {
3918 // Not a pointer.
3919 NonPointer,
3920 // Single-level pointer.
3921 SingleLevelPointer,
3922 // Multi-level pointer (of any pointer kind).
3923 MultiLevelPointer,
3924 // CFFooRef*
3925 MaybePointerToCFRef,
3926 // CFErrorRef*
3927 CFErrorRefPointer,
3928 // NSError**
3929 NSErrorPointerPointer,
3930 };
3931
3932 /// Describes a declarator chunk wrapping a pointer that marks inference as
3933 /// unexpected.
3934 // These values must be kept in sync with diagnostics.
3935 enum class PointerWrappingDeclaratorKind {
3936 /// Pointer is top-level.
3937 None = -1,
3938 /// Pointer is an array element.
3939 Array = 0,
3940 /// Pointer is the referent type of a C++ reference.
3941 Reference = 1
3942 };
3943} // end anonymous namespace
3944
3945/// Classify the given declarator, whose type-specified is \c type, based on
3946/// what kind of pointer it refers to.
3947///
3948/// This is used to determine the default nullability.
3949static PointerDeclaratorKind
3951 PointerWrappingDeclaratorKind &wrappingKind) {
3952 unsigned numNormalPointers = 0;
3953
3954 // For any dependent type, we consider it a non-pointer.
3955 if (type->isDependentType())
3956 return PointerDeclaratorKind::NonPointer;
3957
3958 // Look through the declarator chunks to identify pointers.
3959 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3960 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3961 switch (chunk.Kind) {
3963 if (numNormalPointers == 0)
3964 wrappingKind = PointerWrappingDeclaratorKind::Array;
3965 break;
3966
3969 break;
3970
3973 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3974 : PointerDeclaratorKind::SingleLevelPointer;
3975
3977 break;
3978
3980 if (numNormalPointers == 0)
3981 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3982 break;
3983
3985 ++numNormalPointers;
3986 if (numNormalPointers > 2)
3987 return PointerDeclaratorKind::MultiLevelPointer;
3988 break;
3989 }
3990 }
3991
3992 // Then, dig into the type specifier itself.
3993 unsigned numTypeSpecifierPointers = 0;
3994 do {
3995 // Decompose normal pointers.
3996 if (auto ptrType = type->getAs<PointerType>()) {
3997 ++numNormalPointers;
3998
3999 if (numNormalPointers > 2)
4000 return PointerDeclaratorKind::MultiLevelPointer;
4001
4002 type = ptrType->getPointeeType();
4003 ++numTypeSpecifierPointers;
4004 continue;
4005 }
4006
4007 // Decompose block pointers.
4008 if (type->getAs<BlockPointerType>()) {
4009 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4010 : PointerDeclaratorKind::SingleLevelPointer;
4011 }
4012
4013 // Decompose member pointers.
4014 if (type->getAs<MemberPointerType>()) {
4015 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4016 : PointerDeclaratorKind::SingleLevelPointer;
4017 }
4018
4019 // Look at Objective-C object pointers.
4020 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4021 ++numNormalPointers;
4022 ++numTypeSpecifierPointers;
4023
4024 // If this is NSError**, report that.
4025 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4026 if (objcClassDecl->getIdentifier() == S.ObjC().getNSErrorIdent() &&
4027 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4028 return PointerDeclaratorKind::NSErrorPointerPointer;
4029 }
4030 }
4031
4032 break;
4033 }
4034
4035 // Look at Objective-C class types.
4036 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4037 if (objcClass->getInterface()->getIdentifier() ==
4038 S.ObjC().getNSErrorIdent()) {
4039 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4040 return PointerDeclaratorKind::NSErrorPointerPointer;
4041 }
4042
4043 break;
4044 }
4045
4046 // If at this point we haven't seen a pointer, we won't see one.
4047 if (numNormalPointers == 0)
4048 return PointerDeclaratorKind::NonPointer;
4049
4050 if (auto *recordDecl = type->getAsRecordDecl()) {
4051 // If this is CFErrorRef*, report it as such.
4052 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4053 S.ObjC().isCFError(recordDecl)) {
4054 return PointerDeclaratorKind::CFErrorRefPointer;
4055 }
4056 break;
4057 }
4058
4059 break;
4060 } while (true);
4061
4062 switch (numNormalPointers) {
4063 case 0:
4064 return PointerDeclaratorKind::NonPointer;
4065
4066 case 1:
4067 return PointerDeclaratorKind::SingleLevelPointer;
4068
4069 case 2:
4070 return PointerDeclaratorKind::MaybePointerToCFRef;
4071
4072 default:
4073 return PointerDeclaratorKind::MultiLevelPointer;
4074 }
4075}
4076
4078 SourceLocation loc) {
4079 // If we're anywhere in a function, method, or closure context, don't perform
4080 // completeness checks.
4081 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4082 if (ctx->isFunctionOrMethod())
4083 return FileID();
4084
4085 if (ctx->isFileContext())
4086 break;
4087 }
4088
4089 // We only care about the expansion location.
4090 loc = S.SourceMgr.getExpansionLoc(loc);
4091 FileID file = S.SourceMgr.getFileID(loc);
4092 if (file.isInvalid())
4093 return FileID();
4094
4095 // Retrieve file information.
4096 bool invalid = false;
4097 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4098 if (invalid || !sloc.isFile())
4099 return FileID();
4100
4101 // We don't want to perform completeness checks on the main file or in
4102 // system headers.
4103 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4104 if (fileInfo.getIncludeLoc().isInvalid())
4105 return FileID();
4106 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4108 return FileID();
4109 }
4110
4111 return file;
4112}
4113
4114/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4115/// taking into account whitespace before and after.
4116template <typename DiagBuilderT>
4117static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4118 SourceLocation PointerLoc,
4119 NullabilityKind Nullability) {
4120 assert(PointerLoc.isValid());
4121 if (PointerLoc.isMacroID())
4122 return;
4123
4124 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4125 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4126 return;
4127
4128 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4129 if (!NextChar)
4130 return;
4131
4132 SmallString<32> InsertionTextBuf{" "};
4133 InsertionTextBuf += getNullabilitySpelling(Nullability);
4134 InsertionTextBuf += " ";
4135 StringRef InsertionText = InsertionTextBuf.str();
4136
4137 if (isWhitespace(*NextChar)) {
4138 InsertionText = InsertionText.drop_back();
4139 } else if (NextChar[-1] == '[') {
4140 if (NextChar[0] == ']')
4141 InsertionText = InsertionText.drop_back().drop_front();
4142 else
4143 InsertionText = InsertionText.drop_front();
4144 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4145 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4146 InsertionText = InsertionText.drop_back().drop_front();
4147 }
4148
4149 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4150}
4151
4153 SimplePointerKind PointerKind,
4154 SourceLocation PointerLoc,
4155 SourceLocation PointerEndLoc) {
4156 assert(PointerLoc.isValid());
4157
4158 if (PointerKind == SimplePointerKind::Array) {
4159 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4160 } else {
4161 S.Diag(PointerLoc, diag::warn_nullability_missing)
4162 << static_cast<unsigned>(PointerKind);
4163 }
4164
4165 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4166 if (FixItLoc.isMacroID())
4167 return;
4168
4169 auto addFixIt = [&](NullabilityKind Nullability) {
4170 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4171 Diag << static_cast<unsigned>(Nullability);
4172 Diag << static_cast<unsigned>(PointerKind);
4173 fixItNullability(S, Diag, FixItLoc, Nullability);
4174 };
4175 addFixIt(NullabilityKind::Nullable);
4176 addFixIt(NullabilityKind::NonNull);
4177}
4178
4179/// Complains about missing nullability if the file containing \p pointerLoc
4180/// has other uses of nullability (either the keywords or the \c assume_nonnull
4181/// pragma).
4182///
4183/// If the file has \e not seen other uses of nullability, this particular
4184/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4185static void
4186checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4187 SourceLocation pointerLoc,
4188 SourceLocation pointerEndLoc = SourceLocation()) {
4189 // Determine which file we're performing consistency checking for.
4190 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4191 if (file.isInvalid())
4192 return;
4193
4194 // If we haven't seen any type nullability in this file, we won't warn now
4195 // about anything.
4196 FileNullability &fileNullability = S.NullabilityMap[file];
4197 if (!fileNullability.SawTypeNullability) {
4198 // If this is the first pointer declarator in the file, and the appropriate
4199 // warning is on, record it in case we need to diagnose it retroactively.
4200 diag::kind diagKind;
4201 if (pointerKind == SimplePointerKind::Array)
4202 diagKind = diag::warn_nullability_missing_array;
4203 else
4204 diagKind = diag::warn_nullability_missing;
4205
4206 if (fileNullability.PointerLoc.isInvalid() &&
4207 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4208 fileNullability.PointerLoc = pointerLoc;
4209 fileNullability.PointerEndLoc = pointerEndLoc;
4210 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4211 }
4212
4213 return;
4214 }
4215
4216 // Complain about missing nullability.
4217 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4218}
4219
4220/// Marks that a nullability feature has been used in the file containing
4221/// \p loc.
4222///
4223/// If this file already had pointer types in it that were missing nullability,
4224/// the first such instance is retroactively diagnosed.
4225///
4226/// \sa checkNullabilityConsistency
4229 if (file.isInvalid())
4230 return;
4231
4232 FileNullability &fileNullability = S.NullabilityMap[file];
4233 if (fileNullability.SawTypeNullability)
4234 return;
4235 fileNullability.SawTypeNullability = true;
4236
4237 // If we haven't seen any type nullability before, now we have. Retroactively
4238 // diagnose the first unannotated pointer, if there was one.
4239 if (fileNullability.PointerLoc.isInvalid())
4240 return;
4241
4242 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4244 fileNullability.PointerEndLoc);
4245}
4246
4247/// Returns true if any of the declarator chunks before \p endIndex include a
4248/// level of indirection: array, pointer, reference, or pointer-to-member.
4249///
4250/// Because declarator chunks are stored in outer-to-inner order, testing
4251/// every chunk before \p endIndex is testing all chunks that embed the current
4252/// chunk as part of their type.
4253///
4254/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4255/// end index, in which case all chunks are tested.
4256static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4257 unsigned i = endIndex;
4258 while (i != 0) {
4259 // Walk outwards along the declarator chunks.
4260 --i;
4261 const DeclaratorChunk &DC = D.getTypeObject(i);
4262 switch (DC.Kind) {
4264 break;
4269 return true;
4273 // These are invalid anyway, so just ignore.
4274 break;
4275 }
4276 }
4277 return false;
4278}
4279
4280static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4281 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4282 Chunk.Kind == DeclaratorChunk::Array);
4283}
4284
4285template<typename AttrT>
4286static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4287 AL.setUsedAsTypeAttr();
4288 return ::new (Ctx) AttrT(Ctx, AL);
4289}
4290
4292 NullabilityKind NK) {
4293 switch (NK) {
4296
4299
4302
4305 }
4306 llvm_unreachable("unknown NullabilityKind");
4307}
4308
4309// Diagnose whether this is a case with the multiple addr spaces.
4310// Returns true if this is an invalid case.
4311// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4312// by qualifiers for two or more different address spaces."
4314 LangAS ASNew,
4315 SourceLocation AttrLoc) {
4316 if (ASOld != LangAS::Default) {
4317 if (ASOld != ASNew) {
4318 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4319 return true;
4320 }
4321 // Emit a warning if they are identical; it's likely unintended.
4322 S.Diag(AttrLoc,
4323 diag::warn_attribute_address_multiple_identical_qualifiers);
4324 }
4325 return false;
4326}
4327
4328// Whether this is a type broadly expected to have nullability attached.
4329// These types are affected by `#pragma assume_nonnull`, and missing nullability
4330// will be diagnosed with -Wnullability-completeness.
4332 return T->canHaveNullability(/*ResultIfUnknown=*/false) &&
4333 // For now, do not infer/require nullability on C++ smart pointers.
4334 // It's unclear whether the pragma's behavior is useful for C++.
4335 // e.g. treating type-aliases and template-type-parameters differently
4336 // from types of declarations can be surprising.
4338 T->getCanonicalTypeInternal());
4339}
4340
4341static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4342 QualType declSpecType,
4343 TypeSourceInfo *TInfo) {
4344 // The TypeSourceInfo that this function returns will not be a null type.
4345 // If there is an error, this function will fill in a dummy type as fallback.
4346 QualType T = declSpecType;
4347 Declarator &D = state.getDeclarator();
4348 Sema &S = state.getSema();
4349 ASTContext &Context = S.Context;
4350 const LangOptions &LangOpts = S.getLangOpts();
4351
4352 // The name we're declaring, if any.
4353 DeclarationName Name;
4354 if (D.getIdentifier())
4355 Name = D.getIdentifier();
4356
4357 // Does this declaration declare a typedef-name?
4358 bool IsTypedefName =
4362
4363 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4364 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4365 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4366 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4367
4368 // If T is 'decltype(auto)', the only declarators we can have are parens
4369 // and at most one function declarator if this is a function declaration.
4370 // If T is a deduced class template specialization type, only parentheses
4371 // are allowed.
4372 if (auto *DT = T->getAs<DeducedType>()) {
4373 const AutoType *AT = T->getAs<AutoType>();
4374 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4375 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4376 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4377 unsigned Index = E - I - 1;
4378 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4379 unsigned DiagId = IsClassTemplateDeduction
4380 ? diag::err_deduced_class_template_compound_type
4381 : diag::err_decltype_auto_compound_type;
4382 unsigned DiagKind = 0;
4383 switch (DeclChunk.Kind) {
4385 continue;
4387 if (IsClassTemplateDeduction) {
4388 DiagKind = 3;
4389 break;
4390 }
4391 unsigned FnIndex;
4393 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4394 continue;
4395 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4396 break;
4397 }
4401 DiagKind = 0;
4402 break;
4404 DiagKind = 1;
4405 break;
4407 DiagKind = 2;
4408 break;
4410 break;
4411 }
4412
4413 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4414 D.setInvalidType(true);
4415 break;
4416 }
4417 }
4418 }
4419
4420 // Determine whether we should infer _Nonnull on pointer types.
4421 NullabilityKindOrNone inferNullability = std::nullopt;
4422 bool inferNullabilityCS = false;
4423 bool inferNullabilityInnerOnly = false;
4424 bool inferNullabilityInnerOnlyComplete = false;
4425
4426 // Are we in an assume-nonnull region?
4427 bool inAssumeNonNullRegion = false;
4428 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4429 if (assumeNonNullLoc.isValid()) {
4430 inAssumeNonNullRegion = true;
4431 recordNullabilitySeen(S, assumeNonNullLoc);
4432 }
4433
4434 // Whether to complain about missing nullability specifiers or not.
4435 enum {
4436 /// Never complain.
4437 CAMN_No,
4438 /// Complain on the inner pointers (but not the outermost
4439 /// pointer).
4440 CAMN_InnerPointers,
4441 /// Complain about any pointers that don't have nullability
4442 /// specified or inferred.
4443 CAMN_Yes
4444 } complainAboutMissingNullability = CAMN_No;
4445 unsigned NumPointersRemaining = 0;
4446 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4447
4448 if (IsTypedefName) {
4449 // For typedefs, we do not infer any nullability (the default),
4450 // and we only complain about missing nullability specifiers on
4451 // inner pointers.
4452 complainAboutMissingNullability = CAMN_InnerPointers;
4453
4454 if (shouldHaveNullability(T) && !T->getNullability()) {
4455 // Note that we allow but don't require nullability on dependent types.
4456 ++NumPointersRemaining;
4457 }
4458
4459 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4460 DeclaratorChunk &chunk = D.getTypeObject(i);
4461 switch (chunk.Kind) {
4465 break;
4466
4469 ++NumPointersRemaining;
4470 break;
4471
4474 continue;
4475
4477 ++NumPointersRemaining;
4478 continue;
4479 }
4480 }
4481 } else {
4482 bool isFunctionOrMethod = false;
4483 switch (auto context = state.getDeclarator().getContext()) {
4489 isFunctionOrMethod = true;
4490 [[fallthrough]];
4491
4493 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4494 complainAboutMissingNullability = CAMN_No;
4495 break;
4496 }
4497
4498 // Weak properties are inferred to be nullable.
4499 if (state.getDeclarator().isObjCWeakProperty()) {
4500 // Weak properties cannot be nonnull, and should not complain about
4501 // missing nullable attributes during completeness checks.
4502 complainAboutMissingNullability = CAMN_No;
4503 if (inAssumeNonNullRegion) {
4504 inferNullability = NullabilityKind::Nullable;
4505 }
4506 break;
4507 }
4508
4509 [[fallthrough]];
4510
4513 complainAboutMissingNullability = CAMN_Yes;
4514
4515 // Nullability inference depends on the type and declarator.
4516 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4517 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4518 case PointerDeclaratorKind::NonPointer:
4519 case PointerDeclaratorKind::MultiLevelPointer:
4520 // Cannot infer nullability.
4521 break;
4522
4523 case PointerDeclaratorKind::SingleLevelPointer:
4524 // Infer _Nonnull if we are in an assumes-nonnull region.
4525 if (inAssumeNonNullRegion) {
4526 complainAboutInferringWithinChunk = wrappingKind;
4527 inferNullability = NullabilityKind::NonNull;
4528 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4530 }
4531 break;
4532
4533 case PointerDeclaratorKind::CFErrorRefPointer:
4534 case PointerDeclaratorKind::NSErrorPointerPointer:
4535 // Within a function or method signature, infer _Nullable at both
4536 // levels.
4537 if (isFunctionOrMethod && inAssumeNonNullRegion)
4538 inferNullability = NullabilityKind::Nullable;
4539 break;
4540
4541 case PointerDeclaratorKind::MaybePointerToCFRef:
4542 if (isFunctionOrMethod) {
4543 // On pointer-to-pointer parameters marked cf_returns_retained or
4544 // cf_returns_not_retained, if the outer pointer is explicit then
4545 // infer the inner pointer as _Nullable.
4546 auto hasCFReturnsAttr =
4547 [](const ParsedAttributesView &AttrList) -> bool {
4548 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4549 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4550 };
4551 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4552 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4553 hasCFReturnsAttr(D.getAttributes()) ||
4554 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4555 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4556 inferNullability = NullabilityKind::Nullable;
4557 inferNullabilityInnerOnly = true;
4558 }
4559 }
4560 }
4561 break;
4562 }
4563 break;
4564 }
4565
4567 complainAboutMissingNullability = CAMN_Yes;
4568 break;
4569
4589 // Don't infer in these contexts.
4590 break;
4591 }
4592 }
4593
4594 // Local function that returns true if its argument looks like a va_list.
4595 auto isVaList = [&S](QualType T) -> bool {
4596 auto *typedefTy = T->getAs<TypedefType>();
4597 if (!typedefTy)
4598 return false;
4599 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4600 do {
4601 if (typedefTy->getDecl() == vaListTypedef)
4602 return true;
4603 if (auto *name = typedefTy->getDecl()->getIdentifier())
4604 if (name->isStr("va_list"))
4605 return true;
4606 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4607 } while (typedefTy);
4608 return false;
4609 };
4610
4611 // Local function that checks the nullability for a given pointer declarator.
4612 // Returns true if _Nonnull was inferred.
4613 auto inferPointerNullability =
4614 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4615 SourceLocation pointerEndLoc,
4616 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4617 // We've seen a pointer.
4618 if (NumPointersRemaining > 0)
4619 --NumPointersRemaining;
4620
4621 // If a nullability attribute is present, there's nothing to do.
4622 if (hasNullabilityAttr(attrs))
4623 return nullptr;
4624
4625 // If we're supposed to infer nullability, do so now.
4626 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4627 ParsedAttr::Form form =
4628 inferNullabilityCS
4629 ? ParsedAttr::Form::ContextSensitiveKeyword()
4630 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4631 false /*IsRegularKeywordAttribute*/);
4632 ParsedAttr *nullabilityAttr = Pool.create(
4633 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4634 AttributeScopeInfo(), nullptr, 0, form);
4635
4636 attrs.addAtEnd(nullabilityAttr);
4637
4638 if (inferNullabilityCS) {
4639 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4640 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4641 }
4642
4643 if (pointerLoc.isValid() &&
4644 complainAboutInferringWithinChunk !=
4645 PointerWrappingDeclaratorKind::None) {
4646 auto Diag =
4647 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4648 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4650 }
4651
4652 if (inferNullabilityInnerOnly)
4653 inferNullabilityInnerOnlyComplete = true;
4654 return nullabilityAttr;
4655 }
4656
4657 // If we're supposed to complain about missing nullability, do so
4658 // now if it's truly missing.
4659 switch (complainAboutMissingNullability) {
4660 case CAMN_No:
4661 break;
4662
4663 case CAMN_InnerPointers:
4664 if (NumPointersRemaining == 0)
4665 break;
4666 [[fallthrough]];
4667
4668 case CAMN_Yes:
4669 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4670 }
4671 return nullptr;
4672 };
4673
4674 // If the type itself could have nullability but does not, infer pointer
4675 // nullability and perform consistency checking.
4676 if (S.CodeSynthesisContexts.empty()) {
4677 if (shouldHaveNullability(T) && !T->getNullability()) {
4678 if (isVaList(T)) {
4679 // Record that we've seen a pointer, but do nothing else.
4680 if (NumPointersRemaining > 0)
4681 --NumPointersRemaining;
4682 } else {
4683 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4684 if (T->isBlockPointerType())
4685 pointerKind = SimplePointerKind::BlockPointer;
4686 else if (T->isMemberPointerType())
4687 pointerKind = SimplePointerKind::MemberPointer;
4688
4689 if (auto *attr = inferPointerNullability(
4690 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4691 D.getDeclSpec().getEndLoc(),
4694 T = state.getAttributedType(
4695 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4696 }
4697 }
4698 }
4699
4700 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
4701 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
4703 checkNullabilityConsistency(S, SimplePointerKind::Array,
4705 }
4706 }
4707
4708 bool ExpectNoDerefChunk =
4709 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4710
4711 // Walk the DeclTypeInfo, building the recursive type as we go.
4712 // DeclTypeInfos are ordered from the identifier out, which is
4713 // opposite of what we want :).
4714
4715 // Track if the produced type matches the structure of the declarator.
4716 // This is used later to decide if we can fill `TypeLoc` from
4717 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
4718 // an error by replacing the type with `int`.
4719 bool AreDeclaratorChunksValid = true;
4720 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4721 unsigned chunkIndex = e - i - 1;
4722 state.setCurrentChunkIndex(chunkIndex);
4723 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4724 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4725 switch (DeclType.Kind) {
4727 if (i == 0)
4728 warnAboutRedundantParens(S, D, T);
4729 T = S.BuildParenType(T);
4730 break;
4732 // If blocks are disabled, emit an error.
4733 if (!LangOpts.Blocks)
4734 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4735
4736 // Handle pointer nullability.
4737 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4738 DeclType.EndLoc, DeclType.getAttrs(),
4739 state.getDeclarator().getAttributePool());
4740
4741 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4742 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4743 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4744 // qualified with const.
4745 if (LangOpts.OpenCL)
4746 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4747 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4748 }
4749 break;
4751 // Verify that we're not building a pointer to pointer to function with
4752 // exception specification.
4753 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4754 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4755 D.setInvalidType(true);
4756 // Build the type anyway.
4757 }
4758
4759 // Handle pointer nullability
4760 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4761 DeclType.EndLoc, DeclType.getAttrs(),
4762 state.getDeclarator().getAttributePool());
4763
4764 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4765 T = Context.getObjCObjectPointerType(T);
4766 if (DeclType.Ptr.TypeQuals)
4767 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4768 break;
4769 }
4770
4771 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4772 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4773 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4774 if (LangOpts.OpenCL) {
4775 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4776 T->isBlockPointerType()) {
4777 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4778 D.setInvalidType(true);
4779 }
4780 }
4781
4782 T = S.BuildPointerType(T, DeclType.Loc, Name);
4783 if (DeclType.Ptr.TypeQuals)
4784 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4785 if (DeclType.Ptr.OverflowBehaviorLoc.isValid()) {
4786 auto OBState = DeclType.Ptr.OverflowBehaviorIsWrap
4789 S.Diag(DeclType.Ptr.OverflowBehaviorLoc,
4790 diag::err_overflow_behavior_non_integer_type)
4791 << DeclSpec::getSpecifierName(OBState) << T.getAsString() << 1;
4792 D.setInvalidType(true);
4793 }
4794 break;
4796 // Verify that we're not building a reference to pointer to function with
4797 // exception specification.
4798 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4799 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4800 D.setInvalidType(true);
4801 // Build the type anyway.
4802 }
4803 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4804
4805 if (DeclType.Ref.HasRestrict)
4806 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4807 break;
4808 }
4810 // Verify that we're not building an array of pointers to function with
4811 // exception specification.
4812 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4813 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4814 D.setInvalidType(true);
4815 // Build the type anyway.
4816 }
4817 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4818 Expr *ArraySize = ATI.NumElts;
4820
4821 // Microsoft property fields can have multiple sizeless array chunks
4822 // (i.e. int x[][][]). Skip all of these except one to avoid creating
4823 // bad incomplete array types.
4824 if (chunkIndex != 0 && !ArraySize &&
4826 // This is a sizeless chunk. If the next is also, skip this one.
4827 DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1);
4828 if (NextDeclType.Kind == DeclaratorChunk::Array &&
4829 !NextDeclType.Arr.NumElts)
4830 break;
4831 }
4832
4833 if (ATI.isStar)
4835 else if (ATI.hasStatic)
4837 else
4839 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) {
4840 // FIXME: This check isn't quite right: it allows star in prototypes
4841 // for function definitions, and disallows some edge cases detailed
4842 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4843 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4845 D.setInvalidType(true);
4846 }
4847
4848 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4849 // shall appear only in a declaration of a function parameter with an
4850 // array type, ...
4851 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) {
4852 if (!(D.isPrototypeContext() ||
4854 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype)
4855 << (ASM == ArraySizeModifier::Static ? "'static'"
4856 : "type qualifier");
4857 // Remove the 'static' and the type qualifiers.
4858 if (ASM == ArraySizeModifier::Static)
4860 ATI.TypeQuals = 0;
4861 D.setInvalidType(true);
4862 }
4863
4864 // C99 6.7.5.2p1: ... and then only in the outermost array type
4865 // derivation.
4866 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4867 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost)
4868 << (ASM == ArraySizeModifier::Static ? "'static'"
4869 : "type qualifier");
4870 if (ASM == ArraySizeModifier::Static)
4872 ATI.TypeQuals = 0;
4873 D.setInvalidType(true);
4874 }
4875 }
4876
4877 // Array parameters can be marked nullable as well, although it's not
4878 // necessary if they're marked 'static'.
4879 if (complainAboutMissingNullability == CAMN_Yes &&
4880 !hasNullabilityAttr(DeclType.getAttrs()) &&
4882 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4883 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4884 }
4885
4886 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4887 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4888 break;
4889 }
4891 // If the function declarator has a prototype (i.e. it is not () and
4892 // does not have a K&R-style identifier list), then the arguments are part
4893 // of the type, otherwise the argument list is ().
4894 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4895 IsQualifiedFunction =
4897
4898 auto IsClassType = [&](CXXScopeSpec &SS) {
4899 // If there already was an problem with the scope, don’t issue another
4900 // error about the explicit object parameter.
4901 return SS.isInvalid() ||
4902 isa_and_present<CXXRecordDecl>(S.computeDeclContext(SS));
4903 };
4904
4905 // C++23 [dcl.fct]p6:
4906 //
4907 // An explicit-object-parameter-declaration is a parameter-declaration
4908 // with a this specifier. An explicit-object-parameter-declaration shall
4909 // appear only as the first parameter-declaration of a
4910 // parameter-declaration-list of one of:
4911 //
4912 // - a declaration of a member function or member function template
4913 // ([class.mem]), or
4914 //
4915 // - an explicit instantiation ([temp.explicit]) or explicit
4916 // specialization ([temp.expl.spec]) of a templated member function,
4917 // or
4918 //
4919 // - a lambda-declarator [expr.prim.lambda].
4922 FTI.NumParams ? dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param)
4923 : nullptr;
4924
4925 bool IsFunctionDecl = D.getInnermostNonParenChunk() == &DeclType;
4926 if (First && First->isExplicitObjectParameter() &&
4928
4929 // Either not a member or nested declarator in a member.
4930 //
4931 // Note that e.g. 'static' or 'friend' declarations are accepted
4932 // here; we diagnose them later when we build the member function
4933 // because it's easier that way.
4934 (C != DeclaratorContext::Member || !IsFunctionDecl) &&
4935
4936 // Allow out-of-line definitions of member functions.
4937 !IsClassType(D.getCXXScopeSpec())) {
4938 if (IsFunctionDecl)
4939 S.Diag(First->getBeginLoc(),
4940 diag::err_explicit_object_parameter_nonmember)
4941 << /*non-member*/ 2 << /*function*/ 0 << First->getSourceRange();
4942 else
4943 S.Diag(First->getBeginLoc(),
4944 diag::err_explicit_object_parameter_invalid)
4945 << First->getSourceRange();
4946
4947 // Do let non-member function have explicit parameters
4948 // to not break assumptions elsewhere in the code.
4949 First->setExplicitObjectParameterLoc(SourceLocation());
4950 D.setInvalidType();
4951 AreDeclaratorChunksValid = false;
4952 }
4953
4954 // Check for auto functions and trailing return type and adjust the
4955 // return type accordingly.
4956 if (!D.isInvalidType()) {
4957 // trailing-return-type is only required if we're declaring a function,
4958 // and not, for instance, a pointer to a function.
4959 if (D.getDeclSpec().hasAutoTypeSpec() &&
4960 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4961 if (!S.getLangOpts().CPlusPlus14) {
4964 ? diag::err_auto_missing_trailing_return
4965 : diag::err_deduced_return_type);
4966 T = Context.IntTy;
4967 D.setInvalidType(true);
4968 AreDeclaratorChunksValid = false;
4969 } else {
4971 diag::warn_cxx11_compat_deduced_return_type);
4972 }
4973 } else if (FTI.hasTrailingReturnType()) {
4974 // T must be exactly 'auto' at this point. See CWG issue 681.
4975 if (isa<ParenType>(T)) {
4976 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4977 << T << D.getSourceRange();
4978 D.setInvalidType(true);
4979 // FIXME: recover and fill decls in `TypeLoc`s.
4980 AreDeclaratorChunksValid = false;
4981 } else if (D.getName().getKind() ==
4983 if (T != Context.DependentTy) {
4985 diag::err_deduction_guide_with_complex_decl)
4986 << D.getSourceRange();
4987 D.setInvalidType(true);
4988 // FIXME: recover and fill decls in `TypeLoc`s.
4989 AreDeclaratorChunksValid = false;
4990 }
4991 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
4992 (T.hasQualifiers() || !isa<AutoType>(T) ||
4993 cast<AutoType>(T)->getKeyword() !=
4995 cast<AutoType>(T)->isConstrained())) {
4996 // Attach a valid source location for diagnostics on functions with
4997 // trailing return types missing 'auto'. Attempt to get the location
4998 // from the declared type; if invalid, fall back to the trailing
4999 // return type's location.
5002 if (Loc.isInvalid()) {
5003 Loc = FTI.getTrailingReturnTypeLoc();
5004 SR = D.getSourceRange();
5005 }
5006 S.Diag(Loc, diag::err_trailing_return_without_auto) << T << SR;
5007 D.setInvalidType(true);
5008 // FIXME: recover and fill decls in `TypeLoc`s.
5009 AreDeclaratorChunksValid = false;
5010 }
5011 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5012 if (T.isNull()) {
5013 // An error occurred parsing the trailing return type.
5014 T = Context.IntTy;
5015 D.setInvalidType(true);
5016 } else if (AutoType *Auto = T->getContainedAutoType()) {
5017 // If the trailing return type contains an `auto`, we may need to
5018 // invent a template parameter for it, for cases like
5019 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5020 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5022 InventedParamInfo = &S.InventedParameterInfos.back();
5024 InventedParamInfo = S.getCurLambda();
5025 if (InventedParamInfo) {
5026 std::tie(T, TInfo) = InventTemplateParameter(
5027 state, T, TInfo, Auto, *InventedParamInfo);
5028 }
5029 }
5030 } else {
5031 // This function type is not the type of the entity being declared,
5032 // so checking the 'auto' is not the responsibility of this chunk.
5033 }
5034 }
5035
5036 // C99 6.7.5.3p1: The return type may not be a function or array type.
5037 // For conversion functions, we'll diagnose this particular error later.
5038 if (!D.isInvalidType() &&
5039 ((T->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
5040 T->isFunctionType()) &&
5041 (D.getName().getKind() !=
5043 unsigned diagID = diag::err_func_returning_array_function;
5044 // Last processing chunk in block context means this function chunk
5045 // represents the block.
5046 if (chunkIndex == 0 &&
5048 diagID = diag::err_block_returning_array_function;
5049 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5050 T = Context.IntTy;
5051 D.setInvalidType(true);
5052 AreDeclaratorChunksValid = false;
5053 }
5054
5055 // Do not allow returning half FP value.
5056 // FIXME: This really should be in BuildFunctionType.
5057 if (T->isHalfType()) {
5058 if (S.getLangOpts().OpenCL) {
5059 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5060 S.getLangOpts())) {
5061 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5062 << T << 0 /*pointer hint*/;
5063 D.setInvalidType(true);
5064 }
5065 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5067 S.Diag(D.getIdentifierLoc(),
5068 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5069 D.setInvalidType(true);
5070 }
5071 }
5072
5073 // __ptrauth is illegal on a function return type.
5074 if (T.getPointerAuth()) {
5075 S.Diag(DeclType.Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
5076 }
5077
5078 if (LangOpts.OpenCL) {
5079 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5080 // function.
5081 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5082 T->isPipeType()) {
5083 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5084 << T << 1 /*hint off*/;
5085 D.setInvalidType(true);
5086 }
5087 // OpenCL doesn't support variadic functions and blocks
5088 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5089 // We also allow here any toolchain reserved identifiers.
5090 if (FTI.isVariadic &&
5092 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5093 !(D.getIdentifier() &&
5094 ((D.getIdentifier()->getName() == "printf" &&
5095 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5096 D.getIdentifier()->getName().starts_with("__")))) {
5097 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5098 D.setInvalidType(true);
5099 }
5100 }
5101
5102 // Methods cannot return interface types. All ObjC objects are
5103 // passed by reference.
5104 if (T->isObjCObjectType()) {
5105 SourceLocation DiagLoc, FixitLoc;
5106 if (TInfo) {
5107 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5108 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5109 } else {
5110 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5111 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5112 }
5113 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5114 << 0 << T
5115 << FixItHint::CreateInsertion(FixitLoc, "*");
5116
5117 T = Context.getObjCObjectPointerType(T);
5118 if (TInfo) {
5119 TypeLocBuilder TLB;
5120 TLB.pushFullCopy(TInfo->getTypeLoc());
5122 TLoc.setStarLoc(FixitLoc);
5123 TInfo = TLB.getTypeSourceInfo(Context, T);
5124 } else {
5125 AreDeclaratorChunksValid = false;
5126 }
5127
5128 D.setInvalidType(true);
5129 }
5130
5131 // cv-qualifiers on return types are pointless except when the type is a
5132 // class type in C++.
5133 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5134 // A dependent type or an undeduced type might later become a class
5135 // type.
5136 !(S.getLangOpts().CPlusPlus &&
5137 (T->isRecordType() || T->isDependentType() ||
5138 T->isUndeducedAutoType()))) {
5139 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5142 // [6.9.1/3] qualified void return is invalid on a C
5143 // function definition. Apparently ok on declarations and
5144 // in C++ though (!)
5145 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5146 } else
5147 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5148 }
5149
5150 // C++2a [dcl.fct]p12:
5151 // A volatile-qualified return type is deprecated
5152 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5153 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5154
5155 // Objective-C ARC ownership qualifiers are ignored on the function
5156 // return type (by type canonicalization). Complain if this attribute
5157 // was written here.
5158 if (T.getQualifiers().hasObjCLifetime()) {
5159 SourceLocation AttrLoc;
5160 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5161 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5162 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5163 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5164 AttrLoc = AL.getLoc();
5165 break;
5166 }
5167 }
5168 }
5169 if (AttrLoc.isInvalid()) {
5170 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5171 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5172 AttrLoc = AL.getLoc();
5173 break;
5174 }
5175 }
5176 }
5177
5178 if (AttrLoc.isValid()) {
5179 // The ownership attributes are almost always written via
5180 // the predefined
5181 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5182 if (AttrLoc.isMacroID())
5183 AttrLoc =
5185
5186 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5187 << T.getQualifiers().getObjCLifetime();
5188 }
5189 }
5190
5191 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5192 // C++ [dcl.fct]p6:
5193 // Types shall not be defined in return or parameter types.
5195 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5196 << Context.getCanonicalTagType(Tag);
5197 }
5198
5199 // Exception specs are not allowed in typedefs. Complain, but add it
5200 // anyway.
5201 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5203 diag::err_exception_spec_in_typedef)
5206
5207 // If we see "T var();" or "T var(T());" at block scope, it is probably
5208 // an attempt to initialize a variable, not a function declaration.
5209 if (FTI.isAmbiguous)
5210 warnAboutAmbiguousFunction(S, D, DeclType, T);
5211
5213 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5214
5215 // OpenCL disallows functions without a prototype, but it doesn't enforce
5216 // strict prototypes as in C23 because it allows a function definition to
5217 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5218 if (!FTI.NumParams && !FTI.isVariadic &&
5219 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5220 // Simple void foo(), where the incoming T is the result type.
5221 T = Context.getFunctionNoProtoType(T, EI);
5222 } else {
5223 // We allow a zero-parameter variadic function in C if the
5224 // function is marked with the "overloadable" attribute. Scan
5225 // for this attribute now. We also allow it in C23 per WG14 N2975.
5226 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5227 if (LangOpts.C23)
5228 S.Diag(FTI.getEllipsisLoc(),
5229 diag::warn_c17_compat_ellipsis_only_parameter);
5231 ParsedAttr::AT_Overloadable) &&
5233 ParsedAttr::AT_Overloadable) &&
5235 ParsedAttr::AT_Overloadable))
5236 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5237 }
5238
5239 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5240 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5241 // definition.
5242 S.Diag(FTI.Params[0].IdentLoc,
5243 diag::err_ident_list_in_fn_declaration);
5244 D.setInvalidType(true);
5245 // Recover by creating a K&R-style function type, if possible.
5246 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5247 ? Context.getFunctionNoProtoType(T, EI)
5248 : Context.IntTy;
5249 AreDeclaratorChunksValid = false;
5250 break;
5251 }
5252
5254 EPI.ExtInfo = EI;
5255 EPI.Variadic = FTI.isVariadic;
5256 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5260 : 0);
5263 : RQ_RValue;
5264
5265 // Otherwise, we have a function with a parameter list that is
5266 // potentially variadic.
5268 ParamTys.reserve(FTI.NumParams);
5269
5271 ExtParameterInfos(FTI.NumParams);
5272 bool HasAnyInterestingExtParameterInfos = false;
5273
5274 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5275 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5276 QualType ParamTy = Param->getType();
5277 assert(!ParamTy.isNull() && "Couldn't parse type?");
5278
5279 // Look for 'void'. void is allowed only as a single parameter to a
5280 // function with no other parameters (C99 6.7.5.3p10). We record
5281 // int(void) as a FunctionProtoType with an empty parameter list.
5282 if (ParamTy->isVoidType()) {
5283 // If this is something like 'float(int, void)', reject it. 'void'
5284 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5285 // have parameters of incomplete type.
5286 if (FTI.NumParams != 1 || FTI.isVariadic) {
5287 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5288 ParamTy = Context.IntTy;
5289 Param->setType(ParamTy);
5290 } else if (FTI.Params[i].Ident) {
5291 // Reject, but continue to parse 'int(void abc)'.
5292 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5293 ParamTy = Context.IntTy;
5294 Param->setType(ParamTy);
5295 } else {
5296 // Reject, but continue to parse 'float(const void)'.
5297 if (ParamTy.hasQualifiers())
5298 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5299
5300 for (const auto *A : Param->attrs()) {
5301 S.Diag(A->getLoc(), diag::warn_attribute_on_void_param)
5302 << A << A->getRange();
5303 }
5304
5305 // Reject, but continue to parse 'float(this void)' as
5306 // 'float(void)'.
5307 if (Param->isExplicitObjectParameter()) {
5308 S.Diag(Param->getLocation(),
5309 diag::err_void_explicit_object_param);
5310 Param->setExplicitObjectParameterLoc(SourceLocation());
5311 }
5312
5313 // Do not add 'void' to the list.
5314 break;
5315 }
5316 } else if (ParamTy->isHalfType()) {
5317 // Disallow half FP parameters.
5318 // FIXME: This really should be in BuildFunctionType.
5319 if (S.getLangOpts().OpenCL) {
5320 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5321 S.getLangOpts())) {
5322 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5323 << ParamTy << 0;
5324 D.setInvalidType();
5325 Param->setInvalidDecl();
5326 }
5327 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5329 S.Diag(Param->getLocation(),
5330 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5331 D.setInvalidType();
5332 }
5333 } else if (!FTI.hasPrototype) {
5334 if (Context.isPromotableIntegerType(ParamTy)) {
5335 ParamTy = Context.getPromotedIntegerType(ParamTy);
5336 Param->setKNRPromoted(true);
5337 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5338 if (BTy->getKind() == BuiltinType::Float) {
5339 ParamTy = Context.DoubleTy;
5340 Param->setKNRPromoted(true);
5341 }
5342 }
5343 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5344 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5345 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5346 << ParamTy << 1 /*hint off*/;
5347 D.setInvalidType();
5348 }
5349
5350 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5351 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5352 HasAnyInterestingExtParameterInfos = true;
5353 }
5354
5355 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5356 ExtParameterInfos[i] =
5357 ExtParameterInfos[i].withABI(attr->getABI());
5358 HasAnyInterestingExtParameterInfos = true;
5359 }
5360
5361 if (Param->hasAttr<PassObjectSizeAttr>()) {
5362 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5363 HasAnyInterestingExtParameterInfos = true;
5364 }
5365
5366 if (Param->hasAttr<NoEscapeAttr>()) {
5367 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5368 HasAnyInterestingExtParameterInfos = true;
5369 }
5370
5371 ParamTys.push_back(ParamTy);
5372 }
5373
5374 if (HasAnyInterestingExtParameterInfos) {
5375 EPI.ExtParameterInfos = ExtParameterInfos.data();
5376 checkExtParameterInfos(S, ParamTys, EPI,
5377 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5378 }
5379
5380 SmallVector<QualType, 4> Exceptions;
5381 SmallVector<ParsedType, 2> DynamicExceptions;
5382 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5383 Expr *NoexceptExpr = nullptr;
5384
5385 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5386 // FIXME: It's rather inefficient to have to split into two vectors
5387 // here.
5388 unsigned N = FTI.getNumExceptions();
5389 DynamicExceptions.reserve(N);
5390 DynamicExceptionRanges.reserve(N);
5391 for (unsigned I = 0; I != N; ++I) {
5392 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5393 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5394 }
5395 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5396 NoexceptExpr = FTI.NoexceptExpr;
5397 }
5398
5401 DynamicExceptions,
5402 DynamicExceptionRanges,
5403 NoexceptExpr,
5404 Exceptions,
5405 EPI.ExceptionSpec);
5406
5407 // FIXME: Set address space from attrs for C++ mode here.
5408 // OpenCLCPlusPlus: A class member function has an address space.
5409 auto IsClassMember = [&]() {
5410 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5411 state.getDeclarator()
5412 .getCXXScopeSpec()
5413 .getScopeRep()
5414 .getKind() == NestedNameSpecifier::Kind::Type) ||
5415 state.getDeclarator().getContext() ==
5417 state.getDeclarator().getContext() ==
5419 };
5420
5421 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5422 LangAS ASIdx = LangAS::Default;
5423 // Take address space attr if any and mark as invalid to avoid adding
5424 // them later while creating QualType.
5425 if (FTI.MethodQualifiers)
5427 LangAS ASIdxNew = attr.asOpenCLLangAS();
5428 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5429 attr.getLoc()))
5430 D.setInvalidType(true);
5431 else
5432 ASIdx = ASIdxNew;
5433 }
5434 // If a class member function's address space is not set, set it to
5435 // __generic.
5436 LangAS AS =
5438 : ASIdx);
5439 EPI.TypeQuals.addAddressSpace(AS);
5440 }
5441 T = Context.getFunctionType(T, ParamTys, EPI);
5442 }
5443 break;
5444 }
5446 // The scope spec must refer to a class, or be dependent.
5447 CXXScopeSpec &SS = DeclType.Mem.Scope();
5448
5449 // Handle pointer nullability.
5450 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5451 DeclType.EndLoc, DeclType.getAttrs(),
5452 state.getDeclarator().getAttributePool());
5453
5454 if (SS.isInvalid()) {
5455 // Avoid emitting extra errors if we already errored on the scope.
5456 D.setInvalidType(true);
5457 AreDeclaratorChunksValid = false;
5458 } else {
5459 T = S.BuildMemberPointerType(T, SS, /*Cls=*/nullptr, DeclType.Loc,
5460 D.getIdentifier());
5461 }
5462
5463 if (T.isNull()) {
5464 T = Context.IntTy;
5465 D.setInvalidType(true);
5466 AreDeclaratorChunksValid = false;
5467 } else if (DeclType.Mem.TypeQuals) {
5468 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5469 }
5470 break;
5471 }
5472
5473 case DeclaratorChunk::Pipe: {
5474 T = S.BuildReadPipeType(T, DeclType.Loc);
5477 break;
5478 }
5479 }
5480
5481 if (T.isNull()) {
5482 D.setInvalidType(true);
5483 T = Context.IntTy;
5484 AreDeclaratorChunksValid = false;
5485 }
5486
5487 // See if there are any attributes on this declarator chunk.
5488 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs(),
5490
5491 if (DeclType.Kind != DeclaratorChunk::Paren) {
5492 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5493 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5494
5495 ExpectNoDerefChunk = state.didParseNoDeref();
5496 }
5497 }
5498
5499 if (ExpectNoDerefChunk)
5500 S.Diag(state.getDeclarator().getBeginLoc(),
5501 diag::warn_noderef_on_non_pointer_or_array);
5502
5503 // GNU warning -Wstrict-prototypes
5504 // Warn if a function declaration or definition is without a prototype.
5505 // This warning is issued for all kinds of unprototyped function
5506 // declarations (i.e. function type typedef, function pointer etc.)
5507 // C99 6.7.5.3p14:
5508 // The empty list in a function declarator that is not part of a definition
5509 // of that function specifies that no information about the number or types
5510 // of the parameters is supplied.
5511 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5512 // function declarations whose behavior changes in C23.
5513 if (!LangOpts.requiresStrictPrototypes()) {
5514 bool IsBlock = false;
5515 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5516 switch (DeclType.Kind) {
5518 IsBlock = true;
5519 break;
5521 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5522 // We suppress the warning when there's no LParen location, as this
5523 // indicates the declaration was an implicit declaration, which gets
5524 // warned about separately via -Wimplicit-function-declaration. We also
5525 // suppress the warning when we know the function has a prototype.
5526 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5527 FTI.getLParenLoc().isValid())
5528 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5529 << IsBlock
5530 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5531 IsBlock = false;
5532 break;
5533 }
5534 default:
5535 break;
5536 }
5537 }
5538 }
5539
5540 assert(!T.isNull() && "T must not be null after this point");
5541
5542 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5543 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5544 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5545
5546 // C++ 8.3.5p4:
5547 // A cv-qualifier-seq shall only be part of the function type
5548 // for a nonstatic member function, the function type to which a pointer
5549 // to member refers, or the top-level function type of a function typedef
5550 // declaration.
5551 //
5552 // Core issue 547 also allows cv-qualifiers on function types that are
5553 // top-level template type arguments.
5554 enum {
5555 NonMember,
5556 Member,
5557 ExplicitObjectMember,
5558 DeductionGuide
5559 } Kind = NonMember;
5561 Kind = DeductionGuide;
5562 else if (!D.getCXXScopeSpec().isSet()) {
5566 Kind = Member;
5567 } else {
5569 if (!DC || DC->isRecord())
5570 Kind = Member;
5571 }
5572
5573 if (Kind == Member) {
5574 unsigned I;
5575 if (D.isFunctionDeclarator(I)) {
5576 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5577 if (Chunk.Fun.NumParams) {
5578 auto *P = dyn_cast_or_null<ParmVarDecl>(Chunk.Fun.Params->Param);
5579 if (P && P->isExplicitObjectParameter())
5580 Kind = ExplicitObjectMember;
5581 }
5582 }
5583 }
5584
5585 // C++11 [dcl.fct]p6 (w/DR1417):
5586 // An attempt to specify a function type with a cv-qualifier-seq or a
5587 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5588 // - the function type for a non-static member function,
5589 // - the function type to which a pointer to member refers,
5590 // - the top-level function type of a function typedef declaration or
5591 // alias-declaration,
5592 // - the type-id in the default argument of a type-parameter, or
5593 // - the type-id of a template-argument for a type-parameter
5594 //
5595 // C++23 [dcl.fct]p6 (P0847R7)
5596 // ... A member-declarator with an explicit-object-parameter-declaration
5597 // shall not include a ref-qualifier or a cv-qualifier-seq and shall not be
5598 // declared static or virtual ...
5599 //
5600 // FIXME: Checking this here is insufficient. We accept-invalid on:
5601 //
5602 // template<typename T> struct S { void f(T); };
5603 // S<int() const> s;
5604 //
5605 // ... for instance.
5606 if (IsQualifiedFunction &&
5607 // Check for non-static member function and not and
5608 // explicit-object-parameter-declaration
5609 (Kind != Member || D.isExplicitObjectMemberFunction() ||
5612 D.isStaticMember())) &&
5613 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5615 SourceLocation Loc = D.getBeginLoc();
5616 SourceRange RemovalRange;
5617 unsigned I;
5618 if (D.isFunctionDeclarator(I)) {
5620 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5621 assert(Chunk.Kind == DeclaratorChunk::Function);
5622
5623 if (Chunk.Fun.hasRefQualifier())
5624 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5625
5626 if (Chunk.Fun.hasMethodTypeQualifiers())
5628 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5629 SourceLocation SL) { RemovalLocs.push_back(SL); });
5630
5631 if (!RemovalLocs.empty()) {
5632 llvm::sort(RemovalLocs,
5634 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5635 Loc = RemovalLocs.front();
5636 }
5637 }
5638
5639 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5640 << Kind << D.isFunctionDeclarator() << T
5642 << FixItHint::CreateRemoval(RemovalRange);
5643
5644 // Strip the cv-qualifiers and ref-qualifiers from the type.
5647 EPI.RefQualifier = RQ_None;
5648
5649 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5650 EPI);
5651 // Rebuild any parens around the identifier in the function type.
5652 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5654 break;
5655 T = S.BuildParenType(T);
5656 }
5657 }
5658 }
5659
5660 // Apply any undistributed attributes from the declaration or declarator.
5661 ParsedAttributesView NonSlidingAttrs;
5662 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5663 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5664 NonSlidingAttrs.addAtEnd(&AL);
5665 }
5666 }
5667 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5669
5670 // Diagnose any ignored type attributes.
5671 state.diagnoseIgnoredTypeAttrs(T);
5672
5673 // C++0x [dcl.constexpr]p9:
5674 // A constexpr specifier used in an object declaration declares the object
5675 // as const.
5677 T->isObjectType())
5678 T.addConst();
5679
5680 // C++2a [dcl.fct]p4:
5681 // A parameter with volatile-qualified type is deprecated
5682 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5685 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5686
5687 // If there was an ellipsis in the declarator, the declaration declares a
5688 // parameter pack whose type may be a pack expansion type.
5689 if (D.hasEllipsis()) {
5690 // C++0x [dcl.fct]p13:
5691 // A declarator-id or abstract-declarator containing an ellipsis shall
5692 // only be used in a parameter-declaration. Such a parameter-declaration
5693 // is a parameter pack (14.5.3). [...]
5694 switch (D.getContext()) {
5698 // C++0x [dcl.fct]p13:
5699 // [...] When it is part of a parameter-declaration-clause, the
5700 // parameter pack is a function parameter pack (14.5.3). The type T
5701 // of the declarator-id of the function parameter pack shall contain
5702 // a template parameter pack; each template parameter pack in T is
5703 // expanded by the function parameter pack.
5704 //
5705 // We represent function parameter packs as function parameters whose
5706 // type is a pack expansion.
5707 if (!T->containsUnexpandedParameterPack() &&
5708 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5709 S.Diag(D.getEllipsisLoc(),
5710 diag::err_function_parameter_pack_without_parameter_packs)
5711 << T << D.getSourceRange();
5713 } else {
5714 T = Context.getPackExpansionType(T, std::nullopt,
5715 /*ExpectPackInType=*/false);
5716 }
5717 break;
5719 // C++0x [temp.param]p15:
5720 // If a template-parameter is a [...] is a parameter-declaration that
5721 // declares a parameter pack (8.3.5), then the template-parameter is a
5722 // template parameter pack (14.5.3).
5723 //
5724 // Note: core issue 778 clarifies that, if there are any unexpanded
5725 // parameter packs in the type of the non-type template parameter, then
5726 // it expands those parameter packs.
5727 if (T->containsUnexpandedParameterPack())
5728 T = Context.getPackExpansionType(T, std::nullopt);
5729 else
5730 S.Diag(D.getEllipsisLoc(),
5731 LangOpts.CPlusPlus11
5732 ? diag::warn_cxx98_compat_variadic_templates
5733 : diag::ext_variadic_templates);
5734 break;
5735
5738 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5739 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
5760 // FIXME: We may want to allow parameter packs in block-literal contexts
5761 // in the future.
5762 S.Diag(D.getEllipsisLoc(),
5763 diag::err_ellipsis_in_declarator_not_parameter);
5765 break;
5766 }
5767 }
5768
5769 assert(!T.isNull() && "T must not be null at the end of this function");
5770 if (!AreDeclaratorChunksValid)
5771 return Context.getTrivialTypeSourceInfo(T);
5772
5773 if (state.didParseHLSLParamMod() && !T->isConstantArrayType())
5774 T = S.HLSL().getInoutParameterType(T);
5775 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5776}
5777
5779 // Determine the type of the declarator. Not all forms of declarator
5780 // have a type.
5781
5782 TypeProcessingState state(*this, D);
5783
5784 TypeSourceInfo *ReturnTypeInfo = nullptr;
5785 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5786 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5787 inferARCWriteback(state, T);
5788
5789 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5790}
5791
5793 QualType &declSpecTy,
5794 Qualifiers::ObjCLifetime ownership) {
5795 if (declSpecTy->isObjCRetainableType() &&
5796 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5797 Qualifiers qs;
5798 qs.addObjCLifetime(ownership);
5799 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5800 }
5801}
5802
5803static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5804 Qualifiers::ObjCLifetime ownership,
5805 unsigned chunkIndex) {
5806 Sema &S = state.getSema();
5807 Declarator &D = state.getDeclarator();
5808
5809 // Look for an explicit lifetime attribute.
5810 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5811 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5812 return;
5813
5814 const char *attrStr = nullptr;
5815 switch (ownership) {
5816 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5817 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5818 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5819 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5820 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5821 }
5822
5823 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5824 Arg->setIdentifierInfo(&S.Context.Idents.get(attrStr));
5825
5826 ArgsUnion Args(Arg);
5827
5828 // If there wasn't one, add one (with an invalid source location
5829 // so that we don't make an AttributedType for it).
5830 ParsedAttr *attr =
5831 D.getAttributePool().create(&S.Context.Idents.get("objc_ownership"),
5833 /*args*/ &Args, 1, ParsedAttr::Form::GNU());
5834 chunk.getAttrs().addAtEnd(attr);
5835 // TODO: mark whether we did this inference?
5836}
5837
5838/// Used for transferring ownership in casts resulting in l-values.
5839static void transferARCOwnership(TypeProcessingState &state,
5840 QualType &declSpecTy,
5841 Qualifiers::ObjCLifetime ownership) {
5842 Sema &S = state.getSema();
5843 Declarator &D = state.getDeclarator();
5844
5845 int inner = -1;
5846 bool hasIndirection = false;
5847 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5848 DeclaratorChunk &chunk = D.getTypeObject(i);
5849 switch (chunk.Kind) {
5851 // Ignore parens.
5852 break;
5853
5857 if (inner != -1)
5858 hasIndirection = true;
5859 inner = i;
5860 break;
5861
5863 if (inner != -1)
5864 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5865 return;
5866
5870 return;
5871 }
5872 }
5873
5874 if (inner == -1)
5875 return;
5876
5877 DeclaratorChunk &chunk = D.getTypeObject(inner);
5878 if (chunk.Kind == DeclaratorChunk::Pointer) {
5879 if (declSpecTy->isObjCRetainableType())
5880 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5881 if (declSpecTy->isObjCObjectType() && hasIndirection)
5882 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5883 } else {
5884 assert(chunk.Kind == DeclaratorChunk::Array ||
5886 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5887 }
5888}
5889
5891 TypeProcessingState state(*this, D);
5892
5893 TypeSourceInfo *ReturnTypeInfo = nullptr;
5894 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5895
5896 if (getLangOpts().ObjC) {
5897 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5898 if (ownership != Qualifiers::OCL_None)
5899 transferARCOwnership(state, declSpecTy, ownership);
5900 }
5901
5902 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5903}
5904
5906 TypeProcessingState &State) {
5907 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5908}
5909
5911 TypeProcessingState &State) {
5913 State.getSema().HLSL().TakeLocForHLSLAttribute(TL.getTypePtr());
5914 TL.setSourceRange(LocInfo.Range);
5916}
5917
5919 const ParsedAttributesView &Attrs) {
5920 for (const ParsedAttr &AL : Attrs) {
5921 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
5922 MTL.setAttrNameLoc(AL.getLoc());
5923 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
5924 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
5926 return;
5927 }
5928 }
5929
5930 llvm_unreachable("no matrix_type attribute found at the expected location!");
5931}
5932
5933static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5934 SourceLocation Loc;
5935 switch (Chunk.Kind) {
5940 llvm_unreachable("cannot be _Atomic qualified");
5941
5943 Loc = Chunk.Ptr.AtomicQualLoc;
5944 break;
5945
5949 // FIXME: Provide a source location for the _Atomic keyword.
5950 break;
5951 }
5952
5953 ATL.setKWLoc(Loc);
5955}
5956
5957namespace {
5958 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5959 Sema &SemaRef;
5960 ASTContext &Context;
5961 TypeProcessingState &State;
5962 const DeclSpec &DS;
5963
5964 public:
5965 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
5966 const DeclSpec &DS)
5967 : SemaRef(S), Context(Context), State(State), DS(DS) {}
5968
5969 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5970 Visit(TL.getModifiedLoc());
5971 fillAttributedTypeLoc(TL, State);
5972 }
5973 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
5974 Visit(TL.getWrappedLoc());
5975 }
5976 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
5977 Visit(TL.getWrappedLoc());
5978 }
5979 void VisitHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL) {
5980 Visit(TL.getWrappedLoc());
5982 }
5983 void VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {}
5984 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5985 Visit(TL.getInnerLoc());
5986 TL.setExpansionLoc(
5987 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5988 }
5989 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5990 Visit(TL.getUnqualifiedLoc());
5991 }
5992 // Allow to fill pointee's type locations, e.g.,
5993 // int __attr * __attr * __attr *p;
5994 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
5995 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5996 if (DS.getTypeSpecType() == TST_typename) {
5997 TypeSourceInfo *TInfo = nullptr;
5999 if (TInfo) {
6000 TL.copy(TInfo->getTypeLoc().castAs<TypedefTypeLoc>());
6001 return;
6002 }
6003 }
6004 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6005 ? DS.getTypeSpecTypeLoc()
6006 : SourceLocation(),
6009 }
6010 void VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6011 if (DS.getTypeSpecType() == TST_typename) {
6012 TypeSourceInfo *TInfo = nullptr;
6014 if (TInfo) {
6015 TL.copy(TInfo->getTypeLoc().castAs<UnresolvedUsingTypeLoc>());
6016 return;
6017 }
6018 }
6019 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6020 ? DS.getTypeSpecTypeLoc()
6021 : SourceLocation(),
6024 }
6025 void VisitUsingTypeLoc(UsingTypeLoc TL) {
6026 if (DS.getTypeSpecType() == TST_typename) {
6027 TypeSourceInfo *TInfo = nullptr;
6029 if (TInfo) {
6030 TL.copy(TInfo->getTypeLoc().castAs<UsingTypeLoc>());
6031 return;
6032 }
6033 }
6034 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6035 ? DS.getTypeSpecTypeLoc()
6036 : SourceLocation(),
6039 }
6040 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6042 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6043 // addition field. What we have is good enough for display of location
6044 // of 'fixit' on interface name.
6045 TL.setNameEndLoc(DS.getEndLoc());
6046 }
6047 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6048 TypeSourceInfo *RepTInfo = nullptr;
6049 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6050 TL.copy(RepTInfo->getTypeLoc());
6051 }
6052 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6053 TypeSourceInfo *RepTInfo = nullptr;
6054 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6055 TL.copy(RepTInfo->getTypeLoc());
6056 }
6057 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6058 TypeSourceInfo *TInfo = nullptr;
6060
6061 // If we got no declarator info from previous Sema routines,
6062 // just fill with the typespec loc.
6063 if (!TInfo) {
6064 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
6065 return;
6066 }
6067
6068 TypeLoc OldTL = TInfo->getTypeLoc();
6069 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6070 assert(TL.getRAngleLoc() ==
6071 OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6072 }
6073 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6078 }
6079 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6084 assert(DS.getRepAsType());
6085 TypeSourceInfo *TInfo = nullptr;
6087 TL.setUnmodifiedTInfo(TInfo);
6088 }
6089 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6093 }
6094 void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6097 }
6098 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6099 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6102 assert(DS.getRepAsType());
6103 TypeSourceInfo *TInfo = nullptr;
6105 TL.setUnderlyingTInfo(TInfo);
6106 }
6107 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6108 // By default, use the source location of the type specifier.
6110 if (TL.needsExtraLocalData()) {
6111 // Set info for the written builtin specifiers.
6113 // Try to have a meaningful source location.
6114 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6116 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6118 }
6119 }
6120 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6121 assert(DS.getTypeSpecType() == TST_typename);
6122 TypeSourceInfo *TInfo = nullptr;
6124 assert(TInfo);
6125 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6126 }
6127 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6128 assert(DS.getTypeSpecType() == TST_auto ||
6135 if (!DS.isConstrainedAuto())
6136 return;
6137 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6138 if (!TemplateId)
6139 return;
6140
6141 NestedNameSpecifierLoc NNS =
6142 (DS.getTypeSpecScope().isNotEmpty()
6144 : NestedNameSpecifierLoc());
6145 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6146 TemplateId->RAngleLoc);
6147 if (TemplateId->NumArgs > 0) {
6148 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6149 TemplateId->NumArgs);
6150 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6151 }
6152 DeclarationNameInfo DNI = DeclarationNameInfo(
6153 TL.getTypePtr()->getTypeConstraintConcept()->getDeclName(),
6154 TemplateId->TemplateNameLoc);
6155
6156 NamedDecl *FoundDecl;
6157 if (auto TN = TemplateId->Template.get();
6158 UsingShadowDecl *USD = TN.getAsUsingShadowDecl())
6159 FoundDecl = cast<NamedDecl>(USD);
6160 else
6161 FoundDecl = cast_if_present<NamedDecl>(TN.getAsTemplateDecl());
6162
6163 auto *CR = ConceptReference::Create(
6164 Context, NNS, TemplateId->TemplateKWLoc, DNI, FoundDecl,
6165 /*NamedDecl=*/TL.getTypePtr()->getTypeConstraintConcept(),
6166 ASTTemplateArgumentListInfo::Create(Context, TemplateArgsInfo));
6167 TL.setConceptReference(CR);
6168 }
6169 void VisitDeducedTemplateSpecializationTypeLoc(
6170 DeducedTemplateSpecializationTypeLoc TL) {
6171 assert(DS.getTypeSpecType() == TST_typename);
6172 TypeSourceInfo *TInfo = nullptr;
6174 assert(TInfo);
6175 TL.copy(
6176 TInfo->getTypeLoc().castAs<DeducedTemplateSpecializationTypeLoc>());
6177 }
6178 void VisitTagTypeLoc(TagTypeLoc TL) {
6179 if (DS.getTypeSpecType() == TST_typename) {
6180 TypeSourceInfo *TInfo = nullptr;
6182 if (TInfo) {
6183 TL.copy(TInfo->getTypeLoc().castAs<TagTypeLoc>());
6184 return;
6185 }
6186 }
6187 TL.setElaboratedKeywordLoc(TL.getTypePtr()->getKeyword() !=
6188 ElaboratedTypeKeyword::None
6189 ? DS.getTypeSpecTypeLoc()
6190 : SourceLocation());
6193 }
6194 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6195 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6196 // or an _Atomic qualifier.
6200
6201 TypeSourceInfo *TInfo = nullptr;
6203 assert(TInfo);
6205 } else {
6206 TL.setKWLoc(DS.getAtomicSpecLoc());
6207 // No parens, to indicate this was spelled as an _Atomic qualifier.
6208 TL.setParensRange(SourceRange());
6209 Visit(TL.getValueLoc());
6210 }
6211 }
6212
6213 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6215
6216 TypeSourceInfo *TInfo = nullptr;
6219 }
6220
6221 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6223 }
6224
6225 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6227 }
6228
6229 void VisitTypeLoc(TypeLoc TL) {
6230 // FIXME: add other typespec types and change this to an assert.
6231 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6232 }
6233 };
6234
6235 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6236 ASTContext &Context;
6237 TypeProcessingState &State;
6238 const DeclaratorChunk &Chunk;
6239
6240 public:
6241 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6242 const DeclaratorChunk &Chunk)
6243 : Context(Context), State(State), Chunk(Chunk) {}
6244
6245 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6246 llvm_unreachable("qualified type locs not expected here!");
6247 }
6248 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6249 llvm_unreachable("decayed type locs not expected here!");
6250 }
6251 void VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6252 llvm_unreachable("array parameter type locs not expected here!");
6253 }
6254
6255 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6256 fillAttributedTypeLoc(TL, State);
6257 }
6258 void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
6259 // nothing
6260 }
6261 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6262 // nothing
6263 }
6264 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
6265 // nothing
6266 }
6267 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6268 // nothing
6269 }
6270 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6271 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6272 TL.setCaretLoc(Chunk.Loc);
6273 }
6274 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6275 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6276 TL.setStarLoc(Chunk.Loc);
6277 }
6278 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6279 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6280 TL.setStarLoc(Chunk.Loc);
6281 }
6282 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6283 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6284 TL.setStarLoc(Chunk.Mem.StarLoc);
6285 TL.setQualifierLoc(Chunk.Mem.Scope().getWithLocInContext(Context));
6286 }
6287 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6288 assert(Chunk.Kind == DeclaratorChunk::Reference);
6289 // 'Amp' is misleading: this might have been originally
6290 /// spelled with AmpAmp.
6291 TL.setAmpLoc(Chunk.Loc);
6292 }
6293 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6294 assert(Chunk.Kind == DeclaratorChunk::Reference);
6295 assert(!Chunk.Ref.LValueRef);
6296 TL.setAmpAmpLoc(Chunk.Loc);
6297 }
6298 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6299 assert(Chunk.Kind == DeclaratorChunk::Array);
6300 TL.setLBracketLoc(Chunk.Loc);
6301 TL.setRBracketLoc(Chunk.EndLoc);
6302 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6303 }
6304 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6305 assert(Chunk.Kind == DeclaratorChunk::Function);
6306 TL.setLocalRangeBegin(Chunk.Loc);
6307 TL.setLocalRangeEnd(Chunk.EndLoc);
6308
6309 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6310 TL.setLParenLoc(FTI.getLParenLoc());
6311 TL.setRParenLoc(FTI.getRParenLoc());
6312 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6313 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6314 TL.setParam(tpi++, Param);
6315 }
6317 }
6318 void VisitParenTypeLoc(ParenTypeLoc TL) {
6319 assert(Chunk.Kind == DeclaratorChunk::Paren);
6320 TL.setLParenLoc(Chunk.Loc);
6321 TL.setRParenLoc(Chunk.EndLoc);
6322 }
6323 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6324 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6325 TL.setKWLoc(Chunk.Loc);
6326 }
6327 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6328 TL.setNameLoc(Chunk.Loc);
6329 }
6330 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6331 TL.setExpansionLoc(Chunk.Loc);
6332 }
6333 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6334 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6335 TL.setNameLoc(Chunk.Loc);
6336 }
6337 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6338 TL.setNameLoc(Chunk.Loc);
6339 }
6340 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6341 fillAtomicQualLoc(TL, Chunk);
6342 }
6343 void
6344 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6345 TL.setNameLoc(Chunk.Loc);
6346 }
6347 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6348 fillMatrixTypeLoc(TL, Chunk.getAttrs());
6349 }
6350
6351 void VisitTypeLoc(TypeLoc TL) {
6352 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6353 }
6354 };
6355} // end anonymous namespace
6356
6357static void
6359 const ParsedAttributesView &Attrs) {
6360 for (const ParsedAttr &AL : Attrs) {
6361 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6362 DASTL.setAttrNameLoc(AL.getLoc());
6363 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6365 return;
6366 }
6367 }
6368
6369 llvm_unreachable(
6370 "no address_space attribute found at the expected location!");
6371}
6372
6373/// Create and instantiate a TypeSourceInfo with type source information.
6374///
6375/// \param T QualType referring to the type as written in source code.
6376///
6377/// \param ReturnTypeInfo For declarators whose return type does not show
6378/// up in the normal place in the declaration specifiers (such as a C++
6379/// conversion function), this pointer will refer to a type source information
6380/// for that return type.
6381static TypeSourceInfo *
6382GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6383 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6384 Sema &S = State.getSema();
6385 Declarator &D = State.getDeclarator();
6386
6388 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6389
6390 // Handle parameter packs whose type is a pack expansion.
6391 if (isa<PackExpansionType>(T)) {
6392 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6393 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6394 }
6395
6396 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6397 // Microsoft property fields can have multiple sizeless array chunks
6398 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6399 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6401 continue;
6402
6403 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6404 // declarator chunk.
6405 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6407 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6408 }
6409
6410 bool HasDesugaredTypeLoc = true;
6411 while (HasDesugaredTypeLoc) {
6412 switch (CurrTL.getTypeLocClass()) {
6413 case TypeLoc::MacroQualified: {
6414 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6415 TL.setExpansionLoc(
6416 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6417 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6418 break;
6419 }
6420
6421 case TypeLoc::Attributed: {
6422 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6423 fillAttributedTypeLoc(TL, State);
6424 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6425 break;
6426 }
6427
6428 case TypeLoc::Adjusted:
6429 case TypeLoc::BTFTagAttributed: {
6430 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6431 break;
6432 }
6433
6434 case TypeLoc::DependentAddressSpace: {
6435 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6437 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6438 break;
6439 }
6440
6441 default:
6442 HasDesugaredTypeLoc = false;
6443 break;
6444 }
6445 }
6446
6447 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6448 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6449 }
6450
6451 // If we have different source information for the return type, use
6452 // that. This really only applies to C++ conversion functions.
6453 if (ReturnTypeInfo) {
6454 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6455 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6456 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6457 } else {
6458 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6459 }
6460
6461 return TInfo;
6462}
6463
6464/// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6466 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6467 // and Sema during declaration parsing. Try deallocating/caching them when
6468 // it's appropriate, instead of allocating them and keeping them around.
6469 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(sizeof(LocInfoType),
6470 alignof(LocInfoType));
6471 new (LocT) LocInfoType(T, TInfo);
6472 assert(LocT->getTypeClass() != T->getTypeClass() &&
6473 "LocInfoType's TypeClass conflicts with an existing Type class");
6474 return ParsedType::make(QualType(LocT, 0));
6475}
6476
6478 const PrintingPolicy &Policy) const {
6479 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6480 " was used directly instead of getting the QualType through"
6481 " GetTypeFromParser");
6482}
6483
6485 // C99 6.7.6: Type names have no identifier. This is already validated by
6486 // the parser.
6487 assert(D.getIdentifier() == nullptr &&
6488 "Type name should have no identifier!");
6489
6491 QualType T = TInfo->getType();
6492 if (D.isInvalidType())
6493 return true;
6494
6495 // Make sure there are no unused decl attributes on the declarator.
6496 // We don't want to do this for ObjC parameters because we're going
6497 // to apply them to the actual parameter declaration.
6498 // Likewise, we don't want to do this for alias declarations, because
6499 // we are actually going to build a declaration from this eventually.
6504
6505 if (getLangOpts().CPlusPlus) {
6506 // Check that there are no default arguments (C++ only).
6508 }
6509
6510 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
6511 const AutoType *AT = TL.getTypePtr();
6512 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
6513 }
6514 return CreateParsedType(T, TInfo);
6515}
6516
6517//===----------------------------------------------------------------------===//
6518// Type Attribute Processing
6519//===----------------------------------------------------------------------===//
6520
6521/// Build an AddressSpace index from a constant expression and diagnose any
6522/// errors related to invalid address_spaces. Returns true on successfully
6523/// building an AddressSpace index.
6524static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6525 const Expr *AddrSpace,
6526 SourceLocation AttrLoc) {
6527 if (!AddrSpace->isValueDependent()) {
6528 std::optional<llvm::APSInt> OptAddrSpace =
6529 AddrSpace->getIntegerConstantExpr(S.Context);
6530 if (!OptAddrSpace) {
6531 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6532 << "'address_space'" << AANT_ArgumentIntegerConstant
6533 << AddrSpace->getSourceRange();
6534 return false;
6535 }
6536 llvm::APSInt &addrSpace = *OptAddrSpace;
6537
6538 // Bounds checking.
6539 if (addrSpace.isSigned()) {
6540 if (addrSpace.isNegative()) {
6541 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6542 << AddrSpace->getSourceRange();
6543 return false;
6544 }
6545 addrSpace.setIsSigned(false);
6546 }
6547
6548 llvm::APSInt max(addrSpace.getBitWidth());
6549 max =
6551
6552 if (addrSpace > max) {
6553 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6554 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6555 return false;
6556 }
6557
6558 ASIdx =
6559 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6560 return true;
6561 }
6562
6563 // Default value for DependentAddressSpaceTypes
6564 ASIdx = LangAS::Default;
6565 return true;
6566}
6567
6569 SourceLocation AttrLoc) {
6570 if (!AddrSpace->isValueDependent()) {
6571 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6572 AttrLoc))
6573 return QualType();
6574
6575 return Context.getAddrSpaceQualType(T, ASIdx);
6576 }
6577
6578 // A check with similar intentions as checking if a type already has an
6579 // address space except for on a dependent types, basically if the
6580 // current type is already a DependentAddressSpaceType then its already
6581 // lined up to have another address space on it and we can't have
6582 // multiple address spaces on the one pointer indirection
6583 if (T->getAs<DependentAddressSpaceType>()) {
6584 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6585 return QualType();
6586 }
6587
6588 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6589}
6590
6592 SourceLocation AttrLoc) {
6593 LangAS ASIdx;
6594 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6595 return QualType();
6596 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6597}
6598
6600 TypeProcessingState &State) {
6601 Sema &S = State.getSema();
6602
6603 // This attribute is only supported in C.
6604 // FIXME: we should implement checkCommonAttributeFeatures() in SemaAttr.cpp
6605 // such that it handles type attributes, and then call that from
6606 // processTypeAttrs() instead of one-off checks like this.
6607 if (!Attr.diagnoseLangOpts(S)) {
6608 Attr.setInvalid();
6609 return;
6610 }
6611
6612 // Check the number of attribute arguments.
6613 if (Attr.getNumArgs() != 1) {
6614 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6615 << Attr << 1;
6616 Attr.setInvalid();
6617 return;
6618 }
6619
6620 // Ensure the argument is a string.
6621 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6622 if (!StrLiteral) {
6623 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6625 Attr.setInvalid();
6626 return;
6627 }
6628
6629 ASTContext &Ctx = S.Context;
6630 StringRef BTFTypeTag = StrLiteral->getString();
6631 Type = State.getBTFTagAttributedType(
6632 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6633}
6634
6635/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6636/// specified type. The attribute contains 1 argument, the id of the address
6637/// space for the type.
6639 const ParsedAttr &Attr,
6640 TypeProcessingState &State) {
6641 Sema &S = State.getSema();
6642
6643 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6644 // qualified by an address-space qualifier."
6645 if (Type->isFunctionType()) {
6646 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6647 Attr.setInvalid();
6648 return;
6649 }
6650
6651 LangAS ASIdx;
6652 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6653
6654 // Check the attribute arguments.
6655 if (Attr.getNumArgs() != 1) {
6656 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6657 << 1;
6658 Attr.setInvalid();
6659 return;
6660 }
6661
6662 Expr *ASArgExpr = Attr.getArgAsExpr(0);
6663 LangAS ASIdx;
6664 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6665 Attr.setInvalid();
6666 return;
6667 }
6668
6669 ASTContext &Ctx = S.Context;
6670 auto *ASAttr =
6671 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6672
6673 // If the expression is not value dependent (not templated), then we can
6674 // apply the address space qualifiers just to the equivalent type.
6675 // Otherwise, we make an AttributedType with the modified and equivalent
6676 // type the same, and wrap it in a DependentAddressSpaceType. When this
6677 // dependent type is resolved, the qualifier is added to the equivalent type
6678 // later.
6679 QualType T;
6680 if (!ASArgExpr->isValueDependent()) {
6681 QualType EquivType =
6682 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6683 if (EquivType.isNull()) {
6684 Attr.setInvalid();
6685 return;
6686 }
6687 T = State.getAttributedType(ASAttr, Type, EquivType);
6688 } else {
6689 T = State.getAttributedType(ASAttr, Type, Type);
6690 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6691 }
6692
6693 if (!T.isNull())
6694 Type = T;
6695 else
6696 Attr.setInvalid();
6697 } else {
6698 // The keyword-based type attributes imply which address space to use.
6699 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6700 : Attr.asOpenCLLangAS();
6701 if (S.getLangOpts().HLSL)
6702 ASIdx = Attr.asHLSLLangAS();
6703
6704 if (ASIdx == LangAS::Default)
6705 llvm_unreachable("Invalid address space");
6706
6707 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6708 Attr.getLoc())) {
6709 Attr.setInvalid();
6710 return;
6711 }
6712
6714 }
6715}
6716
6718 TypeProcessingState &State) {
6719 Sema &S = State.getSema();
6720
6721 // Check for -fexperimental-overflow-behavior-types
6722 if (!S.getLangOpts().OverflowBehaviorTypes) {
6723 S.Diag(Attr.getLoc(), diag::warn_overflow_behavior_attribute_disabled)
6724 << Attr << 1;
6725 Attr.setInvalid();
6726 return;
6727 }
6728
6729 // Check the number of attribute arguments.
6730 if (Attr.getNumArgs() != 1) {
6731 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6732 << Attr << 1;
6733 Attr.setInvalid();
6734 return;
6735 }
6736
6737 // Check that the underlying type is an integer type
6738 if (!Type->isIntegerType()) {
6739 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_non_integer_type)
6740 << Attr << Type.getAsString() << 0; // 0 for attribute
6741 Attr.setInvalid();
6742 return;
6743 }
6744
6745 StringRef KindName = "";
6746 IdentifierInfo *Ident = nullptr;
6747
6748 if (Attr.isArgIdent(0)) {
6749 Ident = Attr.getArgAsIdent(0)->getIdentifierInfo();
6750 KindName = Ident->getName();
6751 }
6752
6753 // Support identifier or string argument types. Failure to provide one of
6754 // these two types results in a diagnostic that hints towards using string
6755 // arguments (either "wrap" or "trap") as this is the most common use
6756 // pattern.
6757 if (!Ident) {
6758 auto *Str = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6759 if (Str)
6760 KindName = Str->getString();
6761 else {
6762 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6764 Attr.setInvalid();
6765 return;
6766 }
6767 }
6768
6769 OverflowBehaviorType::OverflowBehaviorKind Kind;
6770 if (KindName == "wrap") {
6771 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
6772 } else if (KindName == "trap") {
6773 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
6774 } else {
6775 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_unknown_ident)
6776 << KindName << Attr;
6777 Attr.setInvalid();
6778 return;
6779 }
6780
6781 // Check for mixed specifier/attribute usage
6782 const DeclSpec &DS = State.getDeclarator().getDeclSpec();
6783 if (DS.isWrapSpecified() || DS.isTrapSpecified()) {
6784 // We have both specifier and attribute on the same type. If
6785 // OverflowBehaviorKinds are the same we can just warn.
6786 OverflowBehaviorType::OverflowBehaviorKind SpecifierKind =
6787 DS.isWrapSpecified() ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
6788 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
6789
6790 if (SpecifierKind != Kind) {
6791 StringRef SpecifierName = DS.isWrapSpecified() ? "wrap" : "trap";
6792 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors)
6793 << 1 << SpecifierName << KindName;
6794 Attr.setInvalid();
6795 return;
6796 }
6797 S.Diag(Attr.getLoc(), diag::warn_redundant_overflow_behaviors_mixed)
6798 << KindName;
6799 Attr.setInvalid();
6800 return;
6801 }
6802
6803 // Check for conflicting overflow behavior attributes
6804 if (const auto *ExistingOBT = Type->getAs<OverflowBehaviorType>()) {
6805 OverflowBehaviorType::OverflowBehaviorKind ExistingKind =
6806 ExistingOBT->getBehaviorKind();
6807 if (ExistingKind != Kind) {
6808 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors) << 0;
6809 if (Kind == OverflowBehaviorType::OverflowBehaviorKind::Trap) {
6810 Type = State.getOverflowBehaviorType(Kind,
6811 ExistingOBT->getUnderlyingType());
6812 }
6813 return;
6814 }
6815 } else {
6816 Type = State.getOverflowBehaviorType(Kind, Type);
6817 }
6818}
6819
6820/// handleObjCOwnershipTypeAttr - Process an objc_ownership
6821/// attribute on the specified type.
6822///
6823/// Returns 'true' if the attribute was handled.
6824static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6826 bool NonObjCPointer = false;
6827
6828 if (!type->isDependentType() && !type->isUndeducedType()) {
6829 if (const PointerType *ptr = type->getAs<PointerType>()) {
6830 QualType pointee = ptr->getPointeeType();
6831 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6832 return false;
6833 // It is important not to lose the source info that there was an attribute
6834 // applied to non-objc pointer. We will create an attributed type but
6835 // its type will be the same as the original type.
6836 NonObjCPointer = true;
6837 } else if (!type->isObjCRetainableType()) {
6838 return false;
6839 }
6840
6841 // Don't accept an ownership attribute in the declspec if it would
6842 // just be the return type of a block pointer.
6843 if (state.isProcessingDeclSpec()) {
6844 Declarator &D = state.getDeclarator();
6846 /*onlyBlockPointers=*/true))
6847 return false;
6848 }
6849 }
6850
6851 Sema &S = state.getSema();
6852 SourceLocation AttrLoc = attr.getLoc();
6853 if (AttrLoc.isMacroID())
6854 AttrLoc =
6856
6857 if (!attr.isArgIdent(0)) {
6858 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6860 attr.setInvalid();
6861 return true;
6862 }
6863
6864 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
6865 Qualifiers::ObjCLifetime lifetime;
6866 if (II->isStr("none"))
6868 else if (II->isStr("strong"))
6869 lifetime = Qualifiers::OCL_Strong;
6870 else if (II->isStr("weak"))
6871 lifetime = Qualifiers::OCL_Weak;
6872 else if (II->isStr("autoreleasing"))
6874 else {
6875 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6876 attr.setInvalid();
6877 return true;
6878 }
6879
6880 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6881 // outside of ARC mode.
6882 if (!S.getLangOpts().ObjCAutoRefCount &&
6883 lifetime != Qualifiers::OCL_Weak &&
6884 lifetime != Qualifiers::OCL_ExplicitNone) {
6885 return true;
6886 }
6887
6888 SplitQualType underlyingType = type.split();
6889
6890 // Check for redundant/conflicting ownership qualifiers.
6891 if (Qualifiers::ObjCLifetime previousLifetime
6892 = type.getQualifiers().getObjCLifetime()) {
6893 // If it's written directly, that's an error.
6895 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6896 << type;
6897 return true;
6898 }
6899
6900 // Otherwise, if the qualifiers actually conflict, pull sugar off
6901 // and remove the ObjCLifetime qualifiers.
6902 if (previousLifetime != lifetime) {
6903 // It's possible to have multiple local ObjCLifetime qualifiers. We
6904 // can't stop after we reach a type that is directly qualified.
6905 const Type *prevTy = nullptr;
6906 while (!prevTy || prevTy != underlyingType.Ty) {
6907 prevTy = underlyingType.Ty;
6908 underlyingType = underlyingType.getSingleStepDesugaredType();
6909 }
6910 underlyingType.Quals.removeObjCLifetime();
6911 }
6912 }
6913
6914 underlyingType.Quals.addObjCLifetime(lifetime);
6915
6916 if (NonObjCPointer) {
6917 StringRef name = attr.getAttrName()->getName();
6918 switch (lifetime) {
6921 break;
6922 case Qualifiers::OCL_Strong: name = "__strong"; break;
6923 case Qualifiers::OCL_Weak: name = "__weak"; break;
6924 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6925 }
6926 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6928 }
6929
6930 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6931 // because having both 'T' and '__unsafe_unretained T' exist in the type
6932 // system causes unfortunate widespread consistency problems. (For example,
6933 // they're not considered compatible types, and we mangle them identicially
6934 // as template arguments.) These problems are all individually fixable,
6935 // but it's easier to just not add the qualifier and instead sniff it out
6936 // in specific places using isObjCInertUnsafeUnretainedType().
6937 //
6938 // Doing this does means we miss some trivial consistency checks that
6939 // would've triggered in ARC, but that's better than trying to solve all
6940 // the coexistence problems with __unsafe_unretained.
6941 if (!S.getLangOpts().ObjCAutoRefCount &&
6942 lifetime == Qualifiers::OCL_ExplicitNone) {
6943 type = state.getAttributedType(
6945 type, type);
6946 return true;
6947 }
6948
6949 QualType origType = type;
6950 if (!NonObjCPointer)
6951 type = S.Context.getQualifiedType(underlyingType);
6952
6953 // If we have a valid source location for the attribute, use an
6954 // AttributedType instead.
6955 if (AttrLoc.isValid()) {
6956 type = state.getAttributedType(::new (S.Context)
6957 ObjCOwnershipAttr(S.Context, attr, II),
6958 origType, type);
6959 }
6960
6961 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6962 unsigned diagnostic, QualType type) {
6967 diagnostic, type, /*ignored*/ 0));
6968 } else {
6969 S.Diag(loc, diagnostic);
6970 }
6971 };
6972
6973 // Sometimes, __weak isn't allowed.
6974 if (lifetime == Qualifiers::OCL_Weak &&
6975 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6976
6977 // Use a specialized diagnostic if the runtime just doesn't support them.
6978 unsigned diagnostic =
6979 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6980 : diag::err_arc_weak_no_runtime);
6981
6982 // In any case, delay the diagnostic until we know what we're parsing.
6983 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6984
6985 attr.setInvalid();
6986 return true;
6987 }
6988
6989 // Forbid __weak for class objects marked as
6990 // objc_arc_weak_reference_unavailable
6991 if (lifetime == Qualifiers::OCL_Weak) {
6992 if (const ObjCObjectPointerType *ObjT =
6993 type->getAs<ObjCObjectPointerType>()) {
6994 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6995 if (Class->isArcWeakrefUnavailable()) {
6996 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6997 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6998 diag::note_class_declared);
6999 }
7000 }
7001 }
7002 }
7003
7004 return true;
7005}
7006
7007/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
7008/// attribute on the specified type. Returns true to indicate that
7009/// the attribute was handled, false to indicate that the type does
7010/// not permit the attribute.
7011static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7012 QualType &type) {
7013 Sema &S = state.getSema();
7014
7015 // Delay if this isn't some kind of pointer.
7016 if (!type->isPointerType() &&
7017 !type->isObjCObjectPointerType() &&
7018 !type->isBlockPointerType())
7019 return false;
7020
7021 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7022 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
7023 attr.setInvalid();
7024 return true;
7025 }
7026
7027 // Check the attribute arguments.
7028 if (!attr.isArgIdent(0)) {
7029 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
7031 attr.setInvalid();
7032 return true;
7033 }
7034 Qualifiers::GC GCAttr;
7035 if (attr.getNumArgs() > 1) {
7036 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
7037 << 1;
7038 attr.setInvalid();
7039 return true;
7040 }
7041
7042 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
7043 if (II->isStr("weak"))
7044 GCAttr = Qualifiers::Weak;
7045 else if (II->isStr("strong"))
7046 GCAttr = Qualifiers::Strong;
7047 else {
7048 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
7049 << attr << II;
7050 attr.setInvalid();
7051 return true;
7052 }
7053
7054 QualType origType = type;
7055 type = S.Context.getObjCGCQualType(origType, GCAttr);
7056
7057 // Make an attributed type to preserve the source information.
7058 if (attr.getLoc().isValid())
7059 type = state.getAttributedType(
7060 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
7061
7062 return true;
7063}
7064
7065namespace {
7066 /// A helper class to unwrap a type down to a function for the
7067 /// purposes of applying attributes there.
7068 ///
7069 /// Use:
7070 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
7071 /// if (unwrapped.isFunctionType()) {
7072 /// const FunctionType *fn = unwrapped.get();
7073 /// // change fn somehow
7074 /// T = unwrapped.wrap(fn);
7075 /// }
7076 struct FunctionTypeUnwrapper {
7077 enum WrapKind {
7078 Desugar,
7079 Attributed,
7080 Parens,
7081 Array,
7082 Pointer,
7083 BlockPointer,
7084 Reference,
7085 MemberPointer,
7086 MacroQualified,
7087 };
7088
7089 QualType Original;
7090 const FunctionType *Fn;
7091 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7092
7093 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7094 while (true) {
7095 const Type *Ty = T.getTypePtr();
7096 if (isa<FunctionType>(Ty)) {
7097 Fn = cast<FunctionType>(Ty);
7098 return;
7099 } else if (isa<ParenType>(Ty)) {
7100 T = cast<ParenType>(Ty)->getInnerType();
7101 Stack.push_back(Parens);
7102 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
7104 T = cast<ArrayType>(Ty)->getElementType();
7105 Stack.push_back(Array);
7106 } else if (isa<PointerType>(Ty)) {
7107 T = cast<PointerType>(Ty)->getPointeeType();
7108 Stack.push_back(Pointer);
7109 } else if (isa<BlockPointerType>(Ty)) {
7110 T = cast<BlockPointerType>(Ty)->getPointeeType();
7111 Stack.push_back(BlockPointer);
7112 } else if (isa<MemberPointerType>(Ty)) {
7113 T = cast<MemberPointerType>(Ty)->getPointeeType();
7114 Stack.push_back(MemberPointer);
7115 } else if (isa<ReferenceType>(Ty)) {
7116 T = cast<ReferenceType>(Ty)->getPointeeType();
7117 Stack.push_back(Reference);
7118 } else if (isa<AttributedType>(Ty)) {
7119 T = cast<AttributedType>(Ty)->getEquivalentType();
7120 Stack.push_back(Attributed);
7121 } else if (isa<MacroQualifiedType>(Ty)) {
7122 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
7123 Stack.push_back(MacroQualified);
7124 } else {
7125 const Type *DTy = Ty->getUnqualifiedDesugaredType();
7126 if (Ty == DTy) {
7127 Fn = nullptr;
7128 return;
7129 }
7130
7131 T = QualType(DTy, 0);
7132 Stack.push_back(Desugar);
7133 }
7134 }
7135 }
7136
7137 bool isFunctionType() const { return (Fn != nullptr); }
7138 const FunctionType *get() const { return Fn; }
7139
7140 QualType wrap(Sema &S, const FunctionType *New) {
7141 // If T wasn't modified from the unwrapped type, do nothing.
7142 if (New == get()) return Original;
7143
7144 Fn = New;
7145 return wrap(S.Context, Original, 0);
7146 }
7147
7148 private:
7149 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7150 if (I == Stack.size())
7151 return C.getQualifiedType(Fn, Old.getQualifiers());
7152
7153 // Build up the inner type, applying the qualifiers from the old
7154 // type to the new type.
7155 SplitQualType SplitOld = Old.split();
7156
7157 // As a special case, tail-recurse if there are no qualifiers.
7158 if (SplitOld.Quals.empty())
7159 return wrap(C, SplitOld.Ty, I);
7160 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
7161 }
7162
7163 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7164 if (I == Stack.size()) return QualType(Fn, 0);
7165
7166 switch (static_cast<WrapKind>(Stack[I++])) {
7167 case Desugar:
7168 // This is the point at which we potentially lose source
7169 // information.
7170 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
7171
7172 case Attributed:
7173 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7174
7175 case Parens: {
7176 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7177 return C.getParenType(New);
7178 }
7179
7180 case MacroQualified:
7181 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7182
7183 case Array: {
7184 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7185 QualType New = wrap(C, CAT->getElementType(), I);
7186 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7187 CAT->getSizeModifier(),
7188 CAT->getIndexTypeCVRQualifiers());
7189 }
7190
7191 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7192 QualType New = wrap(C, VAT->getElementType(), I);
7193 return C.getVariableArrayType(New, VAT->getSizeExpr(),
7194 VAT->getSizeModifier(),
7195 VAT->getIndexTypeCVRQualifiers());
7196 }
7197
7198 const auto *IAT = cast<IncompleteArrayType>(Old);
7199 QualType New = wrap(C, IAT->getElementType(), I);
7200 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7201 IAT->getIndexTypeCVRQualifiers());
7202 }
7203
7204 case Pointer: {
7205 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7206 return C.getPointerType(New);
7207 }
7208
7209 case BlockPointer: {
7210 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7211 return C.getBlockPointerType(New);
7212 }
7213
7214 case MemberPointer: {
7215 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7216 QualType New = wrap(C, OldMPT->getPointeeType(), I);
7217 return C.getMemberPointerType(New, OldMPT->getQualifier(),
7218 OldMPT->getMostRecentCXXRecordDecl());
7219 }
7220
7221 case Reference: {
7222 const ReferenceType *OldRef = cast<ReferenceType>(Old);
7223 QualType New = wrap(C, OldRef->getPointeeType(), I);
7224 if (isa<LValueReferenceType>(OldRef))
7225 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7226 else
7227 return C.getRValueReferenceType(New);
7228 }
7229 }
7230
7231 llvm_unreachable("unknown wrapping kind");
7232 }
7233 };
7234} // end anonymous namespace
7235
7236static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7237 ParsedAttr &PAttr, QualType &Type) {
7238 Sema &S = State.getSema();
7239
7240 Attr *A;
7241 switch (PAttr.getKind()) {
7242 default: llvm_unreachable("Unknown attribute kind");
7243 case ParsedAttr::AT_Ptr32:
7245 break;
7246 case ParsedAttr::AT_Ptr64:
7248 break;
7249 case ParsedAttr::AT_SPtr:
7250 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7251 break;
7252 case ParsedAttr::AT_UPtr:
7253 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7254 break;
7255 }
7256
7257 std::bitset<attr::LastAttr> Attrs;
7258 QualType Desugared = Type;
7259 for (;;) {
7260 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7261 Desugared = TT->desugar();
7262 continue;
7263 }
7264 const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7265 if (!AT)
7266 break;
7267 Attrs[AT->getAttrKind()] = true;
7268 Desugared = AT->getModifiedType();
7269 }
7270
7271 // You cannot specify duplicate type attributes, so if the attribute has
7272 // already been applied, flag it.
7273 attr::Kind NewAttrKind = A->getKind();
7274 if (Attrs[NewAttrKind]) {
7275 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7276 return true;
7277 }
7278 Attrs[NewAttrKind] = true;
7279
7280 // You cannot have both __sptr and __uptr on the same type, nor can you
7281 // have __ptr32 and __ptr64.
7282 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7283 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7284 << "'__ptr32'"
7285 << "'__ptr64'" << /*isRegularKeyword=*/0;
7286 return true;
7287 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7288 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7289 << "'__sptr'"
7290 << "'__uptr'" << /*isRegularKeyword=*/0;
7291 return true;
7292 }
7293
7294 // Check the raw (i.e., desugared) Canonical type to see if it
7295 // is a pointer type.
7296 if (!isa<PointerType>(Desugared)) {
7297 // Pointer type qualifiers can only operate on pointer types, but not
7298 // pointer-to-member types.
7300 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7301 else
7302 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7303 return true;
7304 }
7305
7306 // Add address space to type based on its attributes.
7307 LangAS ASIdx = LangAS::Default;
7308 uint64_t PtrWidth =
7310 if (PtrWidth == 32) {
7311 if (Attrs[attr::Ptr64])
7312 ASIdx = LangAS::ptr64;
7313 else if (Attrs[attr::UPtr])
7314 ASIdx = LangAS::ptr32_uptr;
7315 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7316 if (S.Context.getTargetInfo().getTriple().isOSzOS() || Attrs[attr::UPtr])
7317 ASIdx = LangAS::ptr32_uptr;
7318 else
7319 ASIdx = LangAS::ptr32_sptr;
7320 }
7321
7322 QualType Pointee = Type->getPointeeType();
7323 if (ASIdx != LangAS::Default)
7324 Pointee = S.Context.getAddrSpaceQualType(
7325 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7326 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
7327 return false;
7328}
7329
7330static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7331 QualType &QT, ParsedAttr &PAttr) {
7332 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7333
7334 Sema &S = State.getSema();
7336
7337 std::bitset<attr::LastAttr> Attrs;
7338 attr::Kind NewAttrKind = A->getKind();
7339 const auto *AT = dyn_cast<AttributedType>(QT);
7340 while (AT) {
7341 Attrs[AT->getAttrKind()] = true;
7342 AT = dyn_cast<AttributedType>(AT->getModifiedType());
7343 }
7344
7345 // You cannot specify duplicate type attributes, so if the attribute has
7346 // already been applied, flag it.
7347 if (Attrs[NewAttrKind]) {
7348 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7349 return true;
7350 }
7351
7352 // Check that the type is a function pointer type.
7353 QualType Desugared = QT.getDesugaredType(S.Context);
7354 const auto *Ptr = dyn_cast<PointerType>(Desugared);
7355 if (!Ptr || !Ptr->getPointeeType()->isFunctionType()) {
7356 S.Diag(PAttr.getLoc(), diag::err_attribute_webassembly_funcref);
7357 return true;
7358 }
7359
7360 // Add address space to type based on its attributes.
7362 QualType Pointee = QT->getPointeeType();
7363 Pointee = S.Context.getAddrSpaceQualType(
7364 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7365 QT = State.getAttributedType(A, QT, S.Context.getPointerType(Pointee));
7366 return false;
7367}
7368
7369static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL,
7370 QualType &QT, ParsedAttr &PAttr) {
7371 if (TAL == TAL_DeclName)
7372 return;
7373
7374 Sema &S = State.getSema();
7375 auto &D = State.getDeclarator();
7376
7377 // If the attribute appears in declaration specifiers
7378 // it should be handled as a declaration attribute,
7379 // unless it's associated with a type or a function
7380 // prototype (i.e. appears on a parameter or result type).
7381 if (State.isProcessingDeclSpec()) {
7382 if (!(D.isPrototypeContext() ||
7383 D.getContext() == DeclaratorContext::TypeName))
7384 return;
7385
7386 if (auto *chunk = D.getInnermostNonParenChunk()) {
7387 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7388 const_cast<DeclaratorChunk *>(chunk)->getAttrs());
7389 return;
7390 }
7391 }
7392
7393 StringRef Str;
7394 if (!S.checkStringLiteralArgumentAttr(PAttr, 0, Str)) {
7395 PAttr.setInvalid();
7396 return;
7397 }
7398
7399 // If the attribute as attached to a paren move it closer to
7400 // the declarator. This can happen in block declarations when
7401 // an attribute is placed before `^` i.e. `(__attribute__((...)) ^)`.
7402 //
7403 // Note that it's actually invalid to use GNU style attributes
7404 // in a block but such cases are currently handled gracefully
7405 // but the parser and behavior should be consistent between
7406 // cases when attribute appears before/after block's result
7407 // type and inside (^).
7408 if (TAL == TAL_DeclChunk) {
7409 auto chunkIdx = State.getCurrentChunkIndex();
7410 if (chunkIdx >= 1 &&
7411 D.getTypeObject(chunkIdx).Kind == DeclaratorChunk::Paren) {
7412 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7413 D.getTypeObject(chunkIdx - 1).getAttrs());
7414 return;
7415 }
7416 }
7417
7418 auto *A = ::new (S.Context) SwiftAttrAttr(S.Context, PAttr, Str);
7419 QT = State.getAttributedType(A, QT, QT);
7420 PAttr.setUsedAsTypeAttr();
7421}
7422
7423/// Rebuild an attributed type without the nullability attribute on it.
7425 QualType Type) {
7426 auto Attributed = dyn_cast<AttributedType>(Type.getTypePtr());
7427 if (!Attributed)
7428 return Type;
7429
7430 // Skip the nullability attribute; we're done.
7431 if (Attributed->getImmediateNullability())
7432 return Attributed->getModifiedType();
7433
7434 // Build the modified type.
7436 Ctx, Attributed->getModifiedType());
7437 assert(Modified.getTypePtr() != Attributed->getModifiedType().getTypePtr());
7438 return Ctx.getAttributedType(Attributed->getAttrKind(), Modified,
7439 Attributed->getEquivalentType(),
7440 Attributed->getAttr());
7441}
7442
7443/// Map a nullability attribute kind to a nullability kind.
7445 switch (kind) {
7446 case ParsedAttr::AT_TypeNonNull:
7448
7449 case ParsedAttr::AT_TypeNullable:
7451
7452 case ParsedAttr::AT_TypeNullableResult:
7454
7455 case ParsedAttr::AT_TypeNullUnspecified:
7457
7458 default:
7459 llvm_unreachable("not a nullability attribute kind");
7460 }
7461}
7462
7464 Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT,
7465 NullabilityKind Nullability, SourceLocation NullabilityLoc,
7466 bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting) {
7467 bool Implicit = (State == nullptr);
7468 if (!Implicit)
7469 recordNullabilitySeen(S, NullabilityLoc);
7470
7471 // Check for existing nullability attributes on the type.
7472 QualType Desugared = QT;
7473 while (auto *Attributed = dyn_cast<AttributedType>(Desugared.getTypePtr())) {
7474 // Check whether there is already a null
7475 if (auto ExistingNullability = Attributed->getImmediateNullability()) {
7476 // Duplicated nullability.
7477 if (Nullability == *ExistingNullability) {
7478 if (Implicit)
7479 break;
7480
7481 S.Diag(NullabilityLoc, diag::warn_nullability_duplicate)
7482 << DiagNullabilityKind(Nullability, IsContextSensitive)
7483 << FixItHint::CreateRemoval(NullabilityLoc);
7484
7485 break;
7486 }
7487
7488 if (!OverrideExisting) {
7489 // Conflicting nullability.
7490 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7491 << DiagNullabilityKind(Nullability, IsContextSensitive)
7492 << DiagNullabilityKind(*ExistingNullability, false);
7493 return true;
7494 }
7495
7496 // Rebuild the attributed type, dropping the existing nullability.
7498 }
7499
7500 Desugared = Attributed->getModifiedType();
7501 }
7502
7503 // If there is already a different nullability specifier, complain.
7504 // This (unlike the code above) looks through typedefs that might
7505 // have nullability specifiers on them, which means we cannot
7506 // provide a useful Fix-It.
7507 if (auto ExistingNullability = Desugared->getNullability()) {
7508 if (Nullability != *ExistingNullability && !Implicit) {
7509 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7510 << DiagNullabilityKind(Nullability, IsContextSensitive)
7511 << DiagNullabilityKind(*ExistingNullability, false);
7512
7513 // Try to find the typedef with the existing nullability specifier.
7514 if (auto TT = Desugared->getAs<TypedefType>()) {
7515 TypedefNameDecl *typedefDecl = TT->getDecl();
7516 QualType underlyingType = typedefDecl->getUnderlyingType();
7517 if (auto typedefNullability =
7518 AttributedType::stripOuterNullability(underlyingType)) {
7519 if (*typedefNullability == *ExistingNullability) {
7520 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7521 << DiagNullabilityKind(*ExistingNullability, false);
7522 }
7523 }
7524 }
7525
7526 return true;
7527 }
7528 }
7529
7530 // If this definitely isn't a pointer type, reject the specifier.
7531 if (!Desugared->canHaveNullability() &&
7532 !(AllowOnArrayType && Desugared->isArrayType())) {
7533 if (!Implicit)
7534 S.Diag(NullabilityLoc, diag::err_nullability_nonpointer)
7535 << DiagNullabilityKind(Nullability, IsContextSensitive) << QT;
7536
7537 return true;
7538 }
7539
7540 // For the context-sensitive keywords/Objective-C property
7541 // attributes, require that the type be a single-level pointer.
7542 if (IsContextSensitive) {
7543 // Make sure that the pointee isn't itself a pointer type.
7544 const Type *pointeeType = nullptr;
7545 if (Desugared->isArrayType())
7546 pointeeType = Desugared->getArrayElementTypeNoTypeQual();
7547 else if (Desugared->isAnyPointerType())
7548 pointeeType = Desugared->getPointeeType().getTypePtr();
7549
7550 if (pointeeType && (pointeeType->isAnyPointerType() ||
7551 pointeeType->isObjCObjectPointerType() ||
7552 pointeeType->isMemberPointerType())) {
7553 S.Diag(NullabilityLoc, diag::err_nullability_cs_multilevel)
7554 << DiagNullabilityKind(Nullability, true) << QT;
7555 S.Diag(NullabilityLoc, diag::note_nullability_type_specifier)
7556 << DiagNullabilityKind(Nullability, false) << QT
7557 << FixItHint::CreateReplacement(NullabilityLoc,
7558 getNullabilitySpelling(Nullability));
7559 return true;
7560 }
7561 }
7562
7563 // Form the attributed type.
7564 if (State) {
7565 assert(PAttr);
7566 Attr *A = createNullabilityAttr(S.Context, *PAttr, Nullability);
7567 QT = State->getAttributedType(A, QT, QT);
7568 } else {
7569 QT = S.Context.getAttributedType(Nullability, QT, QT);
7570 }
7571 return false;
7572}
7573
7574static bool CheckNullabilityTypeSpecifier(TypeProcessingState &State,
7576 bool AllowOnArrayType) {
7578 SourceLocation NullabilityLoc = Attr.getLoc();
7579 bool IsContextSensitive = Attr.isContextSensitiveKeywordAttribute();
7580
7581 return CheckNullabilityTypeSpecifier(State.getSema(), &State, &Attr, Type,
7582 Nullability, NullabilityLoc,
7583 IsContextSensitive, AllowOnArrayType,
7584 /*overrideExisting*/ false);
7585}
7586
7588 NullabilityKind Nullability,
7589 SourceLocation DiagLoc,
7590 bool AllowArrayTypes,
7591 bool OverrideExisting) {
7593 *this, nullptr, nullptr, Type, Nullability, DiagLoc,
7594 /*isContextSensitive*/ false, AllowArrayTypes, OverrideExisting);
7595}
7596
7598 QualType T = VD->getType();
7599
7600 // Check that the variable's type can fit in the specified address space. This
7601 // is determined by how far a pointer in that address space can reach.
7602 llvm::APInt MaxSizeForAddrSpace =
7603 llvm::APInt::getMaxValue(Context.getTargetInfo().getPointerWidth(AS));
7604 std::optional<CharUnits> TSizeInChars = Context.getTypeSizeInCharsIfKnown(T);
7605 if (TSizeInChars && static_cast<uint64_t>(TSizeInChars->getQuantity()) >
7606 MaxSizeForAddrSpace.getZExtValue()) {
7607 Diag(VD->getLocation(), diag::err_type_too_large_for_address_space)
7608 << T << MaxSizeForAddrSpace;
7609 return false;
7610 }
7611
7612 return true;
7613}
7614
7615/// Check the application of the Objective-C '__kindof' qualifier to
7616/// the given type.
7617static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7618 ParsedAttr &attr) {
7619 Sema &S = state.getSema();
7620
7622 // Build the attributed type to record where __kindof occurred.
7623 type = state.getAttributedType(
7625 return false;
7626 }
7627
7628 // Find out if it's an Objective-C object or object pointer type;
7629 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7630 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7631 : type->getAs<ObjCObjectType>();
7632
7633 // If not, we can't apply __kindof.
7634 if (!objType) {
7635 // FIXME: Handle dependent types that aren't yet object types.
7636 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7637 << type;
7638 return true;
7639 }
7640
7641 // Rebuild the "equivalent" type, which pushes __kindof down into
7642 // the object type.
7643 // There is no need to apply kindof on an unqualified id type.
7644 QualType equivType = S.Context.getObjCObjectType(
7645 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7646 objType->getProtocols(),
7647 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7648
7649 // If we started with an object pointer type, rebuild it.
7650 if (ptrType) {
7651 equivType = S.Context.getObjCObjectPointerType(equivType);
7652 if (auto nullability = type->getNullability()) {
7653 // We create a nullability attribute from the __kindof attribute.
7654 // Make sure that will make sense.
7655 assert(attr.getAttributeSpellingListIndex() == 0 &&
7656 "multiple spellings for __kindof?");
7657 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7658 A->setImplicit(true);
7659 equivType = state.getAttributedType(A, equivType, equivType);
7660 }
7661 }
7662
7663 // Build the attributed type to record where __kindof occurred.
7664 type = state.getAttributedType(
7666 return false;
7667}
7668
7669/// Distribute a nullability type attribute that cannot be applied to
7670/// the type specifier to a pointer, block pointer, or member pointer
7671/// declarator, complaining if necessary.
7672///
7673/// \returns true if the nullability annotation was distributed, false
7674/// otherwise.
7675static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7677 Declarator &declarator = state.getDeclarator();
7678
7679 /// Attempt to move the attribute to the specified chunk.
7680 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7681 // If there is already a nullability attribute there, don't add
7682 // one.
7683 if (hasNullabilityAttr(chunk.getAttrs()))
7684 return false;
7685
7686 // Complain about the nullability qualifier being in the wrong
7687 // place.
7688 enum {
7689 PK_Pointer,
7690 PK_BlockPointer,
7691 PK_MemberPointer,
7692 PK_FunctionPointer,
7693 PK_MemberFunctionPointer,
7694 } pointerKind
7695 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7696 : PK_Pointer)
7697 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7698 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7699
7700 auto diag = state.getSema().Diag(attr.getLoc(),
7701 diag::warn_nullability_declspec)
7703 attr.isContextSensitiveKeywordAttribute())
7704 << type
7705 << static_cast<unsigned>(pointerKind);
7706
7707 // FIXME: MemberPointer chunks don't carry the location of the *.
7708 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7711 state.getSema().getPreprocessor().getLocForEndOfToken(
7712 chunk.Loc),
7713 " " + attr.getAttrName()->getName().str() + " ");
7714 }
7715
7716 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7717 chunk.getAttrs());
7718 return true;
7719 };
7720
7721 // Move it to the outermost pointer, member pointer, or block
7722 // pointer declarator.
7723 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7724 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7725 switch (chunk.Kind) {
7729 return moveToChunk(chunk, false);
7730
7733 continue;
7734
7736 // Try to move past the return type to a function/block/member
7737 // function pointer.
7739 declarator, i,
7740 /*onlyBlockPointers=*/false)) {
7741 return moveToChunk(*dest, true);
7742 }
7743
7744 return false;
7745
7746 // Don't walk through these.
7749 return false;
7750 }
7751 }
7752
7753 return false;
7754}
7755
7757 assert(!Attr.isInvalid());
7758 switch (Attr.getKind()) {
7759 default:
7760 llvm_unreachable("not a calling convention attribute");
7761 case ParsedAttr::AT_CDecl:
7762 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7763 case ParsedAttr::AT_FastCall:
7765 case ParsedAttr::AT_StdCall:
7767 case ParsedAttr::AT_ThisCall:
7769 case ParsedAttr::AT_RegCall:
7771 case ParsedAttr::AT_Pascal:
7773 case ParsedAttr::AT_SwiftCall:
7775 case ParsedAttr::AT_SwiftAsyncCall:
7777 case ParsedAttr::AT_VectorCall:
7779 case ParsedAttr::AT_AArch64VectorPcs:
7781 case ParsedAttr::AT_AArch64SVEPcs:
7783 case ParsedAttr::AT_ArmStreaming:
7785 case ParsedAttr::AT_Pcs: {
7786 // The attribute may have had a fixit applied where we treated an
7787 // identifier as a string literal. The contents of the string are valid,
7788 // but the form may not be.
7789 StringRef Str;
7790 if (Attr.isArgExpr(0))
7791 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7792 else
7793 Str = Attr.getArgAsIdent(0)->getIdentifierInfo()->getName();
7794 PcsAttr::PCSType Type;
7795 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7796 llvm_unreachable("already validated the attribute");
7797 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7798 }
7799 case ParsedAttr::AT_IntelOclBicc:
7801 case ParsedAttr::AT_MSABI:
7802 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7803 case ParsedAttr::AT_SysVABI:
7805 case ParsedAttr::AT_PreserveMost:
7807 case ParsedAttr::AT_PreserveAll:
7809 case ParsedAttr::AT_M68kRTD:
7811 case ParsedAttr::AT_PreserveNone:
7813 case ParsedAttr::AT_RISCVVectorCC:
7815 case ParsedAttr::AT_RISCVVLSCC: {
7816 // If the riscv_abi_vlen doesn't have any argument, we set set it to default
7817 // value 128.
7818 unsigned ABIVLen = 128;
7819 if (Attr.getNumArgs()) {
7820 std::optional<llvm::APSInt> MaybeABIVLen =
7821 Attr.getArgAsExpr(0)->getIntegerConstantExpr(Ctx);
7822 if (!MaybeABIVLen)
7823 llvm_unreachable("Invalid RISC-V ABI VLEN");
7824 ABIVLen = MaybeABIVLen->getZExtValue();
7825 }
7826
7827 return ::new (Ctx) RISCVVLSCCAttr(Ctx, Attr, ABIVLen);
7828 }
7829 }
7830 llvm_unreachable("unexpected attribute kind!");
7831}
7832
7833std::optional<FunctionEffectMode>
7834Sema::ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName) {
7835 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent())
7837
7838 std::optional<llvm::APSInt> ConditionValue =
7840 if (!ConditionValue) {
7841 // FIXME: err_attribute_argument_type doesn't quote the attribute
7842 // name but needs to; users are inconsistent.
7843 Diag(CondExpr->getExprLoc(), diag::err_attribute_argument_type)
7844 << AttributeName << AANT_ArgumentIntegerConstant
7845 << CondExpr->getSourceRange();
7846 return std::nullopt;
7847 }
7848 return !ConditionValue->isZero() ? FunctionEffectMode::True
7850}
7851
7852static bool
7853handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState,
7854 ParsedAttr &PAttr, QualType &QT,
7855 FunctionTypeUnwrapper &Unwrapped) {
7856 // Delay if this is not a function type.
7857 if (!Unwrapped.isFunctionType())
7858 return false;
7859
7860 Sema &S = TPState.getSema();
7861
7862 // Require FunctionProtoType.
7863 auto *FPT = Unwrapped.get()->getAs<FunctionProtoType>();
7864 if (FPT == nullptr) {
7865 S.Diag(PAttr.getLoc(), diag::err_func_with_effects_no_prototype)
7866 << PAttr.getAttrName()->getName();
7867 return true;
7868 }
7869
7870 // Parse the new attribute.
7871 // non/blocking or non/allocating? Or conditional (computed)?
7872 bool IsNonBlocking = PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7873 PAttr.getKind() == ParsedAttr::AT_Blocking;
7874
7876 Expr *CondExpr = nullptr; // only valid if dependent
7877
7878 if (PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7879 PAttr.getKind() == ParsedAttr::AT_NonAllocating) {
7880 if (!PAttr.checkAtMostNumArgs(S, 1)) {
7881 PAttr.setInvalid();
7882 return true;
7883 }
7884
7885 // Parse the condition, if any.
7886 if (PAttr.getNumArgs() == 1) {
7887 CondExpr = PAttr.getArgAsExpr(0);
7888 std::optional<FunctionEffectMode> MaybeMode =
7889 S.ActOnEffectExpression(CondExpr, PAttr.getAttrName()->getName());
7890 if (!MaybeMode) {
7891 PAttr.setInvalid();
7892 return true;
7893 }
7894 NewMode = *MaybeMode;
7895 if (NewMode != FunctionEffectMode::Dependent)
7896 CondExpr = nullptr;
7897 } else {
7898 NewMode = FunctionEffectMode::True;
7899 }
7900 } else {
7901 // This is the `blocking` or `allocating` attribute.
7902 if (S.CheckAttrNoArgs(PAttr)) {
7903 // The attribute has been marked invalid.
7904 return true;
7905 }
7906 NewMode = FunctionEffectMode::False;
7907 }
7908
7909 const FunctionEffect::Kind FEKind =
7910 (NewMode == FunctionEffectMode::False)
7911 ? (IsNonBlocking ? FunctionEffect::Kind::Blocking
7913 : (IsNonBlocking ? FunctionEffect::Kind::NonBlocking
7915 const FunctionEffectWithCondition NewEC{FunctionEffect(FEKind),
7916 EffectConditionExpr(CondExpr)};
7917
7918 if (S.diagnoseConflictingFunctionEffect(FPT->getFunctionEffects(), NewEC,
7919 PAttr.getLoc())) {
7920 PAttr.setInvalid();
7921 return true;
7922 }
7923
7924 // Add the effect to the FunctionProtoType.
7925 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7928 [[maybe_unused]] bool Success = FX.insert(NewEC, Errs);
7929 assert(Success && "effect conflicts should have been diagnosed above");
7931
7932 QualType NewType = S.Context.getFunctionType(FPT->getReturnType(),
7933 FPT->getParamTypes(), EPI);
7934 QT = Unwrapped.wrap(S, NewType->getAs<FunctionType>());
7935 return true;
7936}
7937
7938static bool checkMutualExclusion(TypeProcessingState &state,
7941 AttributeCommonInfo::Kind OtherKind) {
7942 auto OtherAttr = llvm::find_if(
7943 state.getCurrentAttributes(),
7944 [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
7945 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid())
7946 return false;
7947
7948 Sema &S = state.getSema();
7949 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
7950 << *OtherAttr << Attr
7951 << (OtherAttr->isRegularKeywordAttribute() ||
7953 S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute);
7954 Attr.setInvalid();
7955 return true;
7956}
7957
7960 ParsedAttr &Attr) {
7961 if (!Attr.getNumArgs()) {
7962 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
7963 Attr.setInvalid();
7964 return true;
7965 }
7966
7967 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
7968 StringRef StateName;
7969 SourceLocation LiteralLoc;
7970 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
7971 return true;
7972
7973 if (StateName != "sme_za_state") {
7974 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
7975 Attr.setInvalid();
7976 return true;
7977 }
7978
7979 if (EPI.AArch64SMEAttributes &
7981 S.Diag(Attr.getLoc(), diag::err_conflicting_attributes_arm_agnostic);
7982 Attr.setInvalid();
7983 return true;
7984 }
7985
7987 }
7988
7989 return false;
7990}
7991
7996 if (!Attr.getNumArgs()) {
7997 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
7998 Attr.setInvalid();
7999 return true;
8000 }
8001
8002 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
8003 StringRef StateName;
8004 SourceLocation LiteralLoc;
8005 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
8006 return true;
8007
8008 unsigned Shift;
8009 FunctionType::ArmStateValue ExistingState;
8010 if (StateName == "za") {
8013 } else if (StateName == "zt0") {
8016 } else {
8017 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
8018 Attr.setInvalid();
8019 return true;
8020 }
8021
8023 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_agnostic);
8024 Attr.setInvalid();
8025 return true;
8026 }
8027
8028 // __arm_in(S), __arm_out(S), __arm_inout(S) and __arm_preserves(S)
8029 // are all mutually exclusive for the same S, so check if there are
8030 // conflicting attributes.
8031 if (ExistingState != FunctionType::ARM_None && ExistingState != State) {
8032 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_state)
8033 << StateName;
8034 Attr.setInvalid();
8035 return true;
8036 }
8037
8039 (FunctionType::AArch64SMETypeAttributes)((State << Shift)));
8040 }
8041 return false;
8042}
8043
8044/// Process an individual function attribute. Returns true to
8045/// indicate that the attribute was handled, false if it wasn't.
8046static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
8048 Sema &S = state.getSema();
8049
8050 FunctionTypeUnwrapper unwrapped(S, type);
8051
8052 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
8053 if (S.CheckAttrNoArgs(attr))
8054 return true;
8055
8056 // Delay if this is not a function type.
8057 if (!unwrapped.isFunctionType())
8058 return false;
8059
8060 // Otherwise we can process right away.
8061 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
8062 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8063 return true;
8064 }
8065
8066 if (attr.getKind() == ParsedAttr::AT_CFIUncheckedCallee) {
8067 // Delay if this is not a prototyped function type.
8068 if (!unwrapped.isFunctionType())
8069 return false;
8070
8071 if (!unwrapped.get()->isFunctionProtoType()) {
8072 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
8073 << attr << attr.isRegularKeywordAttribute()
8075 attr.setInvalid();
8076 return true;
8077 }
8078
8079 const auto *FPT = unwrapped.get()->getAs<FunctionProtoType>();
8081 FPT->getReturnType(), FPT->getParamTypes(),
8082 FPT->getExtProtoInfo().withCFIUncheckedCallee(true));
8083 type = unwrapped.wrap(S, cast<FunctionType>(type.getTypePtr()));
8084 return true;
8085 }
8086
8087 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
8088 // Delay if this is not a function type.
8089 if (!unwrapped.isFunctionType())
8090 return false;
8091
8092 // Ignore if we don't have CMSE enabled.
8093 if (!S.getLangOpts().Cmse) {
8094 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
8095 attr.setInvalid();
8096 return true;
8097 }
8098
8099 // Otherwise we can process right away.
8101 unwrapped.get()->getExtInfo().withCmseNSCall(true);
8102 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8103 return true;
8104 }
8105
8106 // ns_returns_retained is not always a type attribute, but if we got
8107 // here, we're treating it as one right now.
8108 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
8109 if (attr.getNumArgs()) return true;
8110
8111 // Delay if this is not a function type.
8112 if (!unwrapped.isFunctionType())
8113 return false;
8114
8115 // Check whether the return type is reasonable.
8117 attr.getLoc(), unwrapped.get()->getReturnType()))
8118 return true;
8119
8120 // Only actually change the underlying type in ARC builds.
8121 QualType origType = type;
8122 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
8124 = unwrapped.get()->getExtInfo().withProducesResult(true);
8125 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8126 }
8127 type = state.getAttributedType(
8129 origType, type);
8130 return true;
8131 }
8132
8133 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
8135 return true;
8136
8137 // Delay if this is not a function type.
8138 if (!unwrapped.isFunctionType())
8139 return false;
8140
8142 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
8143 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8144 return true;
8145 }
8146
8147 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
8148 if (!S.getLangOpts().CFProtectionBranch) {
8149 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
8150 attr.setInvalid();
8151 return true;
8152 }
8153
8155 return true;
8156
8157 // If this is not a function type, warning will be asserted by subject
8158 // check.
8159 if (!unwrapped.isFunctionType())
8160 return true;
8161
8163 unwrapped.get()->getExtInfo().withNoCfCheck(true);
8164 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8165 return true;
8166 }
8167
8168 if (attr.getKind() == ParsedAttr::AT_Regparm) {
8169 unsigned value;
8170 if (S.CheckRegparmAttr(attr, value))
8171 return true;
8172
8173 // Delay if this is not a function type.
8174 if (!unwrapped.isFunctionType())
8175 return false;
8176
8177 // Diagnose regparm with fastcall.
8178 const FunctionType *fn = unwrapped.get();
8179 CallingConv CC = fn->getCallConv();
8180 if (CC == CC_X86FastCall) {
8181 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8182 << FunctionType::getNameForCallConv(CC) << "regparm"
8183 << attr.isRegularKeywordAttribute();
8184 attr.setInvalid();
8185 return true;
8186 }
8187
8189 unwrapped.get()->getExtInfo().withRegParm(value);
8190 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8191 return true;
8192 }
8193
8194 if (attr.getKind() == ParsedAttr::AT_CFISalt) {
8195 if (attr.getNumArgs() != 1)
8196 return true;
8197
8198 StringRef Argument;
8199 if (!S.checkStringLiteralArgumentAttr(attr, 0, Argument))
8200 return true;
8201
8202 // Delay if this is not a function type.
8203 if (!unwrapped.isFunctionType())
8204 return false;
8205
8206 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8207 if (!FnTy) {
8208 S.Diag(attr.getLoc(), diag::err_attribute_wrong_decl_type)
8209 << attr << attr.isRegularKeywordAttribute()
8211 attr.setInvalid();
8212 return true;
8213 }
8214
8215 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8216 EPI.ExtraAttributeInfo.CFISalt = Argument;
8217
8218 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8219 FnTy->getParamTypes(), EPI);
8220 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8221 return true;
8222 }
8223
8224 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8225 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible ||
8226 attr.getKind() == ParsedAttr::AT_ArmPreserves ||
8227 attr.getKind() == ParsedAttr::AT_ArmIn ||
8228 attr.getKind() == ParsedAttr::AT_ArmOut ||
8229 attr.getKind() == ParsedAttr::AT_ArmInOut ||
8230 attr.getKind() == ParsedAttr::AT_ArmAgnostic) {
8231 if (S.CheckAttrTarget(attr))
8232 return true;
8233
8234 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8235 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible)
8236 if (S.CheckAttrNoArgs(attr))
8237 return true;
8238
8239 if (!unwrapped.isFunctionType())
8240 return false;
8241
8242 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8243 if (!FnTy) {
8244 // SME ACLE attributes are not supported on K&R-style unprototyped C
8245 // functions.
8246 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
8247 << attr << attr.isRegularKeywordAttribute()
8249 attr.setInvalid();
8250 return false;
8251 }
8252
8253 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8254 switch (attr.getKind()) {
8255 case ParsedAttr::AT_ArmStreaming:
8256 if (checkMutualExclusion(state, EPI, attr,
8257 ParsedAttr::AT_ArmStreamingCompatible))
8258 return true;
8260 break;
8261 case ParsedAttr::AT_ArmStreamingCompatible:
8262 if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming))
8263 return true;
8265 break;
8266 case ParsedAttr::AT_ArmPreserves:
8268 return true;
8269 break;
8270 case ParsedAttr::AT_ArmIn:
8272 return true;
8273 break;
8274 case ParsedAttr::AT_ArmOut:
8276 return true;
8277 break;
8278 case ParsedAttr::AT_ArmInOut:
8280 return true;
8281 break;
8282 case ParsedAttr::AT_ArmAgnostic:
8283 if (handleArmAgnosticAttribute(S, EPI, attr))
8284 return true;
8285 break;
8286 default:
8287 llvm_unreachable("Unsupported attribute");
8288 }
8289
8290 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8291 FnTy->getParamTypes(), EPI);
8292 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8293 return true;
8294 }
8295
8296 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
8297 // Delay if this is not a function type.
8298 if (!unwrapped.isFunctionType())
8299 return false;
8300
8301 if (S.CheckAttrNoArgs(attr)) {
8302 attr.setInvalid();
8303 return true;
8304 }
8305
8306 // Otherwise we can process right away.
8307 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
8308
8309 // MSVC ignores nothrow if it is in conflict with an explicit exception
8310 // specification.
8311 if (Proto->hasExceptionSpec()) {
8312 switch (Proto->getExceptionSpecType()) {
8313 case EST_None:
8314 llvm_unreachable("This doesn't have an exception spec!");
8315
8316 case EST_DynamicNone:
8317 case EST_BasicNoexcept:
8318 case EST_NoexceptTrue:
8319 case EST_NoThrow:
8320 // Exception spec doesn't conflict with nothrow, so don't warn.
8321 [[fallthrough]];
8322 case EST_Unparsed:
8323 case EST_Uninstantiated:
8325 case EST_Unevaluated:
8326 // We don't have enough information to properly determine if there is a
8327 // conflict, so suppress the warning.
8328 break;
8329 case EST_Dynamic:
8330 case EST_MSAny:
8331 case EST_NoexceptFalse:
8332 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
8333 break;
8334 }
8335 return true;
8336 }
8337
8338 type = unwrapped.wrap(
8339 S, S.Context
8341 QualType{Proto, 0},
8343 ->getAs<FunctionType>());
8344 return true;
8345 }
8346
8347 if (attr.getKind() == ParsedAttr::AT_NonBlocking ||
8348 attr.getKind() == ParsedAttr::AT_NonAllocating ||
8349 attr.getKind() == ParsedAttr::AT_Blocking ||
8350 attr.getKind() == ParsedAttr::AT_Allocating) {
8351 return handleNonBlockingNonAllocatingTypeAttr(state, attr, type, unwrapped);
8352 }
8353
8354 // Delay if the type didn't work out to a function.
8355 if (!unwrapped.isFunctionType()) return false;
8356
8357 // Otherwise, a calling convention.
8358 CallingConv CC;
8359 if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/nullptr, CFT))
8360 return true;
8361
8362 const FunctionType *fn = unwrapped.get();
8363 CallingConv CCOld = fn->getCallConv();
8364 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
8365
8366 if (CCOld != CC) {
8367 // Error out on when there's already an attribute on the type
8368 // and the CCs don't match.
8370 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8373 << attr.isRegularKeywordAttribute();
8374 attr.setInvalid();
8375 return true;
8376 }
8377 }
8378
8379 // Diagnose use of variadic functions with calling conventions that
8380 // don't support them (e.g. because they're callee-cleanup).
8381 // We delay warning about this on unprototyped function declarations
8382 // until after redeclaration checking, just in case we pick up a
8383 // prototype that way. And apparently we also "delay" warning about
8384 // unprototyped function types in general, despite not necessarily having
8385 // much ability to diagnose it later.
8386 if (!supportsVariadicCall(CC)) {
8387 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
8388 if (FnP && FnP->isVariadic()) {
8389 // stdcall and fastcall are ignored with a warning for GCC and MS
8390 // compatibility.
8391 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
8392 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
8395
8396 attr.setInvalid();
8397 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
8399 }
8400 }
8401
8402 // Also diagnose fastcall with regparm.
8403 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
8404 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8406 << attr.isRegularKeywordAttribute();
8407 attr.setInvalid();
8408 return true;
8409 }
8410
8411 // Modify the CC from the wrapped function type, wrap it all back, and then
8412 // wrap the whole thing in an AttributedType as written. The modified type
8413 // might have a different CC if we ignored the attribute.
8415 if (CCOld == CC) {
8416 Equivalent = type;
8417 } else {
8418 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
8419 Equivalent =
8420 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8421 }
8422 type = state.getAttributedType(CCAttr, type, Equivalent);
8423 return true;
8424}
8425
8427 const AttributedType *AT;
8428
8429 // Stop if we'd be stripping off a typedef sugar node to reach the
8430 // AttributedType.
8431 while ((AT = T->getAs<AttributedType>()) &&
8432 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
8433 if (AT->isCallingConv())
8434 return true;
8435 T = AT->getModifiedType();
8436 }
8437 return false;
8438}
8439
8440void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
8441 bool IsCtorOrDtor, SourceLocation Loc) {
8442 FunctionTypeUnwrapper Unwrapped(*this, T);
8443 const FunctionType *FT = Unwrapped.get();
8444 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
8445 cast<FunctionProtoType>(FT)->isVariadic());
8446 CallingConv CurCC = FT->getCallConv();
8447 CallingConv ToCC =
8448 Context.getDefaultCallingConvention(IsVariadic, HasThisPointer);
8449
8450 if (CurCC == ToCC)
8451 return;
8452
8453 // MS compiler ignores explicit calling convention attributes on structors. We
8454 // should do the same.
8455 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
8456 // Issue a warning on ignored calling convention -- except of __stdcall.
8457 // Again, this is what MS compiler does.
8458 if (CurCC != CC_X86StdCall)
8459 Diag(Loc, diag::warn_cconv_unsupported)
8462 // Default adjustment.
8463 } else {
8464 // Only adjust types with the default convention. For example, on Windows
8465 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8466 // __thiscall type to __cdecl for static methods.
8467 CallingConv DefaultCC =
8468 Context.getDefaultCallingConvention(IsVariadic, !HasThisPointer);
8469
8470 if (CurCC != DefaultCC)
8471 return;
8472
8474 return;
8475 }
8476
8477 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
8478 QualType Wrapped = Unwrapped.wrap(*this, FT);
8479 T = Context.getAdjustedType(T, Wrapped);
8480}
8481
8482/// HandleVectorSizeAttribute - this attribute is only applicable to integral
8483/// and float scalars, although arrays, pointers, and function return values are
8484/// allowed in conjunction with this construct. Aggregates with this attribute
8485/// are invalid, even if they are of the same size as a corresponding scalar.
8486/// The raw attribute should contain precisely 1 argument, the vector size for
8487/// the variable, measured in bytes. If curType and rawAttr are well formed,
8488/// this routine will return a new vector type.
8489static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8490 Sema &S) {
8491 // Check the attribute arguments.
8492 if (Attr.getNumArgs() != 1) {
8493 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8494 << 1;
8495 Attr.setInvalid();
8496 return;
8497 }
8498
8499 Expr *SizeExpr = Attr.getArgAsExpr(0);
8500 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
8501 if (!T.isNull())
8502 CurType = T;
8503 else
8504 Attr.setInvalid();
8505}
8506
8507/// Process the OpenCL-like ext_vector_type attribute when it occurs on
8508/// a type.
8510 Sema &S) {
8511 // check the attribute arguments.
8512 if (Attr.getNumArgs() != 1) {
8513 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8514 << 1;
8515 return;
8516 }
8517
8518 Expr *SizeExpr = Attr.getArgAsExpr(0);
8519 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
8520 if (!T.isNull())
8521 CurType = T;
8522}
8523
8524static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) {
8525 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8526 if (!BTy)
8527 return false;
8528
8529 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8530
8531 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8532 // now.
8533 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8534 Triple.getArch() == llvm::Triple::aarch64_32 ||
8535 Triple.getArch() == llvm::Triple::aarch64_be;
8536 if (VecKind == VectorKind::NeonPoly) {
8537 if (IsPolyUnsigned) {
8538 // AArch64 polynomial vectors are unsigned.
8539 return BTy->getKind() == BuiltinType::UChar ||
8540 BTy->getKind() == BuiltinType::UShort ||
8541 BTy->getKind() == BuiltinType::ULong ||
8542 BTy->getKind() == BuiltinType::ULongLong;
8543 } else {
8544 // AArch32 polynomial vectors are signed.
8545 return BTy->getKind() == BuiltinType::SChar ||
8546 BTy->getKind() == BuiltinType::Short ||
8547 BTy->getKind() == BuiltinType::LongLong;
8548 }
8549 }
8550
8551 // Non-polynomial vector types: the usual suspects are allowed, as well as
8552 // float64_t on AArch64.
8553 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8554 BTy->getKind() == BuiltinType::Double)
8555 return true;
8556
8557 return BTy->getKind() == BuiltinType::SChar ||
8558 BTy->getKind() == BuiltinType::UChar ||
8559 BTy->getKind() == BuiltinType::Short ||
8560 BTy->getKind() == BuiltinType::UShort ||
8561 BTy->getKind() == BuiltinType::Int ||
8562 BTy->getKind() == BuiltinType::UInt ||
8563 BTy->getKind() == BuiltinType::Long ||
8564 BTy->getKind() == BuiltinType::ULong ||
8565 BTy->getKind() == BuiltinType::LongLong ||
8566 BTy->getKind() == BuiltinType::ULongLong ||
8567 BTy->getKind() == BuiltinType::Float ||
8568 BTy->getKind() == BuiltinType::Half ||
8569 BTy->getKind() == BuiltinType::BFloat16 ||
8570 BTy->getKind() == BuiltinType::MFloat8;
8571}
8572
8574 llvm::APSInt &Result) {
8575 const auto *AttrExpr = Attr.getArgAsExpr(0);
8576 if (!AttrExpr->isTypeDependent()) {
8577 if (std::optional<llvm::APSInt> Res =
8578 AttrExpr->getIntegerConstantExpr(S.Context)) {
8579 Result = *Res;
8580 return true;
8581 }
8582 }
8583 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8584 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8585 Attr.setInvalid();
8586 return false;
8587}
8588
8589/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8590/// "neon_polyvector_type" attributes are used to create vector types that
8591/// are mangled according to ARM's ABI. Otherwise, these types are identical
8592/// to those created with the "vector_size" attribute. Unlike "vector_size"
8593/// the argument to these Neon attributes is the number of vector elements,
8594/// not the vector size in bytes. The vector width and element type must
8595/// match one of the standard Neon vector types.
8597 Sema &S, VectorKind VecKind) {
8598 bool IsTargetOffloading = S.getLangOpts().isTargetDevice();
8599
8600 // Target must have NEON (or MVE, whose vectors are similar enough
8601 // not to need a separate attribute)
8602 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8603 VecKind == VectorKind::Neon &&
8604 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8605 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8606 << Attr << "'mve'";
8607 Attr.setInvalid();
8608 return;
8609 }
8610 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8611 VecKind == VectorKind::NeonPoly &&
8612 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8613 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8614 << Attr << "'mve'";
8615 Attr.setInvalid();
8616 return;
8617 }
8618
8619 // Check the attribute arguments.
8620 if (Attr.getNumArgs() != 1) {
8621 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8622 << Attr << 1;
8623 Attr.setInvalid();
8624 return;
8625 }
8626 // The number of elements must be an ICE.
8627 llvm::APSInt numEltsInt(32);
8628 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8629 return;
8630
8631 // Only certain element types are supported for Neon vectors.
8632 if (!isPermittedNeonBaseType(CurType, VecKind, S) && !IsTargetOffloading) {
8633 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8634 Attr.setInvalid();
8635 return;
8636 }
8637
8638 // The total size of the vector must be 64 or 128 bits.
8639 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8640 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8641 unsigned vecSize = typeSize * numElts;
8642 if (vecSize != 64 && vecSize != 128) {
8643 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8644 Attr.setInvalid();
8645 return;
8646 }
8647
8648 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8649}
8650
8651/// Handle the __ptrauth qualifier.
8653 const ParsedAttr &Attr, Sema &S) {
8654
8655 assert((Attr.getNumArgs() > 0 && Attr.getNumArgs() <= 3) &&
8656 "__ptrauth qualifier takes between 1 and 3 arguments");
8657 Expr *KeyArg = Attr.getArgAsExpr(0);
8658 Expr *IsAddressDiscriminatedArg =
8659 Attr.getNumArgs() >= 2 ? Attr.getArgAsExpr(1) : nullptr;
8660 Expr *ExtraDiscriminatorArg =
8661 Attr.getNumArgs() >= 3 ? Attr.getArgAsExpr(2) : nullptr;
8662
8663 unsigned Key;
8664 if (S.checkConstantPointerAuthKey(KeyArg, Key)) {
8665 Attr.setInvalid();
8666 return;
8667 }
8668 assert(Key <= PointerAuthQualifier::MaxKey && "ptrauth key is out of range");
8669
8670 bool IsInvalid = false;
8671 unsigned IsAddressDiscriminated, ExtraDiscriminator;
8672 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(IsAddressDiscriminatedArg,
8674 IsAddressDiscriminated);
8675 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(
8676 ExtraDiscriminatorArg, PointerAuthDiscArgKind::Extra, ExtraDiscriminator);
8677
8678 if (IsInvalid) {
8679 Attr.setInvalid();
8680 return;
8681 }
8682
8683 if (!T->isSignableType(Ctx) && !T->isDependentType()) {
8684 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_invalid_target) << T;
8685 Attr.setInvalid();
8686 return;
8687 }
8688
8689 if (T.getPointerAuth()) {
8690 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_redundant) << T;
8691 Attr.setInvalid();
8692 return;
8693 }
8694
8695 if (!S.getLangOpts().PointerAuthIntrinsics) {
8696 S.Diag(Attr.getLoc(), diag::err_ptrauth_disabled) << Attr.getRange();
8697 Attr.setInvalid();
8698 return;
8699 }
8700
8701 assert((!IsAddressDiscriminatedArg || IsAddressDiscriminated <= 1) &&
8702 "address discriminator arg should be either 0 or 1");
8704 Key, IsAddressDiscriminated, ExtraDiscriminator,
8705 PointerAuthenticationMode::SignAndAuth, /*IsIsaPointer=*/false,
8706 /*AuthenticatesNullValues=*/false);
8707 T = S.Context.getPointerAuthType(T, Qual);
8708}
8709
8710/// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8711/// used to create fixed-length versions of sizeless SVE types defined by
8712/// the ACLE, such as svint32_t and svbool_t.
8714 Sema &S) {
8715 // Target must have SVE.
8716 if (!S.Context.getTargetInfo().hasFeature("sve")) {
8717 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8718 Attr.setInvalid();
8719 return;
8720 }
8721
8722 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8723 // if <bits>+ syntax is used.
8724 if (!S.getLangOpts().VScaleMin ||
8725 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8726 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8727 << Attr;
8728 Attr.setInvalid();
8729 return;
8730 }
8731
8732 // Check the attribute arguments.
8733 if (Attr.getNumArgs() != 1) {
8734 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8735 << Attr << 1;
8736 Attr.setInvalid();
8737 return;
8738 }
8739
8740 // The vector size must be an integer constant expression.
8741 llvm::APSInt SveVectorSizeInBits(32);
8742 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8743 return;
8744
8745 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8746
8747 // The attribute vector size must match -msve-vector-bits.
8748 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8749 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8750 << VecSize << S.getLangOpts().VScaleMin * 128;
8751 Attr.setInvalid();
8752 return;
8753 }
8754
8755 // Attribute can only be attached to a single SVE vector or predicate type.
8756 if (!CurType->isSveVLSBuiltinType()) {
8757 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8758 << Attr << CurType;
8759 Attr.setInvalid();
8760 return;
8761 }
8762
8763 const auto *BT = CurType->castAs<BuiltinType>();
8764
8765 QualType EltType = CurType->getSveEltType(S.Context);
8766 unsigned TypeSize = S.Context.getTypeSize(EltType);
8768 if (BT->getKind() == BuiltinType::SveBool) {
8769 // Predicates are represented as i8.
8770 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8772 } else
8773 VecSize /= TypeSize;
8774 CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8775}
8776
8777static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8778 QualType &CurType,
8779 ParsedAttr &Attr) {
8780 const VectorType *VT = dyn_cast<VectorType>(CurType);
8781 if (!VT || VT->getVectorKind() != VectorKind::Neon) {
8782 State.getSema().Diag(Attr.getLoc(),
8783 diag::err_attribute_arm_mve_polymorphism);
8784 Attr.setInvalid();
8785 return;
8786 }
8787
8788 CurType =
8789 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8790 State.getSema().Context, Attr),
8791 CurType, CurType);
8792}
8793
8794/// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8795/// used to create fixed-length versions of sizeless RVV types such as
8796/// vint8m1_t_t.
8798 ParsedAttr &Attr, Sema &S) {
8799 // Target must have vector extension.
8800 if (!S.Context.getTargetInfo().hasFeature("zve32x")) {
8801 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8802 << Attr << "'zve32x'";
8803 Attr.setInvalid();
8804 return;
8805 }
8806
8807 auto VScale = S.Context.getTargetInfo().getVScaleRange(
8809 if (!VScale || !VScale->first || VScale->first != VScale->second) {
8810 S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported)
8811 << Attr;
8812 Attr.setInvalid();
8813 return;
8814 }
8815
8816 // Check the attribute arguments.
8817 if (Attr.getNumArgs() != 1) {
8818 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8819 << Attr << 1;
8820 Attr.setInvalid();
8821 return;
8822 }
8823
8824 // The vector size must be an integer constant expression.
8825 llvm::APSInt RVVVectorSizeInBits(32);
8826 if (!verifyValidIntegerConstantExpr(S, Attr, RVVVectorSizeInBits))
8827 return;
8828
8829 // Attribute can only be attached to a single RVV vector type.
8830 if (!CurType->isRVVVLSBuiltinType()) {
8831 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type)
8832 << Attr << CurType;
8833 Attr.setInvalid();
8834 return;
8835 }
8836
8837 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8838
8841 unsigned MinElts = Info.EC.getKnownMinValue();
8842
8844 unsigned ExpectedSize = VScale->first * MinElts;
8845 QualType EltType = CurType->getRVVEltType(S.Context);
8846 unsigned EltSize = S.Context.getTypeSize(EltType);
8847 unsigned NumElts;
8848 if (Info.ElementType == S.Context.BoolTy) {
8849 NumElts = VecSize / S.Context.getCharWidth();
8850 if (!NumElts) {
8851 NumElts = 1;
8852 switch (VecSize) {
8853 case 1:
8855 break;
8856 case 2:
8858 break;
8859 case 4:
8861 break;
8862 }
8863 } else
8865 } else {
8866 ExpectedSize *= EltSize;
8867 NumElts = VecSize / EltSize;
8868 }
8869
8870 // The attribute vector size must match -mrvv-vector-bits.
8871 if (VecSize != ExpectedSize) {
8872 S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size)
8873 << VecSize << ExpectedSize;
8874 Attr.setInvalid();
8875 return;
8876 }
8877
8878 CurType = S.Context.getVectorType(EltType, NumElts, VecKind);
8879}
8880
8881/// Handle OpenCL Access Qualifier Attribute.
8882static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8883 Sema &S) {
8884 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8885 if (!(CurType->isImageType() || CurType->isPipeType())) {
8886 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8887 Attr.setInvalid();
8888 return;
8889 }
8890
8891 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8892 QualType BaseTy = TypedefTy->desugar();
8893
8894 std::string PrevAccessQual;
8895 if (BaseTy->isPipeType()) {
8896 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8897 OpenCLAccessAttr *Attr =
8898 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8899 PrevAccessQual = Attr->getSpelling();
8900 } else {
8901 PrevAccessQual = "read_only";
8902 }
8903 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8904
8905 switch (ImgType->getKind()) {
8906 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8907 case BuiltinType::Id: \
8908 PrevAccessQual = #Access; \
8909 break;
8910 #include "clang/Basic/OpenCLImageTypes.def"
8911 default:
8912 llvm_unreachable("Unable to find corresponding image type.");
8913 }
8914 } else {
8915 llvm_unreachable("unexpected type");
8916 }
8917 StringRef AttrName = Attr.getAttrName()->getName();
8918 if (PrevAccessQual == AttrName.ltrim("_")) {
8919 // Duplicated qualifiers
8920 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8921 << AttrName << Attr.getRange();
8922 } else {
8923 // Contradicting qualifiers
8924 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8925 }
8926
8927 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8928 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8929 } else if (CurType->isPipeType()) {
8930 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8931 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8932 CurType = S.Context.getWritePipeType(ElemType);
8933 }
8934 }
8935}
8936
8937/// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8938static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8939 Sema &S) {
8940 if (!S.getLangOpts().MatrixTypes) {
8941 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8942 return;
8943 }
8944
8945 if (Attr.getNumArgs() != 2) {
8946 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8947 << Attr << 2;
8948 return;
8949 }
8950
8951 Expr *RowsExpr = Attr.getArgAsExpr(0);
8952 Expr *ColsExpr = Attr.getArgAsExpr(1);
8953 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8954 if (!T.isNull())
8955 CurType = T;
8956}
8957
8958static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8959 QualType &CurType, const ParsedAttr &PA) {
8960 Sema &S = State.getSema();
8961
8962 if (PA.getNumArgs() < 1) {
8963 S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
8964 return;
8965 }
8966
8967 // Make sure that there is a string literal as the annotation's first
8968 // argument.
8969 StringRef Str;
8970 if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
8971 return;
8972
8974 Args.reserve(PA.getNumArgs() - 1);
8975 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
8976 assert(!PA.isArgIdent(Idx));
8977 Args.push_back(PA.getArgAsExpr(Idx));
8978 }
8979 if (!S.ConstantFoldAttrArgs(PA, Args))
8980 return;
8981 auto *AnnotateTypeAttr =
8982 AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
8983 CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
8984}
8985
8986static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8987 QualType &CurType,
8988 ParsedAttr &Attr) {
8989 if (State.getDeclarator().isDeclarationOfFunction()) {
8990 CurType = State.getAttributedType(
8991 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8992 CurType, CurType);
8993 return;
8994 }
8995 State.getSema().Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
8998}
8999
9000static void HandleLifetimeCaptureByAttr(TypeProcessingState &State,
9001 QualType &CurType, ParsedAttr &PA) {
9002 if (State.getDeclarator().isDeclarationOfFunction()) {
9003 auto *Attr = State.getSema().ParseLifetimeCaptureByAttr(PA, "this");
9004 if (Attr)
9005 CurType = State.getAttributedType(Attr, CurType, CurType);
9006 }
9007}
9008
9009static void HandleHLSLParamModifierAttr(TypeProcessingState &State,
9010 QualType &CurType,
9011 const ParsedAttr &Attr, Sema &S) {
9012 // Don't apply this attribute to template dependent types. It is applied on
9013 // substitution during template instantiation. Also skip parsing this if we've
9014 // already modified the type based on an earlier attribute.
9015 if (CurType->isDependentType() || State.didParseHLSLParamMod())
9016 return;
9017 if (Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout ||
9018 Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out) {
9019 State.setParsedHLSLParamMod(true);
9020 }
9021}
9022
9023static void processTypeAttrs(TypeProcessingState &state, QualType &type,
9024 TypeAttrLocation TAL,
9025 const ParsedAttributesView &attrs,
9026 CUDAFunctionTarget CFT) {
9027
9028 state.setParsedNoDeref(false);
9029 if (attrs.empty())
9030 return;
9031
9032 // Scan through and apply attributes to this type where it makes sense. Some
9033 // attributes (such as __address_space__, __vector_size__, etc) apply to the
9034 // type, but others can be present in the type specifiers even though they
9035 // apply to the decl. Here we apply type attributes and ignore the rest.
9036
9037 // This loop modifies the list pretty frequently, but we still need to make
9038 // sure we visit every element once. Copy the attributes list, and iterate
9039 // over that.
9040 ParsedAttributesView AttrsCopy{attrs};
9041 for (ParsedAttr &attr : AttrsCopy) {
9042
9043 // Skip attributes that were marked to be invalid.
9044 if (attr.isInvalid())
9045 continue;
9046
9047 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) {
9048 // [[gnu::...]] attributes are treated as declaration attributes, so may
9049 // not appertain to a DeclaratorChunk. If we handle them as type
9050 // attributes, accept them in that position and diagnose the GCC
9051 // incompatibility.
9052 if (attr.isGNUScope()) {
9053 assert(attr.isStandardAttributeSyntax());
9054 bool IsTypeAttr = attr.isTypeAttr();
9055 if (TAL == TAL_DeclChunk) {
9056 state.getSema().Diag(attr.getLoc(),
9057 IsTypeAttr
9058 ? diag::warn_gcc_ignores_type_attr
9059 : diag::warn_cxx11_gnu_attribute_on_type)
9060 << attr;
9061 if (!IsTypeAttr)
9062 continue;
9063 }
9064 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
9065 !attr.isTypeAttr()) {
9066 // Otherwise, only consider type processing for a C++11 attribute if
9067 // - it has actually been applied to a type (decl-specifier-seq or
9068 // declarator chunk), or
9069 // - it is a type attribute, irrespective of where it was applied (so
9070 // that we can support the legacy behavior of some type attributes
9071 // that can be applied to the declaration name).
9072 continue;
9073 }
9074 }
9075
9076 // If this is an attribute we can handle, do so now,
9077 // otherwise, add it to the FnAttrs list for rechaining.
9078 switch (attr.getKind()) {
9079 default:
9080 // A [[]] attribute on a declarator chunk must appertain to a type.
9081 if ((attr.isStandardAttributeSyntax() ||
9082 attr.isRegularKeywordAttribute()) &&
9083 TAL == TAL_DeclChunk) {
9084 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
9085 << attr << attr.isRegularKeywordAttribute();
9086 attr.setUsedAsTypeAttr();
9087 }
9088 break;
9089
9091 if (attr.isStandardAttributeSyntax()) {
9092 state.getSema().DiagnoseUnknownAttribute(attr);
9093 // Mark the attribute as invalid so we don't emit the same diagnostic
9094 // multiple times.
9095 attr.setInvalid();
9096 }
9097 break;
9098
9100 break;
9101
9102 case ParsedAttr::AT_BTFTypeTag:
9104 attr.setUsedAsTypeAttr();
9105 break;
9106
9107 case ParsedAttr::AT_MayAlias:
9108 // FIXME: This attribute needs to actually be handled, but if we ignore
9109 // it it breaks large amounts of Linux software.
9110 attr.setUsedAsTypeAttr();
9111 break;
9112 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
9113 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
9114 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
9115 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
9116 case ParsedAttr::AT_OpenCLLocalAddressSpace:
9117 case ParsedAttr::AT_OpenCLConstantAddressSpace:
9118 case ParsedAttr::AT_OpenCLGenericAddressSpace:
9119 case ParsedAttr::AT_AddressSpace:
9121 attr.setUsedAsTypeAttr();
9122 break;
9123 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
9125 if (state.getDeclarator().getContext() == DeclaratorContext::Prototype) {
9126 if (state.getSema().getLangOpts().getHLSLVersion() <
9128 state.getSema().Diag(attr.getLoc(), diag::warn_hlsl_groupshared_202x);
9129
9130 // Note: we don't check for the usage of HLSLParamModifiers in/out/inout
9131 // here because the check in the AT_HLSLParamModifier case is sufficient
9132 // regardless of the order of groupshared or in/out/inout specified in
9133 // the parameter. And checking there produces a better error message.
9134 }
9135 attr.setUsedAsTypeAttr();
9136 break;
9137 case ParsedAttr::AT_HLSLRowMajor:
9138 case ParsedAttr::AT_HLSLColumnMajor:
9139 if (Attr *A =
9140 state.getSema().HLSL().buildMatrixLayoutTypeAttr(type, attr))
9141 type = state.getAttributedType(A, type, type);
9142 attr.setUsedAsTypeAttr();
9143 break;
9145 if (!handleObjCPointerTypeAttr(state, attr, type))
9147 attr.setUsedAsTypeAttr();
9148 break;
9149 case ParsedAttr::AT_VectorSize:
9150 HandleVectorSizeAttr(type, attr, state.getSema());
9151 attr.setUsedAsTypeAttr();
9152 break;
9153 case ParsedAttr::AT_ExtVectorType:
9154 HandleExtVectorTypeAttr(type, attr, state.getSema());
9155 attr.setUsedAsTypeAttr();
9156 break;
9157 case ParsedAttr::AT_NeonVectorType:
9159 attr.setUsedAsTypeAttr();
9160 break;
9161 case ParsedAttr::AT_NeonPolyVectorType:
9162 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
9164 attr.setUsedAsTypeAttr();
9165 break;
9166 case ParsedAttr::AT_ArmSveVectorBits:
9167 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
9168 attr.setUsedAsTypeAttr();
9169 break;
9170 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
9172 attr.setUsedAsTypeAttr();
9173 break;
9174 }
9175 case ParsedAttr::AT_RISCVRVVVectorBits:
9176 HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema());
9177 attr.setUsedAsTypeAttr();
9178 break;
9179 case ParsedAttr::AT_OpenCLAccess:
9180 HandleOpenCLAccessAttr(type, attr, state.getSema());
9181 attr.setUsedAsTypeAttr();
9182 break;
9183 case ParsedAttr::AT_PointerAuth:
9184 HandlePtrAuthQualifier(state.getSema().Context, type, attr,
9185 state.getSema());
9186 attr.setUsedAsTypeAttr();
9187 break;
9188 case ParsedAttr::AT_LifetimeBound:
9189 if (TAL == TAL_DeclChunk)
9191 break;
9192 case ParsedAttr::AT_LifetimeCaptureBy:
9193 if (TAL == TAL_DeclChunk)
9195 break;
9196 case ParsedAttr::AT_OverflowBehavior:
9198 attr.setUsedAsTypeAttr();
9199 break;
9200
9201 case ParsedAttr::AT_NoDeref: {
9202 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
9203 // See https://github.com/llvm/llvm-project/issues/55790 for details.
9204 // For the time being, we simply emit a warning that the attribute is
9205 // ignored.
9206 if (attr.isStandardAttributeSyntax()) {
9207 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
9208 << attr;
9209 break;
9210 }
9211 ASTContext &Ctx = state.getSema().Context;
9212 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
9213 type, type);
9214 attr.setUsedAsTypeAttr();
9215 state.setParsedNoDeref(true);
9216 break;
9217 }
9218
9219 case ParsedAttr::AT_MatrixType:
9220 HandleMatrixTypeAttr(type, attr, state.getSema());
9221 attr.setUsedAsTypeAttr();
9222 break;
9223
9224 case ParsedAttr::AT_WebAssemblyFuncref: {
9226 attr.setUsedAsTypeAttr();
9227 break;
9228 }
9229
9230 case ParsedAttr::AT_HLSLParamModifier: {
9231 HandleHLSLParamModifierAttr(state, type, attr, state.getSema());
9232 if (attrs.hasAttribute(ParsedAttr::AT_HLSLGroupSharedAddressSpace)) {
9233 state.getSema().Diag(attr.getLoc(), diag::err_hlsl_attr_incompatible)
9234 << attr << "'groupshared'";
9235 attr.setInvalid();
9236 return;
9237 }
9238 attr.setUsedAsTypeAttr();
9239 break;
9240 }
9241
9242 case ParsedAttr::AT_SwiftAttr: {
9243 HandleSwiftAttr(state, TAL, type, attr);
9244 break;
9245 }
9246
9249 attr.setUsedAsTypeAttr();
9250 break;
9251
9252
9254 // Either add nullability here or try to distribute it. We
9255 // don't want to distribute the nullability specifier past any
9256 // dependent type, because that complicates the user model.
9257 if (type->canHaveNullability() || type->isDependentType() ||
9258 type->isArrayType() ||
9260 unsigned endIndex;
9261 if (TAL == TAL_DeclChunk)
9262 endIndex = state.getCurrentChunkIndex();
9263 else
9264 endIndex = state.getDeclarator().getNumTypeObjects();
9265 bool allowOnArrayType =
9266 state.getDeclarator().isPrototypeContext() &&
9267 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
9269 allowOnArrayType)) {
9270 attr.setInvalid();
9271 }
9272
9273 attr.setUsedAsTypeAttr();
9274 }
9275 break;
9276
9277 case ParsedAttr::AT_ObjCKindOf:
9278 // '__kindof' must be part of the decl-specifiers.
9279 switch (TAL) {
9280 case TAL_DeclSpec:
9281 break;
9282
9283 case TAL_DeclChunk:
9284 case TAL_DeclName:
9285 state.getSema().Diag(attr.getLoc(),
9286 diag::err_objc_kindof_wrong_position)
9287 << FixItHint::CreateRemoval(attr.getLoc())
9289 state.getDeclarator().getDeclSpec().getBeginLoc(),
9290 "__kindof ");
9291 break;
9292 }
9293
9294 // Apply it regardless.
9295 if (checkObjCKindOfType(state, type, attr))
9296 attr.setInvalid();
9297 break;
9298
9299 case ParsedAttr::AT_NoThrow:
9300 // Exception Specifications aren't generally supported in C mode throughout
9301 // clang, so revert to attribute-based handling for C.
9302 if (!state.getSema().getLangOpts().CPlusPlus)
9303 break;
9304 [[fallthrough]];
9306
9307 attr.setUsedAsTypeAttr();
9308
9309 // Attributes with standard syntax have strict rules for what they
9310 // appertain to and hence should not use the "distribution" logic below.
9311 if (attr.isStandardAttributeSyntax() ||
9312 attr.isRegularKeywordAttribute()) {
9313 if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
9314 diagnoseBadTypeAttribute(state.getSema(), attr, type);
9315 attr.setInvalid();
9316 }
9317 break;
9318 }
9319
9320 // Never process function type attributes as part of the
9321 // declaration-specifiers.
9322 if (TAL == TAL_DeclSpec)
9324
9325 // Otherwise, handle the possible delays.
9326 else if (!handleFunctionTypeAttr(state, attr, type, CFT))
9328 break;
9329 case ParsedAttr::AT_AcquireHandle: {
9330 if (!type->isFunctionType())
9331 return;
9332
9333 if (attr.getNumArgs() != 1) {
9334 state.getSema().Diag(attr.getLoc(),
9335 diag::err_attribute_wrong_number_arguments)
9336 << attr << 1;
9337 attr.setInvalid();
9338 return;
9339 }
9340
9341 StringRef HandleType;
9342 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
9343 return;
9344 type = state.getAttributedType(
9345 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
9346 type, type);
9347 attr.setUsedAsTypeAttr();
9348 break;
9349 }
9350 case ParsedAttr::AT_AnnotateType: {
9352 attr.setUsedAsTypeAttr();
9353 break;
9354 }
9355 case ParsedAttr::AT_HLSLResourceClass:
9356 case ParsedAttr::AT_HLSLResourceDimension:
9357 case ParsedAttr::AT_HLSLROV:
9358 case ParsedAttr::AT_HLSLRawBuffer:
9359 case ParsedAttr::AT_HLSLIsArray:
9360 case ParsedAttr::AT_HLSLContainedType: {
9361 // Only collect HLSL resource type attributes that are in
9362 // decl-specifier-seq; do not collect attributes on declarations or those
9363 // that get to slide after declaration name.
9364 if (TAL == TAL_DeclSpec &&
9365 state.getSema().HLSL().handleResourceTypeAttr(type, attr))
9366 attr.setUsedAsTypeAttr();
9367 break;
9368 }
9369 }
9370
9371 // Handle attributes that are defined in a macro. We do not want this to be
9372 // applied to ObjC builtin attributes.
9373 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
9374 !type.getQualifiers().hasObjCLifetime() &&
9375 !type.getQualifiers().hasObjCGCAttr() &&
9376 attr.getKind() != ParsedAttr::AT_ObjCGC &&
9377 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
9378 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
9379 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
9380 state.setExpansionLocForMacroQualifiedType(
9381 cast<MacroQualifiedType>(type.getTypePtr()),
9382 attr.getMacroExpansionLoc());
9383 }
9384 }
9385}
9386
9388 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
9389 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9390 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
9391 auto *Def = Var->getDefinition();
9392 if (!Def) {
9393 SourceLocation PointOfInstantiation = E->getExprLoc();
9394 runWithSufficientStackSpace(PointOfInstantiation, [&] {
9395 InstantiateVariableDefinition(PointOfInstantiation, Var);
9396 });
9397 Def = Var->getDefinition();
9398
9399 // If we don't already have a point of instantiation, and we managed
9400 // to instantiate a definition, this is the point of instantiation.
9401 // Otherwise, we don't request an end-of-TU instantiation, so this is
9402 // not a point of instantiation.
9403 // FIXME: Is this really the right behavior?
9404 if (Var->getPointOfInstantiation().isInvalid() && Def) {
9405 assert(Var->getTemplateSpecializationKind() ==
9407 "explicit instantiation with no point of instantiation");
9408 Var->setTemplateSpecializationKind(
9409 Var->getTemplateSpecializationKind(), PointOfInstantiation);
9410 }
9411 }
9412
9413 // Update the type to the definition's type both here and within the
9414 // expression.
9415 if (Def) {
9416 DRE->setDecl(Def);
9417 QualType T = Def->getType();
9418 DRE->setType(T);
9419 // FIXME: Update the type on all intervening expressions.
9420 E->setType(T);
9421 }
9422
9423 // We still go on to try to complete the type independently, as it
9424 // may also require instantiations or diagnostics if it remains
9425 // incomplete.
9426 }
9427 }
9428 }
9429 if (const auto CastE = dyn_cast<ExplicitCastExpr>(E)) {
9430 QualType DestType = CastE->getTypeAsWritten();
9431 if (const auto *IAT = Context.getAsIncompleteArrayType(DestType)) {
9432 // C++20 [expr.static.cast]p.4: ... If T is array of unknown bound,
9433 // this direct-initialization defines the type of the expression
9434 // as U[1]
9435 QualType ResultType = Context.getConstantArrayType(
9436 IAT->getElementType(),
9437 llvm::APInt(Context.getTypeSize(Context.getSizeType()), 1),
9438 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal,
9439 /*IndexTypeQuals=*/0);
9440 E->setType(ResultType);
9441 }
9442 }
9443}
9444
9446 // Incomplete array types may be completed by the initializer attached to
9447 // their definitions. For static data members of class templates and for
9448 // variable templates, we need to instantiate the definition to get this
9449 // initializer and complete the type.
9450 if (E->getType()->isIncompleteArrayType())
9452
9453 // FIXME: Are there other cases which require instantiating something other
9454 // than the type to complete the type of an expression?
9455
9456 return E->getType();
9457}
9458
9460 TypeDiagnoser &Diagnoser) {
9461 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
9462 Diagnoser);
9463}
9464
9465bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9466 BoundTypeDiagnoser<> Diagnoser(DiagID);
9468}
9469
9471 CompleteTypeKind Kind,
9472 TypeDiagnoser &Diagnoser) {
9473 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
9474 return true;
9475 if (auto *TD = T->getAsTagDecl(); TD && !TD->isCompleteDefinitionRequired()) {
9476 TD->setCompleteDefinitionRequired();
9477 Consumer.HandleTagDeclRequiredDefinition(TD);
9478 }
9479 return false;
9480}
9481
9484 if (!Suggested)
9485 return false;
9486
9487 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9488 // and isolate from other C++ specific checks.
9490 getLangOpts(), D->getASTContext(), Suggested->getASTContext(),
9491 NonEquivalentDecls, StructuralEquivalenceKind::Default,
9492 /*StrictTypeSpelling=*/false, /*Complain=*/true,
9493 /*ErrorOnTagTypeMismatch=*/true);
9494 return Ctx.IsEquivalent(D, Suggested);
9495}
9496
9498 AcceptableKind Kind, bool OnlyNeedComplete) {
9499 // Easy case: if we don't have modules, all declarations are visible.
9500 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9501 return true;
9502
9503 // If this definition was instantiated from a template, map back to the
9504 // pattern from which it was instantiated.
9505 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined())
9506 // We're in the middle of defining it; this definition should be treated
9507 // as visible.
9508 return true;
9509
9510 auto DefinitionIsAcceptable = [&](NamedDecl *D) {
9511 // The (primary) definition might be in a visible module.
9512 if (isAcceptable(D, Kind))
9513 return true;
9514
9515 // A visible module might have a merged definition instead.
9518 if (CodeSynthesisContexts.empty() &&
9519 !getLangOpts().ModulesLocalVisibility) {
9520 // Cache the fact that this definition is implicitly visible because
9521 // there is a visible merged definition.
9523 }
9524 return true;
9525 }
9526
9527 return false;
9528 };
9529 auto IsDefinition = [](NamedDecl *D) {
9530 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
9531 return RD->isThisDeclarationADefinition();
9532 if (auto *ED = dyn_cast<EnumDecl>(D))
9533 return ED->isThisDeclarationADefinition();
9534 if (auto *FD = dyn_cast<FunctionDecl>(D))
9535 return FD->isThisDeclarationADefinition();
9536 if (auto *VD = dyn_cast<VarDecl>(D))
9537 return VD->isThisDeclarationADefinition() == VarDecl::Definition;
9538 llvm_unreachable("unexpected decl type");
9539 };
9540 auto FoundAcceptableDefinition = [&](NamedDecl *D) {
9542 return DefinitionIsAcceptable(D);
9543
9544 // See ASTDeclReader::attachPreviousDeclImpl. Now we still
9545 // may demote definition to declaration for decls in haeder modules,
9546 // so avoid looking at its redeclaration to save time.
9547 // NOTE: If we don't demote definition to declarations for decls
9548 // in header modules, remove the condition.
9550 return DefinitionIsAcceptable(D);
9551
9552 for (auto *RD : D->redecls()) {
9553 auto *ND = cast<NamedDecl>(RD);
9554 if (!IsDefinition(ND))
9555 continue;
9556 if (DefinitionIsAcceptable(ND)) {
9557 *Suggested = ND;
9558 return true;
9559 }
9560 }
9561
9562 return false;
9563 };
9564
9565 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9566 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9567 RD = Pattern;
9568 D = RD->getDefinition();
9569 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
9570 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9571 ED = Pattern;
9572 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9573 // If the enum has a fixed underlying type, it may have been forward
9574 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9575 // the enum and assign it the underlying type of `int`. Since we're only
9576 // looking for a complete type (not a definition), any visible declaration
9577 // of it will do.
9578 *Suggested = nullptr;
9579 for (auto *Redecl : ED->redecls()) {
9580 if (isAcceptable(Redecl, Kind))
9581 return true;
9582 if (Redecl->isThisDeclarationADefinition() ||
9583 (Redecl->isCanonicalDecl() && !*Suggested))
9584 *Suggested = Redecl;
9585 }
9586
9587 return false;
9588 }
9589 D = ED->getDefinition();
9590 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
9591 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9592 FD = Pattern;
9593 D = FD->getDefinition();
9594 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
9595 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9596 VD = Pattern;
9597 D = VD->getDefinition();
9598 }
9599
9600 assert(D && "missing definition for pattern of instantiated definition");
9601
9602 *Suggested = D;
9603
9604 if (FoundAcceptableDefinition(D))
9605 return true;
9606
9607 // The external source may have additional definitions of this entity that are
9608 // visible, so complete the redeclaration chain now and ask again.
9609 if (auto *Source = Context.getExternalSource()) {
9610 Source->CompleteRedeclChain(D);
9611 return FoundAcceptableDefinition(D);
9612 }
9613
9614 return false;
9615}
9616
9617/// Determine whether there is any declaration of \p D that was ever a
9618/// definition (perhaps before module merging) and is currently visible.
9619/// \param D The definition of the entity.
9620/// \param Suggested Filled in with the declaration that should be made visible
9621/// in order to provide a definition of this entity.
9622/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9623/// not defined. This only matters for enums with a fixed underlying
9624/// type, since in all other cases, a type is complete if and only if it
9625/// is defined.
9627 bool OnlyNeedComplete) {
9629 OnlyNeedComplete);
9630}
9631
9632/// Determine whether there is any declaration of \p D that was ever a
9633/// definition (perhaps before module merging) and is currently
9634/// reachable.
9635/// \param D The definition of the entity.
9636/// \param Suggested Filled in with the declaration that should be made
9637/// reachable
9638/// in order to provide a definition of this entity.
9639/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9640/// not defined. This only matters for enums with a fixed underlying
9641/// type, since in all other cases, a type is complete if and only if it
9642/// is defined.
9644 bool OnlyNeedComplete) {
9646 OnlyNeedComplete);
9647}
9648
9649/// Locks in the inheritance model for the given class and all of its bases.
9651 RD = RD->getMostRecentDecl();
9652 if (!RD->hasAttr<MSInheritanceAttr>()) {
9654 bool BestCase = false;
9657 BestCase = true;
9658 IM = RD->calculateInheritanceModel();
9659 break;
9662 break;
9665 break;
9668 break;
9669 }
9670
9673 : RD->getSourceRange();
9674 RD->addAttr(MSInheritanceAttr::CreateImplicit(
9675 S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
9677 }
9678}
9679
9680bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9681 CompleteTypeKind Kind,
9682 TypeDiagnoser *Diagnoser) {
9683 // FIXME: Add this assertion to make sure we always get instantiation points.
9684 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9685 // FIXME: Add this assertion to help us flush out problems with
9686 // checking for dependent types and type-dependent expressions.
9687 //
9688 // assert(!T->isDependentType() &&
9689 // "Can't ask whether a dependent type is complete");
9690
9691 if (const auto *MPTy = dyn_cast<MemberPointerType>(T.getCanonicalType())) {
9692 if (CXXRecordDecl *RD = MPTy->getMostRecentCXXRecordDecl();
9693 RD && !RD->isDependentType()) {
9694 CanQualType T = Context.getCanonicalTagType(RD);
9695 if (getLangOpts().CompleteMemberPointers && !RD->isBeingDefined() &&
9696 RequireCompleteType(Loc, T, Kind, diag::err_memptr_incomplete))
9697 return true;
9698
9699 // We lock in the inheritance model once somebody has asked us to ensure
9700 // that a pointer-to-member type is complete.
9701 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9702 (void)isCompleteType(Loc, T);
9703 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
9704 }
9705 }
9706 }
9707
9708 NamedDecl *Def = nullptr;
9710 bool Incomplete = (T->isIncompleteType(&Def) ||
9711 (!AcceptSizeless && T->isSizelessBuiltinType()));
9712
9713 // Check that any necessary explicit specializations are visible. For an
9714 // enum, we just need the declaration, so don't check this.
9715 if (Def && !isa<EnumDecl>(Def))
9717
9718 // If we have a complete type, we're done.
9719 if (!Incomplete) {
9720 NamedDecl *Suggested = nullptr;
9721 if (Def &&
9722 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
9723 // If the user is going to see an error here, recover by making the
9724 // definition visible.
9725 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9726 if (Diagnoser && Suggested)
9728 /*Recover*/ TreatAsComplete);
9729 return !TreatAsComplete;
9730 } else if (Def && !TemplateInstCallbacks.empty()) {
9731 CodeSynthesisContext TempInst;
9733 TempInst.Template = Def;
9734 TempInst.Entity = Def;
9735 TempInst.PointOfInstantiation = Loc;
9736 atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
9737 atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
9738 }
9739
9740 return false;
9741 }
9742
9743 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
9744 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
9745
9746 // Give the external source a chance to provide a definition of the type.
9747 // This is kept separate from completing the redeclaration chain so that
9748 // external sources such as LLDB can avoid synthesizing a type definition
9749 // unless it's actually needed.
9750 if (Tag || IFace) {
9751 // Avoid diagnosing invalid decls as incomplete.
9752 if (Def->isInvalidDecl())
9753 return true;
9754
9755 // Give the external AST source a chance to complete the type.
9756 if (auto *Source = Context.getExternalSource()) {
9757 if (Tag && Tag->hasExternalLexicalStorage())
9758 Source->CompleteType(Tag);
9759 if (IFace && IFace->hasExternalLexicalStorage())
9760 Source->CompleteType(IFace);
9761 // If the external source completed the type, go through the motions
9762 // again to ensure we're allowed to use the completed type.
9763 if (!T->isIncompleteType())
9764 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9765 }
9766 }
9767
9768 // If we have a class template specialization or a class member of a
9769 // class template specialization, or an array with known size of such,
9770 // try to instantiate it.
9771 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
9772 bool Instantiated = false;
9773 bool Diagnosed = false;
9774 if (RD->isDependentContext()) {
9775 // Don't try to instantiate a dependent class (eg, a member template of
9776 // an instantiated class template specialization).
9777 // FIXME: Can this ever happen?
9778 } else if (auto *ClassTemplateSpec =
9779 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
9780 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9783 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9784 /*Complain=*/Diagnoser, ClassTemplateSpec->hasStrictPackMatch());
9785 });
9786 Instantiated = true;
9787 }
9788 } else {
9789 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9790 if (!RD->isBeingDefined() && Pattern) {
9791 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9792 assert(MSI && "Missing member specialization information?");
9793 // This record was instantiated from a class within a template.
9794 if (MSI->getTemplateSpecializationKind() !=
9797 Diagnosed = InstantiateClass(Loc, RD, Pattern,
9800 /*Complain=*/Diagnoser);
9801 });
9802 Instantiated = true;
9803 }
9804 }
9805 }
9806
9807 if (Instantiated) {
9808 // Instantiate* might have already complained that the template is not
9809 // defined, if we asked it to.
9810 if (Diagnoser && Diagnosed)
9811 return true;
9812 // If we instantiated a definition, check that it's usable, even if
9813 // instantiation produced an error, so that repeated calls to this
9814 // function give consistent answers.
9815 if (!T->isIncompleteType())
9816 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9817 }
9818 }
9819
9820 // FIXME: If we didn't instantiate a definition because of an explicit
9821 // specialization declaration, check that it's visible.
9822
9823 if (!Diagnoser)
9824 return true;
9825
9826 Diagnoser->diagnose(*this, Loc, T);
9827
9828 // If the type was a forward declaration of a class/struct/union
9829 // type, produce a note.
9830 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9831 Diag(Tag->getLocation(), Tag->isBeingDefined()
9832 ? diag::note_type_being_defined
9833 : diag::note_forward_declaration)
9834 << Context.getCanonicalTagType(Tag);
9835
9836 // If the Objective-C class was a forward declaration, produce a note.
9837 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9838 Diag(IFace->getLocation(), diag::note_forward_class);
9839
9840 // If we have external information that we can use to suggest a fix,
9841 // produce a note.
9842 if (ExternalSource)
9843 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9844
9845 return true;
9846}
9847
9849 CompleteTypeKind Kind, unsigned DiagID) {
9850 BoundTypeDiagnoser<> Diagnoser(DiagID);
9851 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9852}
9853
9854/// Get diagnostic %select index for tag kind for
9855/// literal type diagnostic message.
9856/// WARNING: Indexes apply to particular diagnostics only!
9857///
9858/// \returns diagnostic %select index.
9860 switch (Tag) {
9862 return 0;
9864 return 1;
9865 case TagTypeKind::Class:
9866 return 2;
9867 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9868 }
9869}
9870
9872 TypeDiagnoser &Diagnoser) {
9873 assert(!T->isDependentType() && "type should not be dependent");
9874
9875 QualType ElemType = Context.getBaseElementType(T);
9876 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9877 T->isLiteralType(Context))
9878 return false;
9879
9880 Diagnoser.diagnose(*this, Loc, T);
9881
9882 if (T->isVariableArrayType())
9883 return true;
9884
9885 if (!ElemType->isRecordType())
9886 return true;
9887
9888 // A partially-defined class type can't be a literal type, because a literal
9889 // class type must have a trivial destructor (which can't be checked until
9890 // the class definition is complete).
9891 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9892 return true;
9893
9894 const auto *RD = ElemType->castAsCXXRecordDecl();
9895 // [expr.prim.lambda]p3:
9896 // This class type is [not] a literal type.
9897 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9898 Diag(RD->getLocation(), diag::note_non_literal_lambda);
9899 return true;
9900 }
9901
9902 // If the class has virtual base classes, then it's not an aggregate, and
9903 // cannot have any constexpr constructors or a trivial default constructor,
9904 // so is non-literal. This is better to diagnose than the resulting absence
9905 // of constexpr constructors.
9906 if (RD->getNumVBases()) {
9907 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9908 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9909 for (const auto &I : RD->vbases())
9910 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9911 << I.getSourceRange();
9912 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9913 !RD->hasTrivialDefaultConstructor()) {
9914 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9915 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9916 for (const auto &I : RD->bases()) {
9917 if (!I.getType()->isLiteralType(Context)) {
9918 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9919 << RD << I.getType() << I.getSourceRange();
9920 return true;
9921 }
9922 }
9923 for (const auto *I : RD->fields()) {
9924 if (!I->getType()->isLiteralType(Context) ||
9925 I->getType().isVolatileQualified()) {
9926 Diag(I->getLocation(), diag::note_non_literal_field)
9927 << RD << I << I->getType()
9928 << I->getType().isVolatileQualified();
9929 return true;
9930 }
9931 }
9932 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
9933 : !RD->hasTrivialDestructor()) {
9934 // All fields and bases are of literal types, so have trivial or constexpr
9935 // destructors. If this class's destructor is non-trivial / non-constexpr,
9936 // it must be user-declared.
9937 CXXDestructorDecl *Dtor = RD->getDestructor();
9938 assert(Dtor && "class has literal fields and bases but no dtor?");
9939 if (!Dtor)
9940 return true;
9941
9942 if (getLangOpts().CPlusPlus20) {
9943 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
9944 << RD;
9945 } else {
9946 Diag(Dtor->getLocation(), Dtor->isUserProvided()
9947 ? diag::note_non_literal_user_provided_dtor
9948 : diag::note_non_literal_nontrivial_dtor)
9949 << RD;
9950 if (!Dtor->isUserProvided())
9953 /*Diagnose*/ true);
9954 }
9955 }
9956
9957 return true;
9958}
9959
9960bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
9961 BoundTypeDiagnoser<> Diagnoser(DiagID);
9962 return RequireLiteralType(Loc, T, Diagnoser);
9963}
9964
9966 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9967
9968 if (!getLangOpts().CPlusPlus && E->refersToBitField())
9969 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
9970 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
9971
9972 if (!E->isTypeDependent()) {
9973 QualType T = E->getType();
9974 if (const TagType *TT = T->getAs<TagType>())
9975 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
9976 }
9977 return Context.getTypeOfExprType(E, Kind);
9978}
9979
9980static void
9983 // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl.
9984 auto *CountDecl = cast<DeclRefExpr>(E)->getDecl();
9985 Decls.push_back(TypeCoupledDeclRefInfo(CountDecl, /*IsDref*/ false));
9986}
9987
9989 Expr *CountExpr,
9990 bool CountInBytes,
9991 bool OrNull) {
9992 assert(WrappedTy->isIncompleteArrayType() || WrappedTy->isPointerType());
9993
9995 BuildTypeCoupledDecls(CountExpr, Decls);
9996 /// When the resulting expression is invalid, we still create the AST using
9997 /// the original count expression for the sake of AST dump.
9998 return Context.getCountAttributedType(WrappedTy, CountExpr, CountInBytes,
9999 OrNull, Decls);
10000}
10001
10002/// getDecltypeForExpr - Given an expr, will return the decltype for
10003/// that expression, according to the rules in C++11
10004/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
10006
10007 Expr *IDExpr = E;
10008 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
10009 IDExpr = ImplCastExpr->getSubExpr();
10010
10011 if (auto *PackExpr = dyn_cast<PackIndexingExpr>(E)) {
10012 if (E->isInstantiationDependent())
10013 IDExpr = PackExpr->getPackIdExpression();
10014 else
10015 IDExpr = PackExpr->getSelectedExpr();
10016 }
10017
10018 if (E->isTypeDependent())
10019 return Context.DependentTy;
10020
10021 // C++11 [dcl.type.simple]p4:
10022 // The type denoted by decltype(e) is defined as follows:
10023
10024 // C++20:
10025 // - if E is an unparenthesized id-expression naming a non-type
10026 // template-parameter (13.2), decltype(E) is the type of the
10027 // template-parameter after performing any necessary type deduction
10028 // Note that this does not pick up the implicit 'const' for a template
10029 // parameter object. This rule makes no difference before C++20 so we apply
10030 // it unconditionally.
10031 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
10032 IDExpr = SNTTPE->getReplacement();
10033
10034 // - if e is an unparenthesized id-expression or an unparenthesized class
10035 // member access (5.2.5), decltype(e) is the type of the entity named
10036 // by e. If there is no such entity, or if e names a set of overloaded
10037 // functions, the program is ill-formed;
10038 //
10039 // We apply the same rules for Objective-C ivar and property references.
10040 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
10041 const ValueDecl *VD = DRE->getDecl();
10042 QualType T = VD->getType();
10043 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
10044 }
10045 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
10046 if (const auto *VD = ME->getMemberDecl())
10047 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
10048 return VD->getType();
10049 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
10050 return IR->getDecl()->getType();
10051 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
10052 if (PR->isExplicitProperty())
10053 return PR->getExplicitProperty()->getType();
10054 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
10055 return PE->getType();
10056 }
10057
10058 // C++11 [expr.lambda.prim]p18:
10059 // Every occurrence of decltype((x)) where x is a possibly
10060 // parenthesized id-expression that names an entity of automatic
10061 // storage duration is treated as if x were transformed into an
10062 // access to a corresponding data member of the closure type that
10063 // would have been declared if x were an odr-use of the denoted
10064 // entity.
10065 if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
10066 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
10067 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
10068 QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
10069 if (!T.isNull())
10070 return Context.getLValueReferenceType(T);
10071 }
10072 }
10073 }
10074
10075 return Context.getReferenceQualifiedType(E);
10076}
10077
10078QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
10079 assert(!E->hasPlaceholderType() && "unexpected placeholder");
10080
10081 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
10082 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
10083 // The expression operand for decltype is in an unevaluated expression
10084 // context, so side effects could result in unintended consequences.
10085 // Exclude instantiation-dependent expressions, because 'decltype' is often
10086 // used to build SFINAE gadgets.
10087 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
10088 }
10089 return Context.getDecltypeType(E, getDecltypeForExpr(E));
10090}
10091
10093 SourceLocation Loc,
10094 SourceLocation EllipsisLoc) {
10095 if (!IndexExpr)
10096 return QualType();
10097
10098 // Diagnose unexpanded packs but continue to improve recovery.
10099 if (!Pattern->containsUnexpandedParameterPack())
10100 Diag(Loc, diag::err_expected_name_of_pack) << Pattern;
10101
10102 QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc, EllipsisLoc);
10103
10104 if (!Type.isNull())
10105 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::warn_cxx23_pack_indexing
10106 : diag::ext_pack_indexing);
10107 return Type;
10108}
10109
10111 SourceLocation Loc,
10112 SourceLocation EllipsisLoc,
10113 bool FullySubstituted,
10114 ArrayRef<QualType> Expansions) {
10115
10116 UnsignedOrNone Index = std::nullopt;
10117 if (FullySubstituted && !IndexExpr->isValueDependent() &&
10118 !IndexExpr->isTypeDependent()) {
10119 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
10121 IndexExpr, Context.getSizeType(), Value, CCEKind::ArrayBound);
10122 if (!Res.isUsable())
10123 return QualType();
10124 IndexExpr = Res.get();
10125 int64_t V = Value.getExtValue();
10126 if (FullySubstituted && (V < 0 || V >= int64_t(Expansions.size()))) {
10127 Diag(IndexExpr->getBeginLoc(), diag::err_pack_index_out_of_bound)
10128 << V << Pattern << Expansions.size();
10129 return QualType();
10130 }
10131 Index = static_cast<unsigned>(V);
10132 }
10133
10134 return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted,
10135 Expansions, Index);
10136}
10137
10139 SourceLocation Loc) {
10140 assert(BaseType->isEnumeralType());
10141 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
10142
10143 S.DiagnoseUseOfDecl(ED, Loc);
10144
10145 QualType Underlying = ED->getIntegerType();
10146 if (Underlying.isNull()) {
10147 Underlying = ED->getDefinition()->getIntegerType();
10148 assert(!Underlying.isNull());
10149 }
10150
10151 return Underlying;
10152}
10153
10155 SourceLocation Loc) {
10156 if (!BaseType->isEnumeralType()) {
10157 Diag(Loc, diag::err_only_enums_have_underlying_types);
10158 return QualType();
10159 }
10160
10161 // The enum could be incomplete if we're parsing its definition or
10162 // recovering from an error.
10163 NamedDecl *FwdDecl = nullptr;
10164 if (BaseType->isIncompleteType(&FwdDecl)) {
10165 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
10166 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
10167 return QualType();
10168 }
10169
10170 return GetEnumUnderlyingType(*this, BaseType, Loc);
10171}
10172
10174 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
10175 ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
10177 : BaseType;
10178
10179 return Pointer.isNull() ? QualType() : Pointer;
10180}
10181
10183 if (!BaseType->isAnyPointerType())
10184 return BaseType;
10185
10186 return BaseType->getPointeeType();
10187}
10188
10190 QualType Underlying = BaseType.getNonReferenceType();
10191 if (Underlying->isArrayType())
10192 return Context.getDecayedType(Underlying);
10193
10194 if (Underlying->isFunctionType())
10195 return BuiltinAddPointer(BaseType, Loc);
10196
10197 SplitQualType Split = Underlying.getSplitUnqualifiedType();
10198 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
10199 // in the same group of qualifiers as 'const' and 'volatile', we're extending
10200 // '__decay(T)' so that it removes all qualifiers.
10201 Split.Quals.removeCVRQualifiers();
10202 return Context.getQualifiedType(Split);
10203}
10204
10206 SourceLocation Loc) {
10207 assert(LangOpts.CPlusPlus);
10209 BaseType.isReferenceable()
10210 ? BuildReferenceType(BaseType,
10211 UKind == UnaryTransformType::AddLvalueReference,
10212 Loc, DeclarationName())
10213 : BaseType;
10214 return Reference.isNull() ? QualType() : Reference;
10215}
10216
10218 SourceLocation Loc) {
10219 if (UKind == UnaryTransformType::RemoveAllExtents)
10220 return Context.getBaseElementType(BaseType);
10221
10222 if (const auto *AT = Context.getAsArrayType(BaseType))
10223 return AT->getElementType();
10224
10225 return BaseType;
10226}
10227
10229 SourceLocation Loc) {
10230 assert(LangOpts.CPlusPlus);
10231 QualType T = BaseType.getNonReferenceType();
10232 if (UKind == UTTKind::RemoveCVRef &&
10233 (T.isConstQualified() || T.isVolatileQualified())) {
10234 Qualifiers Quals;
10235 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
10236 Quals.removeConst();
10237 Quals.removeVolatile();
10238 T = Context.getQualifiedType(Unqual, Quals);
10239 }
10240 return T;
10241}
10242
10244 SourceLocation Loc) {
10245 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
10246 BaseType->isFunctionType())
10247 return BaseType;
10248
10249 Qualifiers Quals;
10250 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
10251
10252 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
10253 Quals.removeConst();
10254 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
10255 Quals.removeVolatile();
10256 if (UKind == UTTKind::RemoveRestrict)
10257 Quals.removeRestrict();
10258
10259 return Context.getQualifiedType(Unqual, Quals);
10260}
10261
10263 bool IsMakeSigned,
10264 SourceLocation Loc) {
10265 if (BaseType->isEnumeralType()) {
10266 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
10267 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
10268 unsigned int Bits = BitInt->getNumBits();
10269 if (Bits > 1)
10270 return S.Context.getBitIntType(!IsMakeSigned, Bits);
10271
10272 S.Diag(Loc, diag::err_make_signed_integral_only)
10273 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
10274 return QualType();
10275 }
10276 if (Underlying->isBooleanType()) {
10277 S.Diag(Loc, diag::err_make_signed_integral_only)
10278 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
10279 << Underlying;
10280 return QualType();
10281 }
10282 }
10283
10284 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
10285 std::array<CanQualType *, 6> AllSignedIntegers = {
10288 ArrayRef<CanQualType *> AvailableSignedIntegers(
10289 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
10290 std::array<CanQualType *, 6> AllUnsignedIntegers = {
10294 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
10295 AllUnsignedIntegers.size() -
10296 Int128Unsupported);
10297 ArrayRef<CanQualType *> *Consider =
10298 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
10299
10300 uint64_t BaseSize = S.Context.getTypeSize(BaseType);
10301 auto *Result =
10302 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
10303 return BaseSize == S.Context.getTypeSize(T->getTypePtr());
10304 });
10305
10306 assert(Result != Consider->end());
10307 return QualType((*Result)->getTypePtr(), 0);
10308}
10309
10311 SourceLocation Loc) {
10312 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
10313 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
10314 BaseType->isBooleanType() ||
10315 (BaseType->isBitIntType() &&
10316 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
10317 Diag(Loc, diag::err_make_signed_integral_only)
10318 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
10319 return QualType();
10320 }
10321
10322 bool IsNonIntIntegral =
10323 BaseType->isChar16Type() || BaseType->isChar32Type() ||
10324 BaseType->isWideCharType() || BaseType->isEnumeralType();
10325
10326 QualType Underlying =
10327 IsNonIntIntegral
10328 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
10329 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
10330 : Context.getCorrespondingUnsignedType(BaseType);
10331 if (Underlying.isNull())
10332 return Underlying;
10333 return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
10334}
10335
10337 SourceLocation Loc) {
10338 if (BaseType->isDependentType())
10339 return Context.getUnaryTransformType(BaseType, BaseType, UKind);
10341 switch (UKind) {
10342 case UnaryTransformType::EnumUnderlyingType: {
10343 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
10344 break;
10345 }
10346 case UnaryTransformType::AddPointer: {
10347 Result = BuiltinAddPointer(BaseType, Loc);
10348 break;
10349 }
10350 case UnaryTransformType::RemovePointer: {
10351 Result = BuiltinRemovePointer(BaseType, Loc);
10352 break;
10353 }
10354 case UnaryTransformType::Decay: {
10355 Result = BuiltinDecay(BaseType, Loc);
10356 break;
10357 }
10358 case UnaryTransformType::AddLvalueReference:
10359 case UnaryTransformType::AddRvalueReference: {
10360 Result = BuiltinAddReference(BaseType, UKind, Loc);
10361 break;
10362 }
10363 case UnaryTransformType::RemoveAllExtents:
10364 case UnaryTransformType::RemoveExtent: {
10365 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
10366 break;
10367 }
10368 case UnaryTransformType::RemoveCVRef:
10369 case UnaryTransformType::RemoveReference: {
10370 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
10371 break;
10372 }
10373 case UnaryTransformType::RemoveConst:
10374 case UnaryTransformType::RemoveCV:
10375 case UnaryTransformType::RemoveRestrict:
10376 case UnaryTransformType::RemoveVolatile: {
10377 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
10378 break;
10379 }
10380 case UnaryTransformType::MakeSigned:
10381 case UnaryTransformType::MakeUnsigned: {
10382 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
10383 break;
10384 }
10385 }
10386
10387 return !Result.isNull()
10388 ? Context.getUnaryTransformType(BaseType, Result, UKind)
10389 : Result;
10390}
10391
10393 if (!isDependentOrGNUAutoType(T)) {
10394 // FIXME: It isn't entirely clear whether incomplete atomic types
10395 // are allowed or not; for simplicity, ban them for the moment.
10396 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
10397 return QualType();
10398
10399 int DisallowedKind = -1;
10400 if (T->isArrayType())
10401 DisallowedKind = 1;
10402 else if (T->isFunctionType())
10403 DisallowedKind = 2;
10404 else if (T->isReferenceType())
10405 DisallowedKind = 3;
10406 else if (T->isAtomicType())
10407 DisallowedKind = 4;
10408 else if (T.hasQualifiers())
10409 DisallowedKind = 5;
10410 else if (T->isSizelessType())
10411 DisallowedKind = 6;
10412 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus)
10413 // Some other non-trivially-copyable type (probably a C++ class)
10414 DisallowedKind = 7;
10415 else if (T->isBitIntType())
10416 DisallowedKind = 8;
10417 else if (getLangOpts().C23 && T->isUndeducedAutoType())
10418 // _Atomic auto is prohibited in C23
10419 DisallowedKind = 9;
10420
10421 if (DisallowedKind != -1) {
10422 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
10423 return QualType();
10424 }
10425
10426 // FIXME: Do we need any handling for ARC here?
10427 }
10428
10429 // Build the pointer type.
10430 return Context.getAtomicType(T);
10431}
Defines the clang::ASTContext interface.
#define V(N, I)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
static StringRef getTriple(const Command &Job)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
llvm::json::Array Array
Defines the clang::Preprocessor interface.
static QualType getUnderlyingType(const SubRegion *R)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S, VectorKind VecKind)
HandleNeonVectorTypeAttr - The "neon_vector_type" and "neon_polyvector_type" attributes are used to c...
static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType)
static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S)
static void distributeObjCPointerTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType type)
Given that an objc_gc attribute was written somewhere on a declaration other than on the declarator i...
Definition SemaType.cpp:506
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:764
#define MS_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:172
#define CALLING_CONV_ATTRS_CASELIST
Definition SemaType.cpp:125
static void emitNullabilityConsistencyWarning(Sema &S, SimplePointerKind PointerKind, SourceLocation PointerLoc, SourceLocation PointerEndLoc)
static void fixItNullability(Sema &S, DiagBuilderT &Diag, SourceLocation PointerLoc, NullabilityKind Nullability)
Creates a fix-it to insert a C-style nullability keyword at pointerLoc, taking into account whitespac...
static ExprResult checkArraySize(Sema &S, Expr *&ArraySize, llvm::APSInt &SizeVal, unsigned VLADiag, bool VLAIsError)
Check whether the specified array bound can be evaluated using the relevant language rules.
static Attr * createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, NullabilityKind NK)
static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
HandleVectorSizeAttribute - this attribute is only applicable to integral and float scalars,...
static void inferARCWriteback(TypeProcessingState &state, QualType &declSpecType)
Given that this is the declaration of a parameter under ARC, attempt to infer attributes and such for...
static TypeSourceInfo * GetTypeSourceInfoForDeclarator(TypeProcessingState &State, QualType T, TypeSourceInfo *ReturnTypeInfo)
Create and instantiate a TypeSourceInfo with type source information.
static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, const Expr *AddrSpace, SourceLocation AttrLoc)
Build an AddressSpace index from a constant expression and diagnose any errors related to invalid add...
static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr, TypeProcessingState &State)
static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, Qualifiers::ObjCLifetime ownership, unsigned chunkIndex)
static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
handleObjCGCTypeAttr - Process the attribute((objc_gc)) type attribute on the specified type.
static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk)
static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
Process the OpenCL-like ext_vector_type attribute when it occurs on a type.
static void HandleHLSLParamModifierAttr(TypeProcessingState &State, QualType &CurType, const ParsedAttr &Attr, Sema &S)
static void HandleLifetimeBoundAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &Attr)
static bool handleArmStateAttribute(Sema &S, FunctionProtoType::ExtProtoInfo &EPI, ParsedAttr &Attr, FunctionType::ArmStateValue State)
static bool handleArmAgnosticAttribute(Sema &S, FunctionProtoType::ExtProtoInfo &EPI, ParsedAttr &Attr)
static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType, CUDAFunctionTarget CFT)
A function type attribute was written in the decl spec.
Definition SemaType.cpp:674
static bool handleObjCPointerTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
Definition SemaType.cpp:421
static QualType inferARCLifetimeForPointee(Sema &S, QualType type, SourceLocation loc, bool isReference)
Given that we're building a pointer or reference to the given.
static bool handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState, ParsedAttr &PAttr, QualType &QT, FunctionTypeUnwrapper &Unwrapped)
static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType, bool IsMakeSigned, SourceLocation Loc)
static bool CheckNullabilityTypeSpecifier(Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT, NullabilityKind Nullability, SourceLocation NullabilityLoc, bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting)
#define OBJC_POINTER_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:120
static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, QualType type)
diagnoseBadTypeAttribute - Diagnoses a type attribute which doesn't apply to the given type.
Definition SemaType.cpp:80
static PointerDeclaratorKind classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, PointerWrappingDeclaratorKind &wrappingKind)
Classify the given declarator, whose type-specified is type, based on what kind of pointer it refers ...
static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr, llvm::APSInt &Result)
static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL, QualType &QT, ParsedAttr &PAttr)
static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
static bool shouldHaveNullability(QualType T)
static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &Attr)
static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, DeclaratorChunk &DeclType, QualType RT)
Produce an appropriate diagnostic for an ambiguity between a function declarator and a C++ direct-ini...
static void distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType)
Distribute an objc_gc type attribute that was written on the declarator.
Definition SemaType.cpp:562
static FileID getNullabilityCompletenessCheckFileID(Sema &S, SourceLocation loc)
static void HandleOverflowBehaviorAttr(QualType &Type, const ParsedAttr &Attr, TypeProcessingState &State)
static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, Sema &S)
HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is used to create fixed-length v...
#define FUNCTION_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:149
static void HandleLifetimeCaptureByAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &PA)
static bool distributeNullabilityTypeAttr(TypeProcessingState &state, QualType type, ParsedAttr &attr)
Distribute a nullability type attribute that cannot be applied to the type specifier to a pointer,...
static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, QualType &declSpecType, CUDAFunctionTarget CFT)
Given that there are attributes written on the declarator or declaration itself, try to distribute an...
Definition SemaType.cpp:723
static void fillHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL, TypeProcessingState &State)
static bool isDependentOrGNUAutoType(QualType T)
static void distributeFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType type)
A function type attribute was written somewhere in a declaration other than on the declarator itself ...
Definition SemaType.cpp:623
static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type.
static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State, QualType &QT, ParsedAttr &PAttr)
static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex)
Returns true if any of the declarator chunks before endIndex include a level of indirection: array,...
static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
Handle OpenCL Access Qualifier Attribute.
static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind)
Map a nullability attribute kind to a nullability kind.
static bool distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, ParsedAttr &attr, ParsedAttributesView &attrList, QualType &declSpecType, CUDAFunctionTarget CFT)
Try to distribute a function type attribute to the innermost function chunk or type.
Definition SemaType.cpp:654
#define NULLABILITY_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:179
static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, TypeSourceInfo *&ReturnTypeInfo)
static void checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, SourceLocation pointerLoc, SourceLocation pointerEndLoc=SourceLocation())
Complains about missing nullability if the file containing pointerLoc has other uses of nullability (...
static void transferARCOwnership(TypeProcessingState &state, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership)
Used for transferring ownership in casts resulting in l-values.
static std::string getPrintableNameForEntity(DeclarationName Entity)
static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy)
static QualType rebuildAttributedTypeWithoutNullability(ASTContext &Ctx, QualType Type)
Rebuild an attributed type without the nullability attribute on it.
static DeclaratorChunk * maybeMovePastReturnType(Declarator &declarator, unsigned i, bool onlyBlockPointers)
Given the index of a declarator chunk, check whether that chunk directly specifies the return type of...
Definition SemaType.cpp:438
static OpenCLAccessAttr::Spelling getImageAccess(const ParsedAttributesView &Attrs)
Definition SemaType.cpp:878
static void fillMatrixTypeLoc(MatrixTypeLoc MTL, const ParsedAttributesView &Attrs)
static UnaryTransformType::UTTKind TSTToUnaryTransformType(DeclSpec::TST SwitchTST)
Definition SemaType.cpp:886
static void HandleRISCVRVVVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, Sema &S)
HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is used to create fixed-leng...
static void HandleAddressSpaceTypeAttribute(QualType &Type, const ParsedAttr &Attr, TypeProcessingState &State)
HandleAddressSpaceTypeAttribute - Process an address_space attribute on the specified type.
static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, QualifiedFunctionKind QFK)
Check whether the type T is a qualified function type, and if it is, diagnose that it cannot be conta...
static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, QualType Result)
Return true if this is omitted block return type.
Definition SemaType.cpp:848
static void HandlePtrAuthQualifier(ASTContext &Ctx, QualType &T, const ParsedAttr &Attr, Sema &S)
Handle the __ptrauth qualifier.
static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld, LangAS ASNew, SourceLocation AttrLoc)
static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T)
Produce an appropriate diagnostic for a declarator with top-level parentheses.
static QualType ConvertDeclSpecToType(TypeProcessingState &state)
Convert the specified declspec to the appropriate type object.
Definition SemaType.cpp:903
static std::pair< QualType, TypeSourceInfo * > InventTemplateParameter(TypeProcessingState &state, QualType T, TypeSourceInfo *TrailingTSI, AutoType *Auto, InventedTemplateParameterInfo &Info)
static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType, CUDAFunctionTarget CFT)
A function type attribute was written on the declarator or declaration.
Definition SemaType.cpp:694
static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, unsigned &TypeQuals, QualType TypeSoFar, unsigned RemoveTQs, unsigned DiagID)
Definition SemaType.cpp:820
static CallingConv getCCForDeclaratorChunk(Sema &S, Declarator &D, const ParsedAttributesView &AttrList, const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex)
Helper for figuring out the default CC for a function declarator type.
static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for literal type diagnostic message.
static void recordNullabilitySeen(Sema &S, SourceLocation loc)
Marks that a nullability feature has been used in the file containing loc.
static bool CheckBitIntElementType(Sema &S, SourceLocation AttrLoc, const BitIntType *BIT, bool ForMatrixType=false)
static void checkExtParameterInfos(Sema &S, ArrayRef< QualType > paramTypes, const FunctionProtoType::ExtProtoInfo &EPI, llvm::function_ref< SourceLocation(unsigned)> getParamLoc)
Check the extended parameter information.
static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type, CUDAFunctionTarget CFT)
Process an individual function attribute.
static void transferARCOwnershipToDeclSpec(Sema &S, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership)
static void BuildTypeCoupledDecls(Expr *E, llvm::SmallVectorImpl< TypeCoupledDeclRefInfo > &Decls)
static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD)
Locks in the inheritance model for the given class and all of its bases.
static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, ParsedAttr &attr)
Check the application of the Objective-C '__kindof' qualifier to the given type.
static bool hasNullabilityAttr(const ParsedAttributesView &attrs)
Check whether there is a nullability attribute of any kind in the given attribute list.
static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
handleObjCOwnershipTypeAttr - Process an objc_ownership attribute on the specified type.
static void moveAttrFromListToList(ParsedAttr &attr, ParsedAttributesView &fromList, ParsedAttributesView &toList)
Definition SemaType.cpp:387
static void HandleAnnotateTypeAttr(TypeProcessingState &State, QualType &CurType, const ParsedAttr &PA)
static void fillAttributedTypeLoc(AttributedTypeLoc TL, TypeProcessingState &State)
static void fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, const ParsedAttributesView &Attrs)
TypeAttrLocation
The location of a type attribute.
Definition SemaType.cpp:395
@ TAL_DeclChunk
The attribute is part of a DeclaratorChunk.
Definition SemaType.cpp:399
@ TAL_DeclSpec
The attribute is in the decl-specifier-seq.
Definition SemaType.cpp:397
@ TAL_DeclName
The attribute is immediately after the declaration's name.
Definition SemaType.cpp:401
static bool isOmittedBlockReturnType(const Declarator &D)
isOmittedBlockReturnType - Return true if this declarator is missing a return type because this is a ...
Definition SemaType.cpp:63
static TypeSourceInfo * GetFullTypeForDeclarator(TypeProcessingState &state, QualType declSpecType, TypeSourceInfo *TInfo)
TypeDiagSelector
Definition SemaType.cpp:55
@ TDS_ObjCObjOrBlock
Definition SemaType.cpp:58
@ TDS_Function
Definition SemaType.cpp:56
@ TDS_Pointer
Definition SemaType.cpp:57
static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType, SourceLocation Loc)
static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk)
static AttrT * createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL)
static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, Declarator &D, unsigned FunctionChunkIndex)
static void processTypeAttrs(TypeProcessingState &state, QualType &type, TypeAttrLocation TAL, const ParsedAttributesView &attrs, CUDAFunctionTarget CFT=CUDAFunctionTarget::HostDevice)
static bool checkMutualExclusion(TypeProcessingState &state, const FunctionProtoType::ExtProtoInfo &EPI, ParsedAttr &Attr, AttributeCommonInfo::Kind OtherKind)
static Attr * getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr)
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__DEVICE__ int max(int __a, int __b)
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
TranslationUnitDecl * getTranslationUnitDecl() const
CanQualType LongTy
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
CanQualType Int128Ty
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:802
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
CanQualType BoolTy
CanQualType UnsignedLongTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
CanQualType UnsignedLongLongTy
CanQualType UnsignedShortTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
CanQualType ShortTy
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
DiagnosticsEngine & getDiagnostics() const
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:921
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getPointerAuthType(QualType Ty, PointerAuthQualifier PointerAuth)
Return a type with the given __ptrauth qualifier.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
void setLBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1783
void setRBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1791
void setSizeExpr(Expr *Size)
Definition TypeLoc.h:1803
TypeLoc getValueLoc() const
Definition TypeLoc.h:2661
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2673
void setParensRange(SourceRange Range)
Definition TypeLoc.h:2697
Attr - This represents one attribute.
Definition Attr.h:46
attr::Kind getKind() const
Definition Attr.h:92
const char * getSpelling() const
void setImplicit(bool I)
Definition Attr.h:106
Combines information about the source-code form of an attribute, including its syntax and spelling.
bool isContextSensitiveKeywordAttribute() const
SourceLocation getLoc() const
const IdentifierInfo * getAttrName() const
ParsedAttr * create(IdentifierInfo *attrName, SourceRange attrRange, AttributeScopeInfo scope, ArgsUnion *args, unsigned numArgs, ParsedAttr::Form form, SourceLocation ellipsisLoc=SourceLocation())
Definition ParsedAttr.h:735
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
bool hasExplicitTemplateArgs() const
Definition TypeLoc.h:2445
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2411
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2461
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2454
void setConceptReference(ConceptReference *CR)
Definition TypeLoc.h:2405
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2429
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition TypeLoc.h:2472
unsigned getNumArgs() const
Definition TypeLoc.h:2468
TemplateDecl * getNamedConcept() const
Definition TypeLoc.h:2435
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2441
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2399
TypeLoc getWrappedLoc() const
Definition TypeLoc.h:1060
Comparison function object.
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8299
unsigned getNumBits() const
Definition TypeBase.h:8311
void setCaretLoc(SourceLocation Loc)
Definition TypeLoc.h:1532
Pointer to a block type.
Definition TypeBase.h:3606
TypeSpecifierWidth getWrittenWidthSpec() const
Definition TypeLoc.h:641
bool needsExtraLocalData() const
Definition TypeLoc.h:606
void setBuiltinLoc(SourceLocation Loc)
Definition TypeLoc.h:583
WrittenBuiltinSpecs & getWrittenBuiltinSpecs()
Definition TypeLoc.h:599
TypeSpecifierSign getWrittenSignSpec() const
Definition TypeLoc.h:625
void expandBuiltinRange(SourceRange Range)
Definition TypeLoc.h:587
This class is used for builtin types like 'int'.
Definition TypeBase.h:3228
Kind getKind() const
Definition TypeBase.h:3276
Represents a C++ destructor within a class.
Definition DeclCXX.h:2895
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
bool hasUserProvidedDefaultConstructor() const
Whether this class has a user-provided default constructor per C++11.
Definition DeclCXX.h:787
bool hasDefinition() const
Definition DeclCXX.h:561
MSInheritanceModel calculateInheritanceModel() const
Calculate what the inheritance model would be for this class.
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1191
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
Represents a canonical, potentially-qualified type.
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
TypeLoc getNextTypeLoc() const
Definition TypeLoc.h:429
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:251
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:291
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool isRecord() const
Definition DeclBase.h:2202
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2701
bool isFunctionOrMethod() const
Definition DeclBase.h:2174
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
const WrittenBuiltinSpecs & getWrittenBuiltinSpecs() const
Definition DeclSpec.h:896
bool isTypeSpecPipe() const
Definition DeclSpec.h:528
static const TST TST_typeof_unqualType
Definition DeclSpec.h:282
SourceLocation getTypeSpecSignLoc() const
Definition DeclSpec.h:566
bool hasAutoTypeSpec() const
Definition DeclSpec.h:580
static const TST TST_typename
Definition DeclSpec.h:279
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:561
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:698
static const TST TST_char8
Definition DeclSpec.h:255
static const TST TST_BFloat16
Definition DeclSpec.h:262
Expr * getPackIndexingExpr() const
Definition DeclSpec.h:545
TST getTypeSpecType() const
Definition DeclSpec.h:522
SCS getStorageClassSpec() const
Definition DeclSpec.h:486
SourceLocation getOverflowBehaviorLoc() const
Definition DeclSpec.h:624
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:560
bool isTypeSpecSat() const
Definition DeclSpec.h:529
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:559
static const TST TST_auto_type
Definition DeclSpec.h:292
static const TST TST_interface
Definition DeclSpec.h:277
static const TST TST_double
Definition DeclSpec.h:264
static const TST TST_typeofExpr
Definition DeclSpec.h:281
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:602
TemplateIdAnnotation * getRepAsTemplateId() const
Definition DeclSpec.h:551
static const TST TST_union
Definition DeclSpec.h:275
static const TST TST_typename_pack_indexing
Definition DeclSpec.h:286
static const TST TST_char
Definition DeclSpec.h:253
static const TST TST_bool
Definition DeclSpec.h:270
static const TST TST_char16
Definition DeclSpec.h:256
static const TST TST_unknown_anytype
Definition DeclSpec.h:293
TSC getTypeSpecComplex() const
Definition DeclSpec.h:518
static const TST TST_int
Definition DeclSpec.h:258
ParsedType getRepAsType() const
Definition DeclSpec.h:532
static const TST TST_accum
Definition DeclSpec.h:266
static const TST TST_half
Definition DeclSpec.h:261
ParsedAttributes & getAttributes()
Definition DeclSpec.h:880
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:609
bool isTypeAltiVecPixel() const
Definition DeclSpec.h:524
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:631
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:603
static const TST TST_ibm128
Definition DeclSpec.h:269
Expr * getRepAsExpr() const
Definition DeclSpec.h:540
static const TST TST_enum
Definition DeclSpec.h:274
AttributePool & getAttributePool() const
Definition DeclSpec.h:853
bool isWrapSpecified() const
Definition DeclSpec.h:615
static const TST TST_float128
Definition DeclSpec.h:268
static const TST TST_decltype
Definition DeclSpec.h:284
SourceRange getTypeSpecWidthRange() const
Definition DeclSpec.h:564
SourceLocation getTypeSpecTypeNameLoc() const
Definition DeclSpec.h:571
SourceLocation getTypeSpecWidthLoc() const
Definition DeclSpec.h:563
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:604
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:283
static const TST TST_class
Definition DeclSpec.h:278
TypeSpecifierType TST
Definition DeclSpec.h:250
bool isOverflowBehaviorSpecified() const
Definition DeclSpec.h:621
bool hasTagDefinition() const
Definition DeclSpec.cpp:433
static const TST TST_decimal64
Definition DeclSpec.h:272
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition DeclSpec.cpp:442
bool isTypeAltiVecBool() const
Definition DeclSpec.h:525
bool isConstrainedAuto() const
Definition DeclSpec.h:530
static const TST TST_wchar
Definition DeclSpec.h:254
SourceLocation getTypeSpecComplexLoc() const
Definition DeclSpec.h:565
static const TST TST_void
Definition DeclSpec.h:252
bool isTypeAltiVecVector() const
Definition DeclSpec.h:523
static const TST TST_bitint
Definition DeclSpec.h:260
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:532
static const TST TST_float
Definition DeclSpec.h:263
static const TST TST_atomic
Definition DeclSpec.h:294
bool isTrapSpecified() const
Definition DeclSpec.h:618
static const TST TST_fract
Definition DeclSpec.h:267
Decl * getRepAsDecl() const
Definition DeclSpec.h:536
static const TST TST_float16
Definition DeclSpec.h:265
static bool isTransformTypeTrait(TST T)
Definition DeclSpec.h:458
static const TST TST_unspecified
Definition DeclSpec.h:251
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:606
TypeSpecifierSign getTypeSpecSign() const
Definition DeclSpec.h:519
CXXScopeSpec & getTypeSpecScope()
Definition DeclSpec.h:556
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:567
OverflowBehaviorState getOverflowBehaviorState() const
Definition DeclSpec.h:612
static const TST TST_decltype_auto
Definition DeclSpec.h:285
static const TST TST_error
Definition DeclSpec.h:301
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition DeclSpec.cpp:427
static const TST TST_decimal32
Definition DeclSpec.h:271
TypeSpecifierWidth getTypeSpecWidth() const
Definition DeclSpec.h:515
static const TST TST_char32
Definition DeclSpec.h:257
static const TST TST_decimal128
Definition DeclSpec.h:273
bool isTypeSpecOwned() const
Definition DeclSpec.h:526
SourceLocation getTypeSpecSatLoc() const
Definition DeclSpec.h:569
SourceRange getTypeofParensRange() const
Definition DeclSpec.h:577
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:607
static const TST TST_int128
Definition DeclSpec.h:259
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:605
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:828
static const TST TST_typeofType
Definition DeclSpec.h:280
static const TST TST_auto
Definition DeclSpec.h:291
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:839
static const TST TST_struct
Definition DeclSpec.h:276
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
void addAttr(Attr *A)
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:850
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
void setImplicit(bool I=true)
Definition DeclBase.h:602
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1062
bool hasAttr() const
Definition DeclBase.h:585
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:878
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1952
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2508
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2450
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2099
const DeclaratorChunk * getInnermostNonParenChunk() const
Return the innermost (closest to the declarator) chunk of this declarator that is not a parens chunk,...
Definition DeclSpec.h:2476
void AddInnermostTypeInfo(const DeclaratorChunk &TI)
Add a new innermost chunk to this declarator.
Definition DeclSpec.h:2441
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2562
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2793
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2735
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2388
bool hasTrailingReturnType() const
Determine whether a trailing return type was written (at any level) within this declarator.
Definition DeclSpec.h:2660
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2136
bool isExpressionContext() const
Determine whether this declaration appears in a context where an expression could appear.
Definition DeclSpec.h:2604
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2463
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2765
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2446
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2738
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2778
DeclaratorContext getContext() const
Definition DeclSpec.h:2124
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2135
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2118
bool isFirstDeclarator() const
Definition DeclSpec.h:2773
SourceLocation getCommaLoc() const
Definition DeclSpec.h:2774
AttributePool & getAttributePool() const
Definition DeclSpec.h:2108
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2114
bool hasEllipsis() const
Definition DeclSpec.h:2777
ParsedType getTrailingReturnType() const
Get the trailing return type appearing (at any level) within this declarator.
Definition DeclSpec.h:2669
bool isInvalidType() const
Definition DeclSpec.h:2766
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2134
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2801
bool isPrototypeContext() const
Definition DeclSpec.h:2126
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:389
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2106
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2539
void setEllipsisLoc(SourceLocation EL)
Definition DeclSpec.h:2779
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2291
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2288
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:1977
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:1998
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4125
void copy(DependentNameTypeLoc Loc)
Definition TypeLoc.h:2612
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2096
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2068
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:960
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:729
Wrap a function effect's condition expression in another struct so that FunctionProtoType's TrailingO...
Definition TypeBase.h:5091
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation NameLoc)
Definition TypeLoc.h:744
Represents an enum.
Definition Decl.h:4033
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4206
EnumDecl * getDefinition() const
Definition Decl.h:4145
This represents one expression.
Definition Expr.h:112
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isPRValue() const
Definition Expr.h:285
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3697
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isInvalid() const
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
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:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
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:104
A SourceLocation and its associated SourceManager.
unsigned getSpellingLineNumber(bool *Invalid=nullptr) const
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2428
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5307
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:5805
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5339
Represents an abstract function effect, using just an enumeration describing its kind.
Definition TypeBase.h:4984
Kind
Identifies the particular effect.
Definition TypeBase.h:4987
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5171
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
Qualifiers getMethodQuals() const
Definition TypeBase.h:5797
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5775
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition TypeBase.h:5805
unsigned getNumParams() const
Definition TypeLoc.h:1716
void setLocalRangeBegin(SourceLocation L)
Definition TypeLoc.h:1664
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1680
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1723
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1688
void setLocalRangeEnd(SourceLocation L)
Definition TypeLoc.h:1672
void setExceptionSpecRange(SourceRange R)
Definition TypeLoc.h:1702
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4678
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4790
CallingConv getCC() const
Definition TypeBase.h:4737
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4606
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
ExtInfo getExtInfo() const
Definition TypeBase.h:4923
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3704
AArch64SMETypeAttributes
The AArch64 SME ACLE (Arm C/C++ Language Extensions) define a number of function type attributes that...
Definition TypeBase.h:4843
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4876
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4872
CallingConv getCallConv() const
Definition TypeBase.h:4922
QualType getReturnType() const
Definition TypeBase.h:4907
bool getHasRegParm() const
Definition TypeBase.h:4909
Type source information for HLSL attributed resource type.
Definition TypeLoc.h:1113
void setContainedTypeSourceInfo(TypeSourceInfo *TSI) const
Definition TypeLoc.h:1120
void setSourceRange(const SourceRange &R)
Definition TypeLoc.h:1124
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
A simple pair of identifier info and location.
void setIdentifierInfo(IdentifierInfo *Ident)
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ElaboratedTypeKeyword getKeyword() const
Definition TypeBase.h:6048
void setAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1614
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3681
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
bool isImplicitIntAllowed() const
Returns true if implicit int is supported at all.
bool allowArrayReturnTypes() const
bool isTargetDevice() const
True when compiling for an offloading target device.
bool isImplicitIntRequired() const
Returns true if implicit int is part of the language requirements.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Holds a QualType and a TypeSourceInfo* that came out of a declarator parsing.
Definition LocInfoType.h:28
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
Represents the results of name lookup.
Definition Lookup.h:147
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1373
void setExpansionLoc(SourceLocation Loc)
Definition TypeLoc.h:1383
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6250
void setAttrRowOperand(Expr *e)
Definition TypeLoc.h:2131
void setAttrColumnOperand(Expr *e)
Definition TypeLoc.h:2137
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2146
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2125
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4422
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1550
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:1559
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3749
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5642
QualType getPointeeType() const
Definition TypeBase.h:3735
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:866
This represents a decl that may have a name.
Definition Decl.h:274
bool isModulePrivate() const
Whether this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:656
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NamespaceAndPrefix getAsNamespaceAndPrefix() const
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1313
void setNameEndLoc(SourceLocation Loc)
Definition TypeLoc.h:1325
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8009
Wraps an ObjCPointerType with source location information.
Definition TypeLoc.h:1586
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1592
Represents a pointer to an Objective C object.
Definition TypeBase.h:8065
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8102
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(QualType P)
Definition Ownership.h:61
OpenCL supported extensions and optional core features.
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
bool isSupported(llvm::StringRef Ext, const LangOptions &LO) const
TypeLoc getWrappedLoc() const
Definition TypeLoc.h:1084
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2316
A parameter attribute which changes the argument-passing ABI rule for the parameter.
Definition Attr.h:260
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1415
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1411
Represents a parameter to a function.
Definition Decl.h:1808
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void setInvalid(bool b=true) const
Definition ParsedAttr.h:345
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition ParsedAttr.h:371
bool isArgIdent(unsigned Arg) const
Definition ParsedAttr.h:385
Expr * getArgAsExpr(unsigned Arg) const
Definition ParsedAttr.h:383
AttributeCommonInfo::Kind getKind() const
Definition ParsedAttr.h:610
void setUsedAsTypeAttr(bool Used=true)
Definition ParsedAttr.h:360
bool checkAtMostNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at most as many args as Num.
void addAtEnd(ParsedAttr *newAttr)
Definition ParsedAttr.h:827
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:897
void remove(ParsedAttr *ToBeRemoved)
Definition ParsedAttr.h:832
void takeOneFrom(ParsedAttributes &Other, ParsedAttr *PA)
Definition ParsedAttr.h:962
TypeLoc getValueLoc() const
Definition TypeLoc.h:2720
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2725
PipeType - OpenCL20.
Definition TypeBase.h:8265
Pointer-authentication qualifiers.
Definition TypeBase.h:152
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:239
@ MaxKey
The maximum supported pointer-authentication key.
Definition TypeBase.h:229
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1519
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
SourceLocation getPragmaAssumeNonNullLoc() const
The location of the currently-active #pragma clang assume_nonnull begin.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8536
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1468
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1311
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1089
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8468
SplitQualType getSplitUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8548
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8568
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8493
UnqualTypeLoc getUnqualifiedLoc() const
Definition TypeLoc.h:304
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
void removeObjCLifetime()
Definition TypeBase.h:551
void addCVRUQualifiers(unsigned mask)
Definition TypeBase.h:506
bool hasRestrict() const
Definition TypeBase.h:477
void removeRestrict()
Definition TypeBase.h:479
static Qualifiers fromCVRMask(unsigned CVR)
Definition TypeBase.h:435
bool empty() const
Definition TypeBase.h:647
void setUnaligned(bool flag)
Definition TypeBase.h:512
void removeVolatile()
Definition TypeBase.h:469
std::string getAsString() const
@ MaxAddressSpace
The maximum supported address space number.
Definition TypeBase.h:373
void addObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:552
void setAmpAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1628
QualType getPointeeType() const
Definition TypeBase.h:3655
bool isSpelledAsLValue() const
Definition TypeBase.h:3650
bool isFunctionDeclarationScope() const
isFunctionDeclarationScope - Return true if this scope is a function prototype scope.
Definition Scope.h:475
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:208
QualType ProcessResourceTypeAttributes(QualType Wrapped)
QualType getInoutParameterType(QualType Ty)
bool isCFError(RecordDecl *D)
IdentifierInfo * getNSErrorIdent()
Retrieve the identifier "NSError".
bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type)
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1398
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7803
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
QualType BuildParenType(QualType T)
Build a paren type including T.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs (unless they are value dependent ...
Definition SemaAttr.cpp:546
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13688
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1141
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8330
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
UnaryTransformType::UTTKind UTTKind
Definition Sema.h:15517
QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc)
BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression is uninstantiated.
bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind, unsigned &IntVal)
QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc)
SemaOpenMP & OpenMP()
Definition Sema.h:1533
std::optional< FunctionEffectMode > ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName)
Try to parse the conditional expression attached to an effect attribute (e.g.
SemaCUDA & CUDA()
Definition Sema.h:1473
@ AcceptSizeless
Relax the normal rules for complete types so that they include sizeless built-in types.
Definition Sema.h:15202
class clang::Sema::DelayedDiagnostics DelayedDiagnostics
QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc)
Build an ext-vector type.
bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS)
Check whether the given variable declaration has a size that fits within the address space it is decl...
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def)
ASTContext & Context
Definition Sema.h:1308
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
SemaObjC & ObjC()
Definition Sema.h:1518
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TrivialABIHandling::IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
ASTContext & getASTContext() const
Definition Sema.h:939
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD=nullptr, CUDAFunctionTarget CFT=CUDAFunctionTarget::InvalidTarget)
Check validaty of calling convention attribute attr.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull)
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc)
Build a bit-precise integer type.
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1744
QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
bool CheckFunctionReturnType(QualType T, SourceLocation Loc)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14571
const LangOptions & getLangOpts() const
Definition Sema.h:932
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
Preprocessor & PP
Definition Sema.h:1307
QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
const LangOptions & LangOpts
Definition Sema.h:1306
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2673
SemaHLSL & HLSL()
Definition Sema.h:1483
IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, unsigned Index)
Invent a new identifier for parameters of abbreviated templates.
Definition Sema.cpp:140
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition Sema.h:1835
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6578
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition Sema.h:13735
void completeExprArrayBound(Expr *E)
bool hasExplicitCallingConv(QualType T)
bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value)
Checks a regparm attribute, returning true if it is ill-formed and otherwise setting numParams to the...
FileNullabilityMap NullabilityMap
A mapping that describes the nullability we've seen in each header file.
Definition Sema.h:15177
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1341
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2410
QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS, CXXRecordDecl *Cls, SourceLocation Loc, DeclarationName Entity)
Build a member pointer type T Class::*.
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:644
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1446
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:1528
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
IdentifierInfo * getNullabilityKeyword(NullabilityKind nullability)
Retrieve the keyword associated.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8263
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
bool isAcceptable(const NamedDecl *D, AcceptableKind Kind)
Determine whether a declaration is acceptable (visible/reachable).
Definition Sema.h:15629
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14054
SourceManager & getSourceManager() const
Definition Sema.h:937
QualType BuiltinAddReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
bool hasVisibleMergedDefinition(const NamedDecl *Def)
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
@ NTCUK_Destruct
Definition Sema.h:4139
@ NTCUK_Copy
Definition Sema.h:4140
QualType BuildAtomicType(QualType T, SourceLocation Loc)
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX, const FunctionEffectWithCondition &EC, SourceLocation NewAttrLoc)
Warn and return true if adding a function effect to a set would create a conflict.
TypeSourceInfo * ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
TypeResult ActOnTypeName(Declarator &D)
bool isSFINAEContext() const
Definition Sema.h:13787
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15571
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration,...
QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a pointer type.
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc)
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1584
ASTConsumer & Consumer
Definition Sema.h:1309
bool CheckImplicitNullabilityTypeSpecifier(QualType &Type, NullabilityKind Nullability, SourceLocation DiagLoc, bool AllowArrayTypes, bool OverrideExisting)
Check whether a nullability type specifier can be added to the given type through some means not writ...
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
bool CheckDistantExceptionSpec(QualType T)
CheckDistantExceptionSpec - Check if the given type is a pointer or pointer to member to a function w...
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind, SourceLocation Loc)
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind, SourceLocation Loc)
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind, SourceLocation Loc)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:1311
DiagnosticsEngine & Diags
Definition Sema.h:1310
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:933
QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc)
QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity)
Build an array type.
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc)
QualType BuildReadPipeType(QualType T, SourceLocation Loc)
Build a Read-only Pipe type.
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition Sema.h:1830
llvm::BumpPtrAllocator BumpAlloc
Definition Sema.h:1253
QualType BuildWritePipeType(QualType T, SourceLocation Loc)
Build a Write-only Pipe type.
QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc)
QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:631
QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc)
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2219
bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, AcceptableKind Kind, bool OnlyNeedComplete=false)
QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind, SourceLocation Loc)
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a block pointer type.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Information about a FileID, basically just the logical file that it represents and include stack info...
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
SourceLocation getIncludeLoc() const
This is a discriminated union of FileInfo and ExpansionInfo.
const FileInfo & getFile() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3739
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:3870
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3840
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4889
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:816
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:824
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
Exposes information about the current target.
Definition TargetInfo.h:227
virtual bool hasBitIntType() const
Determine whether the _BitInt type is supported on this target.
Definition TargetInfo.h:690
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual size_t getMaxBitIntWidth() const
Definition TargetInfo.h:696
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts, ArmStreamingKind Mode, llvm::StringMap< bool > *FeatureMap=nullptr) const
Returns target-specific min and max values VScale_Range.
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition TargetInfo.h:490
virtual bool allowHalfArgsAndReturns() const
Whether half args and returns are supported.
Definition TargetInfo.h:715
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:679
virtual bool hasFloat16Type() const
Determine whether the _Float16 type is supported on this target.
Definition TargetInfo.h:721
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:733
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:718
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition TargetInfo.h:724
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:1922
void copy(TemplateSpecializationTypeLoc Loc)
Definition TypeLoc.h:1925
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition TypeBase.h:3420
const Type * getTypeForDecl() const
Definition Decl.h:3560
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition TypeLoc.h:349
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:171
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:217
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition TypeLoc.h:165
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:884
void * getOpaqueData() const
Get the pointer where source information is stored.
Definition TypeLoc.h:143
void copy(TypeLoc other)
Copies the other type loc into this one.
Definition TypeLoc.cpp:169
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition TypeLoc.h:211
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
void setUnmodifiedTInfo(TypeSourceInfo *TI) const
Definition TypeLoc.h:2265
A container of type source information.
Definition TypeBase.h:8418
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8429
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2545
bool isBlockPointerType() const
Definition TypeBase.h:8704
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2771
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2173
bool isUndeducedAutoType() const
Definition TypeBase.h:8880
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:8783
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isPointerType() const
Definition TypeBase.h:8684
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
NestedNameSpecifier getPrefix() const
If this type represents a qualified-id, this returns its nested name specifier.
Definition Type.cpp:1977
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2701
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition Type.cpp:508
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool canHaveNullability(bool ResultIfUnknown=true) const
Determine whether the given type can have a nullability specifier applied to it, i....
Definition Type.cpp:5165
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2740
bool isImageType() const
Definition TypeBase.h:8948
bool isPipeType() const
Definition TypeBase.h:8955
bool isBitIntType() const
Definition TypeBase.h:8959
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8807
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool isChar16Type() const
Definition Type.cpp:2215
bool isHalfType() const
Definition TypeBase.h:9054
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2465
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2651
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isAtomicType() const
Definition TypeBase.h:8876
bool isObjCObjectType() const
Definition TypeBase.h:8867
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9193
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2527
bool isFunctionType() const
Definition TypeBase.h:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2753
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
bool isAnyPointerType() const
Definition TypeBase.h:8692
TypeClass getTypeClass() const
Definition TypeBase.h:2445
bool isSamplerT() const
Definition TypeBase.h:8928
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition Type.cpp:5400
bool isRecordType() const
Definition TypeBase.h:8811
bool isObjCRetainableType() const
Definition Type.cpp:5431
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5152
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3689
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3584
void setParensRange(SourceRange range)
Definition TypeLoc.h:2224
void setTypeofLoc(SourceLocation Loc)
Definition TypeLoc.h:2200
void setParensRange(SourceRange Range)
Definition TypeLoc.h:2368
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2344
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition TypeLoc.h:2356
Wrapper of type source information for a type with no direct qualifiers.
Definition TypeLoc.h:274
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:283
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1075
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1248
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1121
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3417
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1314
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2045
Represents a GCC generic vector type.
Definition TypeBase.h:4239
VectorKind getVectorKind() const
Definition TypeBase.h:4259
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
Defines the clang::TargetInfo interface.
const internal::VariadicDynCastAllOfMatcher< Decl, TypedefDecl > typedefDecl
Matches typedef declarations.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Decl, RecordDecl > recordDecl
Matches class, struct, and union declarations.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_auto_type
Definition Specifiers.h:95
@ TST_auto
Definition Specifiers.h:93
@ TST_unspecified
Definition Specifiers.h:57
@ TST_typename
Definition Specifiers.h:85
@ TST_decltype_auto
Definition Specifiers.h:94
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:213
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus26
@ CPlusPlus17
@ ExpectedParameterOrImplicitObjectParameter
@ ExpectedFunctionWithProtoType
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
@ GNUAutoType
__auto_type (GNU extension)
Definition TypeBase.h:1842
@ DecltypeAuto
decltype(auto)
Definition TypeBase.h:1839
llvm::StringRef getParameterABISpelling(ParameterABI kind)
FunctionEffectMode
Used with attributes/effects with a boolean condition, e.g. nonblocking.
Definition Sema.h:459
LLVM_READONLY bool isAsciiIdentifierContinue(unsigned char c)
Definition CharInfo.h:61
CUDAFunctionTarget
Definition Cuda.h:63
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:349
@ Nullable
Values of this type can be null.
Definition Specifiers.h:353
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:358
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1797
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1800
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1803
llvm::PointerUnion< Expr *, IdentifierLoc * > ArgsUnion
A union of the various pointer types that can be passed to an ParsedAttr as an argument.
Definition ParsedAttr.h:103
@ Success
Annotation was successful.
Definition Parser.h:65
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:1035
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1033
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1031
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1027
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1025
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1023
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1017
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1029
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1019
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1021
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:918
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
@ AANT_ArgumentIntegerConstant
@ AANT_ArgumentString
DeclaratorContext
Definition DeclSpec.h:1902
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
llvm::StringRef getNullabilitySpelling(NullabilityKind kind, bool isContextSensitive=false)
Retrieve the spelling of the given nullability kind.
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3783
@ SwiftAsyncContext
This parameter (which must have pointer type) uses the special Swift asynchronous context-pointer ABI...
Definition Specifiers.h:402
@ SwiftErrorResult
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
Definition Specifiers.h:392
@ Ordinary
This parameter uses ordinary ABI rules for its type.
Definition Specifiers.h:383
@ SwiftIndirectResult
This parameter (which must have pointer type) is a Swift indirect result parameter.
Definition Specifiers.h:387
@ SwiftContext
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment.
Definition Specifiers.h:397
OptionalUnsigned< unsigned > UnsignedOrNone
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:320
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
static bool isBlockPointer(Expr *Arg)
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5995
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6000
@ Struct
The "struct" keyword.
Definition TypeBase.h:5997
@ Class
The "class" keyword.
Definition TypeBase.h:6006
@ Union
The "union" keyword.
Definition TypeBase.h:6003
@ Enum
The "enum" keyword.
Definition TypeBase.h:6009
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition CharInfo.h:108
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
@ Type
The name was classified as a type.
Definition Sema.h:564
LangAS
Defines the address space values used by the address space qualifier of QualType.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
@ Deduced
The normal deduced case.
Definition TypeBase.h:1814
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1809
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition Specifiers.h:413
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:647
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_Swift
Definition Specifiers.h:294
@ CC_DeviceKernel
Definition Specifiers.h:293
@ CC_SwiftAsync
Definition Specifiers.h:295
@ CC_X86StdCall
Definition Specifiers.h:281
@ CC_X86FastCall
Definition Specifiers.h:282
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4209
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4218
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4203
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4206
@ Neon
is ARM Neon vector
Definition TypeBase.h:4212
@ Generic
not a target-specific vector type
Definition TypeBase.h:4200
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4224
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4227
@ NeonPoly
is ARM Neon polynomial vector
Definition TypeBase.h:4215
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4221
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5970
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2249
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
@ Implicit
An implicit conversion.
Definition Sema.h:440
OptionalUnsigned< NullabilityKind > NullabilityKindOrNone
Definition Specifiers.h:365
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
unsigned isStar
True if this dimension was [*]. In this case, NumElts is null.
Definition DeclSpec.h:1360
unsigned TypeQuals
The type qualifiers for the array: const/volatile/restrict/__unaligned/_Atomic.
Definition DeclSpec.h:1352
unsigned hasStatic
True if this dimension included the 'static' keyword.
Definition DeclSpec.h:1356
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition DeclSpec.h:1365
unsigned TypeQuals
For now, sema will catch these as invalid.
Definition DeclSpec.h:1649
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition DeclSpec.h:1412
SourceLocation getTrailingReturnTypeLoc() const
Get the trailing-return-type location for this function declarator.
Definition DeclSpec.h:1639
SourceLocation getLParenLoc() const
Definition DeclSpec.h:1554
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition DeclSpec.h:1630
TypeAndRange * Exceptions
Pointer to a new[]'d array of TypeAndRange objects that contain the types in the function's dynamic e...
Definition DeclSpec.h:1484
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1472
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition DeclSpec.h:1633
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1421
SourceLocation getExceptionSpecLocBeg() const
Definition DeclSpec.h:1560
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1475
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1573
SourceLocation getRParenLoc() const
Definition DeclSpec.h:1558
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:1556
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1447
unsigned getNumExceptions() const
Get the number of dynamic exception specifications.
Definition DeclSpec.h:1616
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1605
unsigned isAmbiguous
Can this declaration be a constructor-style initializer?
Definition DeclSpec.h:1416
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1406
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1598
SourceRange getExceptionSpecRange() const
Definition DeclSpec.h:1568
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition DeclSpec.h:1611
Expr * NoexceptExpr
Pointer to the expression in the noexcept-specifier of this function, if it has one.
Definition DeclSpec.h:1488
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
Definition DeclSpec.h:1658
SourceLocation StarLoc
Location of the '*' token.
Definition DeclSpec.h:1660
const IdentifierInfo * Ident
Definition DeclSpec.h:1378
SourceLocation OverflowBehaviorLoc
The location of an __ob_wrap or __ob_trap qualifier, if any.
Definition DeclSpec.h:1328
SourceLocation RestrictQualLoc
The location of the restrict-qualifier, if any.
Definition DeclSpec.h:1319
SourceLocation ConstQualLoc
The location of the const-qualifier, if any.
Definition DeclSpec.h:1313
SourceLocation VolatileQualLoc
The location of the volatile-qualifier, if any.
Definition DeclSpec.h:1316
SourceLocation UnalignedQualLoc
The location of the __unaligned-qualifier, if any.
Definition DeclSpec.h:1325
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/unaligned/atomic.
Definition DeclSpec.h:1310
SourceLocation AtomicQualLoc
The location of the _Atomic-qualifier, if any.
Definition DeclSpec.h:1322
unsigned OverflowBehaviorIsWrap
Whether the overflow behavior qualifier is wrap (true) or trap (false).
Definition DeclSpec.h:1333
bool LValueRef
True if this is an lvalue reference, false if it's an rvalue reference.
Definition DeclSpec.h:1343
bool HasRestrict
The type qualifier: restrict. [GNU] C++ extension.
Definition DeclSpec.h:1341
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1287
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1707
SourceLocation EndLoc
EndLoc - If valid, the place where this chunck ends.
Definition DeclSpec.h:1297
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition DeclSpec.cpp:132
ReferenceTypeInfo Ref
Definition DeclSpec.h:1684
BlockPointerTypeInfo Cls
Definition DeclSpec.h:1687
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1688
ArrayTypeInfo Arr
Definition DeclSpec.h:1685
SourceLocation Loc
Loc - The place where this type was defined.
Definition DeclSpec.h:1295
FunctionTypeInfo Fun
Definition DeclSpec.h:1686
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
PointerTypeInfo Ptr
Definition DeclSpec.h:1683
Describes whether we've seen any nullability information for the given file.
Definition Sema.h:242
SourceLocation PointerEndLoc
The end location for the first pointer declarator in the file.
Definition Sema.h:249
SourceLocation PointerLoc
The first pointer declarator (of any pointer kind) in the file that does not have a corresponding nul...
Definition Sema.h:245
bool SawTypeNullability
Whether we saw any type nullability annotations in the given file.
Definition Sema.h:255
uint8_t PointerKind
Which kind of pointer declarator we saw.
Definition Sema.h:252
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition TypeBase.h:5108
Holds information about the various types of exception specification.
Definition TypeBase.h:5428
Extra information about a function prototype.
Definition TypeBase.h:5456
FunctionTypeExtraAttributeInfo ExtraAttributeInfo
Definition TypeBase.h:5464
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5461
void setArmSMEAttribute(AArch64SMETypeAttributes Kind, bool Enable=true)
Definition TypeBase.h:5510
StringRef CFISalt
A CFI "salt" that differentiates functions with the same prototype.
Definition TypeBase.h:4833
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition DeclSpec.h:2948
unsigned AutoTemplateParameterDepth
If this is a generic lambda or abbreviated function template, use this as the depth of each 'auto' pa...
Definition DeclSpec.h:2939
static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
Definition Type.cpp:3348
Describes how types, statements, expressions, and declarations should be printed.
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13199
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13300
Abstract class used to diagnose incomplete types.
Definition Sema.h:8344
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
SplitQualType getSingleStepDesugaredType() const
Definition TypeBase.h:8440
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.