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