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