clang 24.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"
44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/STLForwardCompat.h"
46#include "llvm/ADT/StringExtras.h"
47#include "llvm/IR/DerivedTypes.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/TargetParser/RISCVTargetParser.h"
50#include <bitset>
51#include <optional>
52
53using namespace clang;
54
60
61/// isOmittedBlockReturnType - Return true if this declarator is missing a
62/// return type because this is a omitted return type on a block literal.
63static bool isOmittedBlockReturnType(const Declarator &D) {
66 return false;
67
68 if (D.getNumTypeObjects() == 0)
69 return true; // ^{ ... }
70
71 if (D.getNumTypeObjects() == 1 &&
73 return true; // ^(int X, float Y) { ... }
74
75 return false;
76}
77
78/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
79/// doesn't apply to the given type.
81 QualType type) {
82 TypeDiagSelector WhichType;
83 bool useExpansionLoc = true;
84 switch (attr.getKind()) {
85 case ParsedAttr::AT_ObjCGC:
86 WhichType = TDS_Pointer;
87 break;
88 case ParsedAttr::AT_ObjCOwnership:
89 WhichType = TDS_ObjCObjOrBlock;
90 break;
91 default:
92 // Assume everything else was a function attribute.
93 WhichType = TDS_Function;
94 useExpansionLoc = false;
95 break;
96 }
97
98 SourceLocation loc = attr.getLoc();
99 StringRef name = attr.getAttrName()->getName();
100
101 // The GC attributes are usually written with macros; special-case them.
102 IdentifierInfo *II =
103 attr.isArgIdent(0) ? attr.getArgAsIdent(0)->getIdentifierInfo() : nullptr;
104 if (useExpansionLoc && loc.isMacroID() && II) {
105 if (II->isStr("strong")) {
106 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
107 } else if (II->isStr("weak")) {
108 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
109 }
110 }
111
112 S.Diag(loc, attr.isRegularKeywordAttribute()
113 ? diag::err_type_attribute_wrong_type
114 : diag::warn_type_attribute_wrong_type)
115 << name << WhichType << type;
116}
117
118// objc_gc applies to Objective-C pointers or, otherwise, to the
119// smallest available pointer type (i.e. 'void*' in 'void**').
120#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
121 case ParsedAttr::AT_ObjCGC: \
122 case ParsedAttr::AT_ObjCOwnership
123
124// Calling convention attributes.
125#define CALLING_CONV_ATTRS_CASELIST \
126 case ParsedAttr::AT_CDecl: \
127 case ParsedAttr::AT_FastCall: \
128 case ParsedAttr::AT_StdCall: \
129 case ParsedAttr::AT_ThisCall: \
130 case ParsedAttr::AT_RegCall: \
131 case ParsedAttr::AT_Pascal: \
132 case ParsedAttr::AT_SwiftCall: \
133 case ParsedAttr::AT_SwiftAsyncCall: \
134 case ParsedAttr::AT_VectorCall: \
135 case ParsedAttr::AT_AArch64VectorPcs: \
136 case ParsedAttr::AT_AArch64SVEPcs: \
137 case ParsedAttr::AT_MSABI: \
138 case ParsedAttr::AT_SysVABI: \
139 case ParsedAttr::AT_Pcs: \
140 case ParsedAttr::AT_IntelOclBicc: \
141 case ParsedAttr::AT_PreserveMost: \
142 case ParsedAttr::AT_PreserveAll: \
143 case ParsedAttr::AT_M68kRTD: \
144 case ParsedAttr::AT_PreserveNone: \
145 case ParsedAttr::AT_RISCVVectorCC: \
146 case ParsedAttr::AT_RISCVVLSCC
147
148// Function type attributes.
149#define FUNCTION_TYPE_ATTRS_CASELIST \
150 case ParsedAttr::AT_NSReturnsRetained: \
151 case ParsedAttr::AT_NoReturn: \
152 case ParsedAttr::AT_NonBlocking: \
153 case ParsedAttr::AT_NonAllocating: \
154 case ParsedAttr::AT_Blocking: \
155 case ParsedAttr::AT_Allocating: \
156 case ParsedAttr::AT_Regparm: \
157 case ParsedAttr::AT_CFIUncheckedCallee: \
158 case ParsedAttr::AT_CFISalt: \
159 case ParsedAttr::AT_CmseNSCall: \
160 case ParsedAttr::AT_ArmStreaming: \
161 case ParsedAttr::AT_ArmStreamingCompatible: \
162 case ParsedAttr::AT_ArmPreserves: \
163 case ParsedAttr::AT_ArmIn: \
164 case ParsedAttr::AT_ArmOut: \
165 case ParsedAttr::AT_ArmInOut: \
166 case ParsedAttr::AT_ArmAgnostic: \
167 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
168 case ParsedAttr::AT_AnyX86NoCfCheck: \
169 CALLING_CONV_ATTRS_CASELIST
170
171// Microsoft-specific type qualifiers.
172#define MS_TYPE_ATTRS_CASELIST \
173 case ParsedAttr::AT_Ptr32: \
174 case ParsedAttr::AT_Ptr64: \
175 case ParsedAttr::AT_SPtr: \
176 case ParsedAttr::AT_UPtr
177
178// Nullability qualifiers.
179#define NULLABILITY_TYPE_ATTRS_CASELIST \
180 case ParsedAttr::AT_TypeNonNull: \
181 case ParsedAttr::AT_TypeNullable: \
182 case ParsedAttr::AT_TypeNullableResult: \
183 case ParsedAttr::AT_TypeNullUnspecified
184
185namespace {
186 /// An object which stores processing state for the entire
187 /// GetTypeForDeclarator process.
188 class TypeProcessingState {
189 Sema &sema;
190
191 /// The declarator being processed.
192 Declarator &declarator;
193
194 /// The index of the declarator chunk we're currently processing.
195 /// May be the total number of valid chunks, indicating the
196 /// DeclSpec.
197 unsigned chunkIndex;
198
199 /// The original set of attributes on the DeclSpec.
201
202 /// A list of attributes to diagnose the uselessness of when the
203 /// processing is complete.
204 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
205
206 /// Attributes corresponding to AttributedTypeLocs that we have not yet
207 /// populated.
208 // FIXME: The two-phase mechanism by which we construct Types and fill
209 // their TypeLocs makes it hard to correctly assign these. We keep the
210 // attributes in creation order as an attempt to make them line up
211 // properly.
212 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
213 SmallVector<TypeAttrPair, 8> AttrsForTypes;
214 bool AttrsForTypesSorted = true;
215
216 /// MacroQualifiedTypes mapping to macro expansion locations that will be
217 /// stored in a MacroQualifiedTypeLoc.
218 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
219
220 /// Flag to indicate we parsed a noderef attribute. This is used for
221 /// validating that noderef was used on a pointer or array.
222 bool parsedNoDeref;
223
224 // Flag to indicate that we already parsed a HLSL parameter modifier
225 // attribute. This prevents double-mutating the type.
226 bool ParsedHLSLParamMod;
227
228 public:
229 TypeProcessingState(Sema &sema, Declarator &declarator)
230 : sema(sema), declarator(declarator),
231 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false),
232 ParsedHLSLParamMod(false) {}
233
234 Sema &getSema() const {
235 return sema;
236 }
237
238 Declarator &getDeclarator() const {
239 return declarator;
240 }
241
242 bool isProcessingDeclSpec() const {
243 return chunkIndex == declarator.getNumTypeObjects();
244 }
245
246 unsigned getCurrentChunkIndex() const {
247 return chunkIndex;
248 }
249
250 void setCurrentChunkIndex(unsigned idx) {
251 assert(idx <= declarator.getNumTypeObjects());
252 chunkIndex = idx;
253 }
254
255 ParsedAttributesView &getCurrentAttributes() const {
256 if (isProcessingDeclSpec())
257 return getMutableDeclSpec().getAttributes();
258 return declarator.getTypeObject(chunkIndex).getAttrs();
259 }
260
261 /// Save the current set of attributes on the DeclSpec.
262 void saveDeclSpecAttrs() {
263 // Don't try to save them multiple times.
264 if (!savedAttrs.empty())
265 return;
266
267 DeclSpec &spec = getMutableDeclSpec();
268 llvm::append_range(savedAttrs,
269 llvm::make_pointer_range(spec.getAttributes()));
270 }
271
272 /// Record that we had nowhere to put the given type attribute.
273 /// We will diagnose such attributes later.
274 void addIgnoredTypeAttr(ParsedAttr &attr) {
275 ignoredTypeAttrs.push_back(&attr);
276 }
277
278 /// Diagnose all the ignored type attributes, given that the
279 /// declarator worked out to the given type.
280 void diagnoseIgnoredTypeAttrs(QualType type) const {
281 for (auto *Attr : ignoredTypeAttrs)
282 diagnoseBadTypeAttribute(getSema(), *Attr, type);
283 }
284
285 /// Get an attributed type for the given attribute, and remember the Attr
286 /// object so that we can attach it to the AttributedTypeLoc.
287 QualType getAttributedType(Attr *A, QualType ModifiedType,
288 QualType EquivType) {
289 QualType T =
290 sema.Context.getAttributedType(A, ModifiedType, EquivType);
291 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
292 AttrsForTypesSorted = false;
293 return T;
294 }
295
296 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
297 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
298 QualType WrappedType) {
299 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
300 }
301
302 /// Get a OverflowBehaviorType type for the overflow_behavior type
303 /// attribute.
305 getOverflowBehaviorType(OverflowBehaviorType::OverflowBehaviorKind Kind,
306 QualType UnderlyingType) {
307 return sema.Context.getOverflowBehaviorType(Kind, UnderlyingType);
308 }
309
310 /// Completely replace the \c auto in \p TypeWithAuto by
311 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
312 /// necessary.
313 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
314 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
315 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
316 // Attributed type still should be an attributed type after replacement.
317 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
318 for (TypeAttrPair &A : AttrsForTypes) {
319 if (A.first == AttrTy)
320 A.first = NewAttrTy;
321 }
322 AttrsForTypesSorted = false;
323 }
324 return T;
325 }
326
327 /// Extract and remove the Attr* for a given attributed type.
328 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
329 if (!AttrsForTypesSorted) {
330 llvm::stable_sort(AttrsForTypes, llvm::less_first());
331 AttrsForTypesSorted = true;
332 }
333
334 // FIXME: This is quadratic if we have lots of reuses of the same
335 // attributed type.
336 for (auto It = llvm::partition_point(
337 AttrsForTypes,
338 [=](const TypeAttrPair &A) { return A.first < AT; });
339 It != AttrsForTypes.end() && It->first == AT; ++It) {
340 if (It->second) {
341 const Attr *Result = It->second;
342 It->second = nullptr;
343 return Result;
344 }
345 }
346
347 // The AttributedType can be inherited from another declarator, for
348 // example when __typeof__ reuses a type built for a different
349 // declaration, in which case there is no entry for it in this
350 // TypeProcessingState. Return null in that case.
351 return nullptr;
352 }
353
355 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
356 auto FoundLoc = LocsForMacros.find(MQT);
357 assert(FoundLoc != LocsForMacros.end() &&
358 "Unable to find macro expansion location for MacroQualifedType");
359 return FoundLoc->second;
360 }
361
362 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
363 SourceLocation Loc) {
364 LocsForMacros[MQT] = Loc;
365 }
366
367 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
368
369 bool didParseNoDeref() const { return parsedNoDeref; }
370
371 void setParsedHLSLParamMod(bool Parsed) { ParsedHLSLParamMod = Parsed; }
372
373 bool didParseHLSLParamMod() const { return ParsedHLSLParamMod; }
374
375 ~TypeProcessingState() {
376 if (savedAttrs.empty())
377 return;
378
379 getMutableDeclSpec().getAttributes().clearListOnly();
380 for (ParsedAttr *AL : savedAttrs)
381 getMutableDeclSpec().getAttributes().addAtEnd(AL);
382 }
383
384 private:
385 DeclSpec &getMutableDeclSpec() const {
386 return const_cast<DeclSpec&>(declarator.getDeclSpec());
387 }
388 };
389} // end anonymous namespace
390
392 ParsedAttributesView &fromList,
393 ParsedAttributesView &toList) {
394 fromList.remove(&attr);
395 toList.addAtEnd(&attr);
396}
397
398/// The location of a type attribute.
400 /// The attribute is in the decl-specifier-seq.
402 /// The attribute is part of a DeclaratorChunk.
404 /// The attribute is immediately after the declaration's name.
406};
407
408static void
409processTypeAttrs(TypeProcessingState &state, QualType &type,
410 TypeAttrLocation TAL, const ParsedAttributesView &attrs,
412
413static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
415
416static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
418
419static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
420 QualType &type);
421
422static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
424
425static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
427 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
428 return handleObjCGCTypeAttr(state, attr, type);
429 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
430 return handleObjCOwnershipTypeAttr(state, attr, type);
431}
432
433/// Given the index of a declarator chunk, check whether that chunk
434/// directly specifies the return type of a function and, if so, find
435/// an appropriate place for it.
436///
437/// \param i - a notional index which the search will start
438/// immediately inside
439///
440/// \param onlyBlockPointers Whether we should only look into block
441/// pointer types (vs. all pointer types).
443 unsigned i,
444 bool onlyBlockPointers) {
445 assert(i <= declarator.getNumTypeObjects());
446
447 DeclaratorChunk *result = nullptr;
448
449 // First, look inwards past parens for a function declarator.
450 for (; i != 0; --i) {
451 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
452 switch (fnChunk.Kind) {
454 continue;
455
456 // If we find anything except a function, bail out.
463 return result;
464
465 // If we do find a function declarator, scan inwards from that,
466 // looking for a (block-)pointer declarator.
468 for (--i; i != 0; --i) {
469 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
470 switch (ptrChunk.Kind) {
476 continue;
477
480 if (onlyBlockPointers)
481 continue;
482
483 [[fallthrough]];
484
486 result = &ptrChunk;
487 goto continue_outer;
488 }
489 llvm_unreachable("bad declarator chunk kind");
490 }
491
492 // If we run out of declarators doing that, we're done.
493 return result;
494 }
495 llvm_unreachable("bad declarator chunk kind");
496
497 // Okay, reconsider from our new point.
498 continue_outer: ;
499 }
500
501 // Ran out of chunks, bail out.
502 return result;
503}
504
505/// Given that an objc_gc attribute was written somewhere on a
506/// declaration *other* than on the declarator itself (for which, use
507/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
508/// didn't apply in whatever position it was written in, try to move
509/// it to a more appropriate position.
510static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
512 Declarator &declarator = state.getDeclarator();
513
514 // Move it to the outermost normal or block pointer declarator.
515 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
516 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
517 switch (chunk.Kind) {
520 // But don't move an ARC ownership attribute to the return type
521 // of a block.
522 DeclaratorChunk *destChunk = nullptr;
523 if (state.isProcessingDeclSpec() &&
524 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
525 destChunk = maybeMovePastReturnType(declarator, i - 1,
526 /*onlyBlockPointers=*/true);
527 if (!destChunk) destChunk = &chunk;
528
529 moveAttrFromListToList(attr, state.getCurrentAttributes(),
530 destChunk->getAttrs());
531 return;
532 }
533
536 continue;
537
538 // We may be starting at the return type of a block.
540 if (state.isProcessingDeclSpec() &&
541 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
543 declarator, i,
544 /*onlyBlockPointers=*/true)) {
545 moveAttrFromListToList(attr, state.getCurrentAttributes(),
546 dest->getAttrs());
547 return;
548 }
549 }
550 goto error;
551
552 // Don't walk through these.
556 goto error;
557 }
558 }
559 error:
560
561 diagnoseBadTypeAttribute(state.getSema(), attr, type);
562}
563
564/// Distribute an objc_gc type attribute that was written on the
565/// declarator.
567 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
568 Declarator &declarator = state.getDeclarator();
569
570 // objc_gc goes on the innermost pointer to something that's not a
571 // pointer.
572 unsigned innermost = -1U;
573 bool considerDeclSpec = true;
574 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
575 DeclaratorChunk &chunk = declarator.getTypeObject(i);
576 switch (chunk.Kind) {
579 innermost = i;
580 continue;
581
587 continue;
588
590 considerDeclSpec = false;
591 goto done;
592 }
593 }
594 done:
595
596 // That might actually be the decl spec if we weren't blocked by
597 // anything in the declarator.
598 if (considerDeclSpec) {
599 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
600 // Splice the attribute into the decl spec. Prevents the
601 // attribute from being applied multiple times and gives
602 // the source-location-filler something to work with.
603 state.saveDeclSpecAttrs();
605 declarator.getAttributes(), &attr);
606 return;
607 }
608 }
609
610 // Otherwise, if we found an appropriate chunk, splice the attribute
611 // into it.
612 if (innermost != -1U) {
614 declarator.getTypeObject(innermost).getAttrs());
615 return;
616 }
617
618 // Otherwise, diagnose when we're done building the type.
619 declarator.getAttributes().remove(&attr);
620 state.addIgnoredTypeAttr(attr);
621}
622
623/// A function type attribute was written somewhere in a declaration
624/// *other* than on the declarator itself or in the decl spec. Given
625/// that it didn't apply in whatever position it was written in, try
626/// to move it to a more appropriate position.
627static void distributeFunctionTypeAttr(TypeProcessingState &state,
629 Declarator &declarator = state.getDeclarator();
630
631 // Try to push the attribute from the return type of a function to
632 // the function itself.
633 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
634 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
635 switch (chunk.Kind) {
637 moveAttrFromListToList(attr, state.getCurrentAttributes(),
638 chunk.getAttrs());
639 return;
640
648 continue;
649 }
650 }
651
652 diagnoseBadTypeAttribute(state.getSema(), attr, type);
653}
654
655/// Try to distribute a function type attribute to the innermost
656/// function chunk or type. Returns true if the attribute was
657/// distributed, false if no location was found.
659 TypeProcessingState &state, ParsedAttr &attr,
660 ParsedAttributesView &attrList, QualType &declSpecType,
661 CUDAFunctionTarget CFT) {
662 Declarator &declarator = state.getDeclarator();
663
664 // Put it on the innermost function chunk, if there is one.
665 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
666 DeclaratorChunk &chunk = declarator.getTypeObject(i);
667 if (chunk.Kind != DeclaratorChunk::Function) continue;
668
669 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
670 return true;
671 }
672
673 return handleFunctionTypeAttr(state, attr, declSpecType, CFT);
674}
675
676/// A function type attribute was written in the decl spec. Try to
677/// apply it somewhere.
678static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
680 QualType &declSpecType,
681 CUDAFunctionTarget CFT) {
682 state.saveDeclSpecAttrs();
683
684 // Try to distribute to the innermost.
686 state, attr, state.getCurrentAttributes(), declSpecType, CFT))
687 return;
688
689 // If that failed, diagnose the bad attribute when the declarator is
690 // fully built.
691 state.addIgnoredTypeAttr(attr);
692}
693
694/// A function type attribute was written on the declarator or declaration.
695/// Try to apply it somewhere.
696/// `Attrs` is the attribute list containing the declaration (either of the
697/// declarator or the declaration).
698static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
700 QualType &declSpecType,
701 CUDAFunctionTarget CFT) {
702 Declarator &declarator = state.getDeclarator();
703
704 // Try to distribute to the innermost.
706 state, attr, declarator.getAttributes(), declSpecType, CFT))
707 return;
708
709 // If that failed, diagnose the bad attribute when the declarator is
710 // fully built.
711 declarator.getAttributes().remove(&attr);
712 state.addIgnoredTypeAttr(attr);
713}
714
715/// Given that there are attributes written on the declarator or declaration
716/// itself, try to distribute any type attributes to the appropriate
717/// declarator chunk.
718///
719/// These are attributes like the following:
720/// int f ATTR;
721/// int (f ATTR)();
722/// but not necessarily this:
723/// int f() ATTR;
724///
725/// `Attrs` is the attribute list containing the declaration (either of the
726/// declarator or the declaration).
727static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
728 QualType &declSpecType,
729 CUDAFunctionTarget CFT) {
730 // The called functions in this loop actually remove things from the current
731 // list, so iterating over the existing list isn't possible. Instead, make a
732 // non-owning copy and iterate over that.
733 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
734 for (ParsedAttr &attr : AttrsCopy) {
735 // Do not distribute [[]] attributes. They have strict rules for what
736 // they appertain to.
737 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute())
738 continue;
739
740 switch (attr.getKind()) {
743 break;
744
746 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT);
747 break;
748
750 // Microsoft type attributes cannot go after the declarator-id.
751 continue;
752
754 // Nullability specifiers cannot go after the declarator-id.
755
756 // Objective-C __kindof does not get distributed.
757 case ParsedAttr::AT_ObjCKindOf:
758 continue;
759
760 default:
761 break;
762 }
763 }
764}
765
766/// Add a synthetic '()' to a block-literal declarator if it is
767/// required, given the return type.
768static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
769 QualType declSpecType) {
770 Declarator &declarator = state.getDeclarator();
771
772 // First, check whether the declarator would produce a function,
773 // i.e. whether the innermost semantic chunk is a function.
774 if (declarator.isFunctionDeclarator()) {
775 // If so, make that declarator a prototyped declarator.
776 declarator.getFunctionTypeInfo().hasPrototype = true;
777 return;
778 }
779
780 // If there are any type objects, the type as written won't name a
781 // function, regardless of the decl spec type. This is because a
782 // block signature declarator is always an abstract-declarator, and
783 // abstract-declarators can't just be parentheses chunks. Therefore
784 // we need to build a function chunk unless there are no type
785 // objects and the decl spec type is a function.
786 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
787 return;
788
789 // Note that there *are* cases with invalid declarators where
790 // declarators consist solely of parentheses. In general, these
791 // occur only in failed efforts to make function declarators, so
792 // faking up the function chunk is still the right thing to do.
793
794 // Otherwise, we need to fake up a function declarator.
795 SourceLocation loc = declarator.getBeginLoc();
796
797 // ...and *prepend* it to the declarator.
798 SourceLocation NoLoc;
800 /*HasProto=*/true,
801 /*IsAmbiguous=*/false,
802 /*LParenLoc=*/NoLoc,
803 /*ArgInfo=*/nullptr,
804 /*NumParams=*/0,
805 /*EllipsisLoc=*/NoLoc,
806 /*RParenLoc=*/NoLoc,
807 /*RefQualifierIsLvalueRef=*/true,
808 /*RefQualifierLoc=*/NoLoc,
809 /*MutableLoc=*/NoLoc, EST_None,
810 /*ESpecRange=*/SourceRange(),
811 /*Exceptions=*/nullptr,
812 /*ExceptionRanges=*/nullptr,
813 /*NumExceptions=*/0,
814 /*NoexceptExpr=*/nullptr,
815 /*ExceptionSpecTokens=*/nullptr,
816 /*DeclsInPrototype=*/{}, loc, loc, declarator));
817
818 // For consistency, make sure the state still has us as processing
819 // the decl spec.
820 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
821 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
822}
823
825 unsigned &TypeQuals,
826 QualType TypeSoFar,
827 unsigned RemoveTQs,
828 unsigned DiagID) {
829 // If this occurs outside a template instantiation, warn the user about
830 // it; they probably didn't mean to specify a redundant qualifier.
831 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
832 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
835 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
836 if (!(RemoveTQs & Qual.first))
837 continue;
838
839 if (!S.inTemplateInstantiation()) {
840 if (TypeQuals & Qual.first)
841 S.Diag(Qual.second, DiagID)
842 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
843 << FixItHint::CreateRemoval(Qual.second);
844 }
845
846 TypeQuals &= ~Qual.first;
847 }
848}
849
850/// Return true if this is omitted block return type. Also check type
851/// attributes and type qualifiers when returning true.
852static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
854 if (!isOmittedBlockReturnType(declarator))
855 return false;
856
857 // Warn if we see type attributes for omitted return type on a block literal.
859 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
860 if (AL.isInvalid() || !AL.isTypeAttr())
861 continue;
862 S.Diag(AL.getLoc(),
863 diag::warn_block_literal_attributes_on_omitted_return_type)
864 << AL;
865 ToBeRemoved.push_back(&AL);
866 }
867 // Remove bad attributes from the list.
868 for (ParsedAttr *AL : ToBeRemoved)
869 declarator.getMutableDeclSpec().getAttributes().remove(AL);
870
871 // Warn if we see type qualifiers for omitted return type on a block literal.
872 const DeclSpec &DS = declarator.getDeclSpec();
873 unsigned TypeQuals = DS.getTypeQualifiers();
874 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
875 diag::warn_block_literal_qualifiers_on_omitted_return_type);
877
878 return true;
879}
880
881static OpenCLAccessAttr::Spelling
883 for (const ParsedAttr &AL : Attrs)
884 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
885 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
886 return OpenCLAccessAttr::Keyword_read_only;
887}
888
889static UnaryTransformType::UTTKind
891 switch (SwitchTST) {
892#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
893 case TST_##Trait: \
894 return UnaryTransformType::Enum;
895#include "clang/Basic/BuiltinTraits.inc"
896 default:
897 llvm_unreachable("attempted to parse a non-unary transform builtin");
898 }
899}
900
901/// Convert the specified declspec to the appropriate type
902/// object.
903/// \param state Specifies the declarator containing the declaration specifier
904/// to be converted, along with other associated processing state.
905/// \returns The type described by the declaration specifiers. This function
906/// never returns null.
907static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
908 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
909 // checking.
910
911 Sema &S = state.getSema();
912 Declarator &declarator = state.getDeclarator();
913 DeclSpec &DS = declarator.getMutableDeclSpec();
914 SourceLocation DeclLoc = declarator.getIdentifierLoc();
915 if (DeclLoc.isInvalid())
916 DeclLoc = DS.getBeginLoc();
917
918 ASTContext &Context = S.Context;
919
921 switch (DS.getTypeSpecType()) {
923 Result = Context.VoidTy;
924 break;
927 Result = Context.CharTy;
929 Result = Context.SignedCharTy;
930 else {
932 "Unknown TSS value");
933 Result = Context.UnsignedCharTy;
934 }
935 break;
938 Result = Context.WCharTy;
940 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
942 Context.getPrintingPolicy());
943 Result = Context.getSignedWCharType();
944 } else {
946 "Unknown TSS value");
947 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
949 Context.getPrintingPolicy());
950 Result = Context.getUnsignedWCharType();
951 }
952 break;
955 "Unknown TSS value");
956 Result = Context.Char8Ty;
957 break;
960 "Unknown TSS value");
961 Result = Context.Char16Ty;
962 break;
965 "Unknown TSS value");
966 Result = Context.Char32Ty;
967 break;
969 // If this is a missing declspec in a block literal return context, then it
970 // is inferred from the return statements inside the block.
971 // The declspec is always missing in a lambda expr context; it is either
972 // specified with a trailing return type or inferred.
973 if (S.getLangOpts().CPlusPlus14 &&
975 // In C++1y, a lambda's implicit return type is 'auto'.
976 Result = Context.getAutoDeductType();
977 break;
978 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
979 checkOmittedBlockReturnType(S, declarator,
980 Context.DependentTy)) {
981 Result = Context.DependentTy;
982 break;
983 }
984
985 // Unspecified typespec defaults to int in C90. However, the C90 grammar
986 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
987 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
988 // Note that the one exception to this is function definitions, which are
989 // allowed to be completely missing a declspec. This is handled in the
990 // parser already though by it pretending to have seen an 'int' in this
991 // case.
993 // Only emit the diagnostic for the first declarator in a DeclGroup, as
994 // the warning is always implied for all subsequent declarators, and the
995 // fix must only be applied exactly once as well.
996 if (declarator.isFirstDeclarator()) {
997 S.Diag(DeclLoc, diag::warn_missing_type_specifier)
998 << DS.getSourceRange()
1000 }
1001 } else if (!DS.hasTypeSpecifier()) {
1002 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1003 // "At least one type specifier shall be given in the declaration
1004 // specifiers in each declaration, and in the specifier-qualifier list
1005 // in each struct declaration and type name."
1006 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
1007 if (declarator.isFirstDeclarator()) {
1008 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1009 << DS.getSourceRange();
1010 }
1011
1012 // When this occurs, often something is very broken with the value
1013 // being declared, poison it as invalid so we don't get chains of
1014 // errors.
1015 declarator.setInvalidType(true);
1016 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1017 DS.isTypeSpecPipe()) {
1018 if (declarator.isFirstDeclarator()) {
1019 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1020 << DS.getSourceRange();
1021 }
1022 declarator.setInvalidType(true);
1023 } else if (declarator.isFirstDeclarator()) {
1024 assert(S.getLangOpts().isImplicitIntAllowed() &&
1025 "implicit int is disabled?");
1026 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1027 << DS.getSourceRange()
1028 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int ");
1029 }
1030 }
1031
1032 [[fallthrough]];
1033 case DeclSpec::TST_int: {
1035 switch (DS.getTypeSpecWidth()) {
1037 Result = Context.IntTy;
1038 break;
1040 Result = Context.ShortTy;
1041 break;
1043 Result = Context.LongTy;
1044 break;
1046 Result = Context.LongLongTy;
1047
1048 if (S.getLangOpts().OpenCL) {
1049 // OpenCL v3.0 s6.3.4: 'long long' is a reserved data type.
1050 S.Diag(DS.getTypeSpecWidthLoc(), diag::warn_opencl_longlong);
1051 } else if (!S.getLangOpts().C99) {
1052 // 'long long' is a C99 or C++11 feature.
1053 if (S.getLangOpts().CPlusPlus)
1055 S.getLangOpts().CPlusPlus11 ?
1056 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1057 else
1058 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1059 }
1060 break;
1061 }
1062 } else {
1063 switch (DS.getTypeSpecWidth()) {
1065 Result = Context.UnsignedIntTy;
1066 break;
1068 Result = Context.UnsignedShortTy;
1069 break;
1071 Result = Context.UnsignedLongTy;
1072 break;
1074 Result = Context.UnsignedLongLongTy;
1075
1076 if (S.getLangOpts().OpenCL) {
1077 // OpenCL v3.0 s6.3.4: 'long long' is a reserved data type.
1078 S.Diag(DS.getTypeSpecWidthLoc(), diag::warn_opencl_longlong);
1079 } else if (!S.getLangOpts().C99) {
1080 // 'long long' is a C99 or C++11 feature.
1081 if (S.getLangOpts().CPlusPlus)
1083 S.getLangOpts().CPlusPlus11 ?
1084 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1085 else
1086 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1087 }
1088 break;
1089 }
1090 }
1091 break;
1092 }
1093 case DeclSpec::TST_bitint: {
1095 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1096 Result =
1098 DS.getRepAsExpr(), DS.getBeginLoc());
1099 if (Result.isNull()) {
1100 Result = Context.IntTy;
1101 declarator.setInvalidType(true);
1102 }
1103 break;
1104 }
1105 case DeclSpec::TST_accum: {
1106 switch (DS.getTypeSpecWidth()) {
1108 Result = Context.ShortAccumTy;
1109 break;
1111 Result = Context.AccumTy;
1112 break;
1114 Result = Context.LongAccumTy;
1115 break;
1117 llvm_unreachable("Unable to specify long long as _Accum width");
1118 }
1119
1121 Result = Context.getCorrespondingUnsignedType(Result);
1122
1123 if (DS.isTypeSpecSat())
1124 Result = Context.getCorrespondingSaturatedType(Result);
1125
1126 break;
1127 }
1128 case DeclSpec::TST_fract: {
1129 switch (DS.getTypeSpecWidth()) {
1131 Result = Context.ShortFractTy;
1132 break;
1134 Result = Context.FractTy;
1135 break;
1137 Result = Context.LongFractTy;
1138 break;
1140 llvm_unreachable("Unable to specify long long as _Fract width");
1141 }
1142
1144 Result = Context.getCorrespondingUnsignedType(Result);
1145
1146 if (DS.isTypeSpecSat())
1147 Result = Context.getCorrespondingSaturatedType(Result);
1148
1149 break;
1150 }
1152 if (!S.Context.getTargetInfo().hasInt128Type() &&
1153 !(S.getLangOpts().isTargetDevice()))
1154 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1155 << "__int128";
1157 Result = Context.UnsignedInt128Ty;
1158 else
1159 Result = Context.Int128Ty;
1160 break;
1162 // CUDA host and device may have different _Float16 support, therefore
1163 // do not diagnose _Float16 usage to avoid false alarm.
1164 // ToDo: more precise diagnostics for CUDA.
1165 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1166 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1167 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1168 << "_Float16";
1169 Result = Context.Float16Ty;
1170 break;
1171 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1174 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) &&
1175 !S.getLangOpts().SYCLIsDevice)
1176 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16";
1177 Result = Context.BFloat16Ty;
1178 break;
1179 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1182 Result = Context.LongDoubleTy;
1183 else
1184 Result = Context.DoubleTy;
1185 if (S.getLangOpts().OpenCL) {
1186 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1187 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1188 << 0 << Result
1189 << (S.getLangOpts().getOpenCLCompatibleVersion() >= 300
1190 ? "cl_khr_fp64 and __opencl_c_fp64"
1191 : "cl_khr_fp64");
1192 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1193 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1194 }
1195 break;
1199 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1200 << "__float128";
1201 Result = Context.Float128Ty;
1202 break;
1204 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1205 !S.getLangOpts().SYCLIsDevice &&
1206 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1207 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1208 Result = Context.Ibm128Ty;
1209 break;
1210 case DeclSpec::TST_bool:
1211 Result = Context.BoolTy; // _Bool or bool
1212 break;
1213 case DeclSpec::TST_decimal32: // _Decimal32
1214 case DeclSpec::TST_decimal64: // _Decimal64
1215 case DeclSpec::TST_decimal128: // _Decimal128
1216 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1217 Result = Context.IntTy;
1218 declarator.setInvalidType(true);
1219 break;
1221 case DeclSpec::TST_enum:
1225 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1226 if (!D) {
1227 // This can happen in C++ with ambiguous lookups.
1228 Result = Context.IntTy;
1229 declarator.setInvalidType(true);
1230 break;
1231 }
1232
1233 // If the type is deprecated or unavailable, diagnose it.
1235
1237 DS.getTypeSpecComplex() == 0 &&
1239 "No qualifiers on tag names!");
1240
1243 // TypeQuals handled by caller.
1244 Result = Context.getTagType(Keyword, DS.getTypeSpecScope().getScopeRep(), D,
1245 DS.isTypeSpecOwned());
1246 break;
1247 }
1250 DS.getTypeSpecComplex() == 0 &&
1252 "Can't handle qualifiers on typedef names yet!");
1254 if (Result.isNull()) {
1255 declarator.setInvalidType(true);
1256 }
1257
1258 // TypeQuals handled by caller.
1259 break;
1260 }
1263 // FIXME: Preserve type source info.
1265 assert(!Result.isNull() && "Didn't get a type for typeof?");
1266 if (!Result->isDependentType())
1267 if (const auto *TT = Result->getAs<TagType>())
1268 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1269 // TypeQuals handled by caller.
1270 Result = Context.getTypeOfType(
1274 break;
1277 Expr *E = DS.getRepAsExpr();
1278 assert(E && "Didn't get an expression for typeof?");
1279 // TypeQuals handled by caller.
1284 if (Result.isNull()) {
1285 Result = Context.IntTy;
1286 declarator.setInvalidType(true);
1287 }
1288 break;
1289 }
1291 Expr *E = DS.getRepAsExpr();
1292 assert(E && "Didn't get an expression for decltype?");
1293 // TypeQuals handled by caller.
1295 if (Result.isNull()) {
1296 Result = Context.IntTy;
1297 declarator.setInvalidType(true);
1298 }
1299 break;
1300 }
1303 if (Result.isNull()) {
1304 declarator.setInvalidType(true);
1305 Result = Context.IntTy;
1306 }
1307 break;
1308 }
1309
1310#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1311#include "clang/Basic/BuiltinTraits.inc"
1313 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1316 DS.getTypeSpecTypeLoc());
1317 if (Result.isNull()) {
1318 Result = Context.IntTy;
1319 declarator.setInvalidType(true);
1320 }
1321 break;
1322
1323 case DeclSpec::TST_auto:
1325 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1328
1329 TemplateName TypeConstraintConcept;
1331 if (DS.isConstrainedAuto()) {
1332 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1333 TypeConstraintConcept = TemplateId->Template.get();
1334 TemplateArgumentListInfo TemplateArgsInfo;
1335 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1336 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1337 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1338 TemplateId->NumArgs);
1339 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1340 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1341 TemplateArgs.push_back(ArgLoc.getArgument());
1342 } else {
1343 declarator.setInvalidType(true);
1344 }
1345 }
1347 TypeConstraintConcept, TemplateArgs);
1348 break;
1349 }
1350
1352 Result = Context.getAutoType(DeducedKind::Undeduced, QualType(),
1354 break;
1355
1357 Result = Context.UnknownAnyTy;
1358 break;
1359
1362 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1364 if (Result.isNull()) {
1365 Result = Context.IntTy;
1366 declarator.setInvalidType(true);
1367 }
1368 break;
1369
1370#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1371 case DeclSpec::TST_##ImgType##_t: \
1372 switch (getImageAccess(DS.getAttributes())) { \
1373 case OpenCLAccessAttr::Keyword_write_only: \
1374 Result = Context.Id##WOTy; \
1375 break; \
1376 case OpenCLAccessAttr::Keyword_read_write: \
1377 Result = Context.Id##RWTy; \
1378 break; \
1379 case OpenCLAccessAttr::Keyword_read_only: \
1380 Result = Context.Id##ROTy; \
1381 break; \
1382 case OpenCLAccessAttr::SpellingNotCalculated: \
1383 llvm_unreachable("Spelling not yet calculated"); \
1384 } \
1385 break;
1386#include "clang/Basic/OpenCLImageTypes.def"
1387
1388#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1389 case DeclSpec::TST_##Name: \
1390 Result = Context.SingletonId; \
1391 break;
1392#include "clang/Basic/HLSLIntangibleTypes.def"
1393
1394#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
1395 case DeclSpec::TST_##Name: \
1396 Result = Context.SingletonId; \
1397 break;
1398#include "clang/Basic/HLSLPackedTypes.def"
1399
1401 Result = Context.IntTy;
1402 declarator.setInvalidType(true);
1403 break;
1404 }
1405
1406 // FIXME: we want resulting declarations to be marked invalid, but claiming
1407 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1408 // a null type.
1409 if (Result->containsErrors())
1410 declarator.setInvalidType();
1411
1412 if (S.getLangOpts().OpenCL) {
1413 const auto &OpenCLOptions = S.getOpenCLOptions();
1414 bool IsOpenCLC30Compatible =
1416 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1417 // support.
1418 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1419 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1420 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1421 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1422 // only when the optional feature is supported
1423 if ((Result->isImageType() || Result->isSamplerT()) &&
1424 (IsOpenCLC30Compatible &&
1425 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1426 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1427 << 0 << Result << "__opencl_c_images";
1428 declarator.setInvalidType();
1429 } else if (Result->isOCLImage3dWOType() &&
1430 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1431 S.getLangOpts())) {
1432 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1433 << 0 << Result
1434 << (IsOpenCLC30Compatible
1435 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1436 : "cl_khr_3d_image_writes");
1437 declarator.setInvalidType();
1438 }
1439 }
1440
1441 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1443
1444 // Only fixed point types can be saturated
1445 if (DS.isTypeSpecSat() && !IsFixedPointType)
1446 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1448 Context.getPrintingPolicy());
1449
1450 // Handle complex types.
1452 if (S.getLangOpts().Freestanding)
1453 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1454 Result = Context.getComplexType(Result);
1455 } else if (DS.isTypeAltiVecVector()) {
1456 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1457 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1459 if (DS.isTypeAltiVecPixel())
1460 VecKind = VectorKind::AltiVecPixel;
1461 else if (DS.isTypeAltiVecBool())
1462 VecKind = VectorKind::AltiVecBool;
1463 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1464 }
1465
1466 // _Imaginary was a feature of C99 through C23 but was never supported in
1467 // Clang. The feature was removed in C2y, but we retain the unsupported
1468 // diagnostic for an improved user experience.
1470 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1471
1472 // Before we process any type attributes, synthesize a block literal
1473 // function declarator if necessary.
1474 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1476
1477 // Apply any type attributes from the decl spec. This may cause the
1478 // list of type attributes to be temporarily saved while the type
1479 // attributes are pushed around.
1480 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1481 if (!DS.isTypeSpecPipe()) {
1482 // We also apply declaration attributes that "slide" to the decl spec.
1483 // Ordering can be important for attributes. The decalaration attributes
1484 // come syntactically before the decl spec attributes, so we process them
1485 // in that order.
1486 ParsedAttributesView SlidingAttrs;
1487 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1488 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1489 SlidingAttrs.addAtEnd(&AL);
1490
1491 // For standard syntax attributes, which would normally appertain to the
1492 // declaration here, suggest moving them to the type instead. But only
1493 // do this for our own vendor attributes; moving other vendors'
1494 // attributes might hurt portability.
1495 // There's one special case that we need to deal with here: The
1496 // `MatrixType` attribute may only be used in a typedef declaration. If
1497 // it's being used anywhere else, don't output the warning as
1498 // ProcessDeclAttributes() will output an error anyway.
1499 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1500 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1502 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1503 << AL;
1504 }
1505 }
1506 }
1507 // During this call to processTypeAttrs(),
1508 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1509 // reference to the DeclSpec attributes, rather than the declaration
1510 // attributes. However, this doesn't matter, as getCurrentAttributes()
1511 // is only called when distributing attributes from one attribute list
1512 // to another. Declaration attributes are always C++11 attributes, and these
1513 // are never distributed.
1514 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1516 }
1517
1518 // Apply const/volatile/restrict qualifiers to T.
1519 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1520 // Warn about CV qualifiers on function types.
1521 // C99 6.7.3p8:
1522 // If the specification of a function type includes any type qualifiers,
1523 // the behavior is undefined.
1524 // C2y changed this behavior to be implementation-defined. Clang defines
1525 // the behavior in all cases to ignore the qualifier, as in C++.
1526 // C++11 [dcl.fct]p7:
1527 // The effect of a cv-qualifier-seq in a function declarator is not the
1528 // same as adding cv-qualification on top of the function type. In the
1529 // latter case, the cv-qualifiers are ignored.
1530 if (Result->isFunctionType()) {
1531 unsigned DiagId = diag::warn_typecheck_function_qualifiers_ignored;
1532 if (!S.getLangOpts().CPlusPlus && !S.getLangOpts().C2y)
1533 DiagId = diag::ext_typecheck_function_qualifiers_unspecified;
1535 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1536 DiagId);
1537 // No diagnostic for 'restrict' or '_Atomic' applied to a
1538 // function type; we'll diagnose those later, in BuildQualifiedType.
1539 }
1540
1541 // C++11 [dcl.ref]p1:
1542 // Cv-qualified references are ill-formed except when the
1543 // cv-qualifiers are introduced through the use of a typedef-name
1544 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1545 //
1546 // There don't appear to be any other contexts in which a cv-qualified
1547 // reference type could be formed, so the 'ill-formed' clause here appears
1548 // to never happen.
1549 if (TypeQuals && Result->isReferenceType()) {
1551 S, DS, TypeQuals, Result,
1553 diag::warn_typecheck_reference_qualifiers);
1554 }
1555
1556 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1557 // than once in the same specifier-list or qualifier-list, either directly
1558 // or via one or more typedefs."
1559 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1560 && TypeQuals & Result.getCVRQualifiers()) {
1561 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1562 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1563 << "const";
1564 }
1565
1566 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1567 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1568 << "volatile";
1569 }
1570
1571 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1572 // produce a warning in this case.
1573 }
1574
1575 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1576
1577 // If adding qualifiers fails, just use the unqualified type.
1578 if (Qualified.isNull())
1579 declarator.setInvalidType(true);
1580 else
1581 Result = Qualified;
1582 }
1583
1584 // Check for __ob_wrap and __ob_trap
1585 if (DS.isOverflowBehaviorSpecified() &&
1586 S.getLangOpts().OverflowBehaviorTypes) {
1587 if (Result->isAtomicType()) {
1589 StringRef SpecifierName =
1591 S.Diag(Loc, diag::err_overflow_behavior_atomic_type)
1592 << SpecifierName << Result.getAsString() << 1;
1593 } else if (!Result->isIntegerType()) {
1595 StringRef SpecifierName =
1597 S.Diag(Loc, diag::err_overflow_behavior_non_integer_type)
1598 << SpecifierName << Result.getAsString() << 1;
1599 } else {
1600 OverflowBehaviorType::OverflowBehaviorKind Kind =
1601 DS.isWrapSpecified()
1602 ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
1603 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
1604 Result = state.getOverflowBehaviorType(Kind, Result);
1605 }
1606 }
1607
1608 if (S.getLangOpts().HLSL)
1610
1611 assert(!Result.isNull() && "This function should not return a null type");
1612 return Result;
1613}
1614
1615static std::string getPrintableNameForEntity(DeclarationName Entity) {
1616 if (Entity)
1617 return Entity.getAsString();
1618
1619 return "type name";
1620}
1621
1623 Qualifiers Qs, const DeclSpec *DS) {
1624 if (T.isNull())
1625 return QualType();
1626
1627 // Ignore any attempt to form a cv-qualified reference.
1628 if (T->isReferenceType()) {
1629 Qs.removeConst();
1630 Qs.removeVolatile();
1631 }
1632
1633 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1634 // object or incomplete types shall not be restrict-qualified."
1635 if (Qs.hasRestrict()) {
1636 unsigned DiagID = 0;
1637 QualType EltTy = Context.getBaseElementType(T);
1638
1639 if (EltTy->isAnyPointerType() || EltTy->isReferenceType() ||
1640 EltTy->isMemberPointerType()) {
1641
1642 if (const auto *PTy = EltTy->getAs<MemberPointerType>())
1643 EltTy = PTy->getPointeeType();
1644 else
1645 EltTy = EltTy->getPointeeType();
1646
1647 // If we have a pointer or reference, the pointee must have an object
1648 // incomplete type.
1649 if (!EltTy->isIncompleteOrObjectType())
1650 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1651
1652 } else if (!T->isDependentType() && !isa<AutoType>(T)) {
1653 // For an inferred type, we may not have seen the initializer yet and so
1654 // have no idea whether the underlying type is a pointer type or not.
1655 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1656 EltTy = T;
1657 }
1658
1659 Loc = DS ? DS->getRestrictSpecLoc() : Loc;
1660 if (DiagID) {
1661 Diag(Loc, DiagID) << EltTy;
1662 Qs.removeRestrict();
1663 } else {
1664 if (T->isArrayType())
1665 DiagCompat(Loc, diag_compat::restrict_on_array_of_pointers);
1666 }
1667 }
1668
1669 return Context.getQualifiedType(T, Qs);
1670}
1671
1673 unsigned CVRAU, const DeclSpec *DS) {
1674 if (T.isNull())
1675 return QualType();
1676
1677 // Ignore any attempt to form a cv-qualified reference.
1678 if (T->isReferenceType())
1679 CVRAU &=
1681
1682 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1683 // TQ_unaligned;
1684 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1685
1686 // C11 6.7.3/5:
1687 // If the same qualifier appears more than once in the same
1688 // specifier-qualifier-list, either directly or via one or more typedefs,
1689 // the behavior is the same as if it appeared only once.
1690 //
1691 // It's not specified what happens when the _Atomic qualifier is applied to
1692 // a type specified with the _Atomic specifier, but we assume that this
1693 // should be treated as if the _Atomic qualifier appeared multiple times.
1694 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1695 // C11 6.7.3/5:
1696 // If other qualifiers appear along with the _Atomic qualifier in a
1697 // specifier-qualifier-list, the resulting type is the so-qualified
1698 // atomic type.
1699 //
1700 // Don't need to worry about array types here, since _Atomic can't be
1701 // applied to such types.
1702 SplitQualType Split = T.getSplitUnqualifiedType();
1703 T = BuildAtomicType(QualType(Split.Ty, 0),
1704 DS ? DS->getAtomicSpecLoc() : Loc);
1705 if (T.isNull())
1706 return T;
1707 Split.Quals.addCVRQualifiers(CVR);
1708 return BuildQualifiedType(T, Loc, Split.Quals);
1709 }
1710
1713 return BuildQualifiedType(T, Loc, Q, DS);
1714}
1715
1717 return Context.getParenType(T);
1718}
1719
1720/// Given that we're building a pointer or reference to the given
1722 SourceLocation loc,
1723 bool isReference) {
1724 // Bail out if retention is unrequired or already specified.
1725 if (!type->isObjCLifetimeType() ||
1726 type.getObjCLifetime() != Qualifiers::OCL_None)
1727 return type;
1728
1730
1731 // If the object type is const-qualified, we can safely use
1732 // __unsafe_unretained. This is safe (because there are no read
1733 // barriers), and it'll be safe to coerce anything but __weak* to
1734 // the resulting type.
1735 if (type.isConstQualified()) {
1736 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1737
1738 // Otherwise, check whether the static type does not require
1739 // retaining. This currently only triggers for Class (possibly
1740 // protocol-qualifed, and arrays thereof).
1741 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1742 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1743
1744 // If we are in an unevaluated context, like sizeof, skip adding a
1745 // qualification.
1746 } else if (S.isUnevaluatedContext()) {
1747 return type;
1748
1749 // If that failed, give an error and recover using __strong. __strong
1750 // is the option most likely to prevent spurious second-order diagnostics,
1751 // like when binding a reference to a field.
1752 } else {
1753 // These types can show up in private ivars in system headers, so
1754 // we need this to not be an error in those cases. Instead we
1755 // want to delay.
1759 diag::err_arc_indirect_no_ownership, type, isReference));
1760 } else {
1761 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1762 }
1763 implicitLifetime = Qualifiers::OCL_Strong;
1764 }
1765 assert(implicitLifetime && "didn't infer any lifetime!");
1766
1767 Qualifiers qs;
1768 qs.addObjCLifetime(implicitLifetime);
1769 return S.Context.getQualifiedType(type, qs);
1770}
1771
1772static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1773 std::string Quals = FnTy->getMethodQuals().getAsString();
1774
1775 switch (FnTy->getRefQualifier()) {
1776 case RQ_None:
1777 break;
1778
1779 case RQ_LValue:
1780 if (!Quals.empty())
1781 Quals += ' ';
1782 Quals += '&';
1783 break;
1784
1785 case RQ_RValue:
1786 if (!Quals.empty())
1787 Quals += ' ';
1788 Quals += "&&";
1789 break;
1790 }
1791
1792 return Quals;
1793}
1794
1795namespace {
1796/// Kinds of declarator that cannot contain a qualified function type.
1797///
1798/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1799/// a function type with a cv-qualifier or a ref-qualifier can only appear
1800/// at the topmost level of a type.
1801///
1802/// Parens and member pointers are permitted. We don't diagnose array and
1803/// function declarators, because they don't allow function types at all.
1804///
1805/// The values of this enum are used in diagnostics.
1806enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1807} // end anonymous namespace
1808
1809/// Check whether the type T is a qualified function type, and if it is,
1810/// diagnose that it cannot be contained within the given kind of declarator.
1812 QualifiedFunctionKind QFK) {
1813 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1814 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1815 if (!FPT ||
1816 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1817 return false;
1818
1819 S.Diag(Loc, diag::err_compound_qualified_function_type)
1820 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1822 return true;
1823}
1824
1826 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1827 if (!FPT ||
1828 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1829 return false;
1830
1831 Diag(Loc, diag::err_qualified_function_typeid)
1833 return true;
1834}
1835
1836// Helper to deduce addr space of a pointee type in OpenCL mode.
1838 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
1839 !PointeeType->isSamplerT() &&
1840 !PointeeType.hasAddressSpace())
1841 PointeeType = S.getASTContext().getAddrSpaceQualType(
1843 return PointeeType;
1844}
1845
1847 SourceLocation Loc, DeclarationName Entity) {
1848 if (T->isReferenceType()) {
1849 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1850 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1851 << getPrintableNameForEntity(Entity) << T;
1852 return QualType();
1853 }
1854
1855 if (T->isFunctionType() && getLangOpts().OpenCL &&
1856 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1857 getLangOpts())) {
1858 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
1859 return QualType();
1860 }
1861
1862 if (getLangOpts().HLSL && Loc.isValid()) {
1863 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
1864 return QualType();
1865 }
1866
1867 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1868 return QualType();
1869
1870 if (T->isObjCObjectType())
1871 return Context.getObjCObjectPointerType(T);
1872
1873 // In ARC, it is forbidden to build pointers to unqualified pointers.
1874 if (getLangOpts().ObjCAutoRefCount)
1875 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1876
1877 if (getLangOpts().OpenCL)
1879
1880 // In WebAssembly, pointers to reference types and pointers to tables are
1881 // illegal.
1882 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
1883 if (T.isWebAssemblyReferenceType()) {
1884 Diag(Loc, diag::err_wasm_reference_pr) << 0;
1885 return QualType();
1886 }
1887
1888 // We need to desugar the type here in case T is a ParenType.
1889 if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
1890 Diag(Loc, diag::err_wasm_table_pr) << 0;
1891 return QualType();
1892 }
1893 }
1894
1895 // Build the pointer type.
1896 return Context.getPointerType(T);
1897}
1898
1900 SourceLocation Loc,
1901 DeclarationName Entity) {
1902 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1903 "Unresolved overloaded function type");
1904
1905 // C++0x [dcl.ref]p6:
1906 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1907 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1908 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1909 // the type "lvalue reference to T", while an attempt to create the type
1910 // "rvalue reference to cv TR" creates the type TR.
1911 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1912
1913 // C++ [dcl.ref]p4: There shall be no references to references.
1914 //
1915 // According to C++ DR 106, references to references are only
1916 // diagnosed when they are written directly (e.g., "int & &"),
1917 // but not when they happen via a typedef:
1918 //
1919 // typedef int& intref;
1920 // typedef intref& intref2;
1921 //
1922 // Parser::ParseDeclaratorInternal diagnoses the case where
1923 // references are written directly; here, we handle the
1924 // collapsing of references-to-references as described in C++0x.
1925 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1926
1927 // C++ [dcl.ref]p1:
1928 // A declarator that specifies the type "reference to cv void"
1929 // is ill-formed.
1930 if (T->isVoidType()) {
1931 Diag(Loc, diag::err_reference_to_void);
1932 return QualType();
1933 }
1934
1935 if (getLangOpts().HLSL && Loc.isValid()) {
1936 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
1937 return QualType();
1938 }
1939
1940 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1941 return QualType();
1942
1943 if (T->isFunctionType() && getLangOpts().OpenCL &&
1944 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1945 getLangOpts())) {
1946 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
1947 return QualType();
1948 }
1949
1950 // In ARC, it is forbidden to build references to unqualified pointers.
1951 if (getLangOpts().ObjCAutoRefCount)
1952 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1953
1954 if (getLangOpts().OpenCL)
1956
1957 // In WebAssembly, references to reference types and tables are illegal.
1958 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
1959 T.isWebAssemblyReferenceType()) {
1960 Diag(Loc, diag::err_wasm_reference_pr) << 1;
1961 return QualType();
1962 }
1963 if (T->isWebAssemblyTableType()) {
1964 Diag(Loc, diag::err_wasm_table_pr) << 1;
1965 return QualType();
1966 }
1967
1968 // Handle restrict on references.
1969 if (LValueRef)
1970 return Context.getLValueReferenceType(T, SpelledAsLValue);
1971 return Context.getRValueReferenceType(T);
1972}
1973
1975 if (T->isPointerType())
1976 return S.Diag(Loc, diag::err_invalid_pipe_packet_type)
1977 << /*pointer*/ 0 << T;
1978 if (T->isReferenceType())
1979 return S.Diag(Loc, diag::err_invalid_pipe_packet_type)
1980 << /*reference*/ 1 << T;
1981 if (T->isBlockPointerType())
1982 return S.Diag(Loc, diag::err_invalid_pipe_packet_type)
1983 << /*block pointer*/ 2 << T;
1984 if (!T->isObjectType())
1985 return S.Diag(Loc, diag::err_invalid_pipe_packet_type)
1986 << /*non-object*/ 3 << T;
1987 if (!T->isDependentType() && !S.isCompleteType(Loc, T))
1988 return S.Diag(Loc, diag::err_invalid_pipe_packet_type)
1989 << /*incomplete*/ 4 << T;
1990
1991 return false;
1992}
1993
1995 if (checkOpenCLPipePacketType(*this, T, Loc))
1996 return QualType();
1997 return Context.getReadPipeType(T);
1998}
1999
2001 if (checkOpenCLPipePacketType(*this, T, Loc))
2002 return QualType();
2003 return Context.getWritePipeType(T);
2004}
2005
2006QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
2007 SourceLocation Loc) {
2008 if (BitWidth->isInstantiationDependent())
2009 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
2010
2011 llvm::APSInt Bits(32);
2013 BitWidth, &Bits, /*FIXME*/ AllowFoldKind::Allow);
2014
2015 if (ICE.isInvalid())
2016 return QualType();
2017
2018 size_t NumBits = Bits.getZExtValue();
2019 if (!IsUnsigned && NumBits < 2) {
2020 Diag(Loc, diag::err_bit_int_bad_size) << 0;
2021 return QualType();
2022 }
2023
2024 if (IsUnsigned && NumBits < 1) {
2025 Diag(Loc, diag::err_bit_int_bad_size) << 1;
2026 return QualType();
2027 }
2028
2029 const TargetInfo &TI = getASTContext().getTargetInfo();
2030 if (NumBits > TI.getMaxBitIntWidth()) {
2031 Diag(Loc, diag::err_bit_int_max_size)
2032 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2033 return QualType();
2034 }
2035
2036 return Context.getBitIntType(IsUnsigned, NumBits);
2037}
2038
2039/// Check whether the specified array bound can be evaluated using the relevant
2040/// language rules. If so, returns the possibly-converted expression and sets
2041/// SizeVal to the size. If not, but the expression might be a VLA bound,
2042/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2043/// ExprError().
2044static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2045 llvm::APSInt &SizeVal, unsigned VLADiag,
2046 bool VLAIsError) {
2047 if (S.getLangOpts().CPlusPlus14 &&
2048 (VLAIsError ||
2049 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2050 // C++14 [dcl.array]p1:
2051 // The constant-expression shall be a converted constant expression of
2052 // type std::size_t.
2053 //
2054 // Don't apply this rule if we might be forming a VLA: in that case, we
2055 // allow non-constant expressions and constant-folding. We only need to use
2056 // the converted constant expression rules (to properly convert the source)
2057 // when the source expression is of class type.
2059 ArraySize, S.Context.getSizeType(), SizeVal, CCEKind::ArrayBound);
2060 }
2061
2062 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2063 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2064 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2065 public:
2066 unsigned VLADiag;
2067 bool VLAIsError;
2068 bool IsVLA = false;
2069
2070 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2071 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2072
2073 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2074 QualType T) override {
2075 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2076 }
2077
2078 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2079 SourceLocation Loc) override {
2080 IsVLA = !VLAIsError;
2081 return S.Diag(Loc, VLADiag);
2082 }
2083
2084 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2085 SourceLocation Loc) override {
2086 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2087 }
2088 } Diagnoser(VLADiag, VLAIsError);
2089
2090 ExprResult R =
2091 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2092 if (Diagnoser.IsVLA)
2093 return ExprResult();
2094 return R;
2095}
2096
2098 EltTy = Context.getBaseElementType(EltTy);
2099 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2100 EltTy->isUndeducedType())
2101 return true;
2102
2103 CharUnits Size = Context.getTypeSizeInChars(EltTy);
2104 CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2105
2106 if (Size.isMultipleOf(Alignment))
2107 return true;
2108
2109 Diag(Loc, diag::err_array_element_alignment)
2110 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2111 return false;
2112}
2113
2115 const llvm::APSInt &NumElements,
2116 SourceLocation Loc, SourceRange Range) {
2117 unsigned ActiveSizeBits = NumElements.getActiveBits();
2118 if (!ElementType->isDependentType() && !ElementType->isIncompleteType() &&
2119 !ElementType->isUndeducedType() && ElementType->isConstantSizeType())
2120 ActiveSizeBits =
2121 std::max(ActiveSizeBits, ConstantArrayType::getNumAddressingBits(
2122 Context, ElementType, NumElements));
2123 if (ActiveSizeBits <= ConstantArrayType::getMaxSizeBits(Context))
2124 return false;
2125
2126 Diag(Loc, diag::err_array_too_large)
2127 << toString(NumElements, 10, NumElements.isSigned(),
2128 /*formatAsCLiteral=*/false, /*UpperCase=*/false,
2129 /*InsertSeparators=*/true)
2130 << Range;
2131 return true;
2132}
2133
2135 Expr *ArraySize, unsigned Quals,
2136 SourceRange Brackets, DeclarationName Entity) {
2137 // ArrayType stores only the CVR qualifiers; __unaligned and _Atomic are
2138 // dropped.
2139 unsigned IndexTypeQuals = Quals & Qualifiers::CVRMask;
2140
2141 SourceLocation Loc = Brackets.getBegin();
2142 if (getLangOpts().CPlusPlus) {
2143 // C++ [dcl.array]p1:
2144 // T is called the array element type; this type shall not be a reference
2145 // type, the (possibly cv-qualified) type void, a function type or an
2146 // abstract class type.
2147 //
2148 // C++ [dcl.array]p3:
2149 // When several "array of" specifications are adjacent, [...] only the
2150 // first of the constant expressions that specify the bounds of the arrays
2151 // may be omitted.
2152 //
2153 // Note: function types are handled in the common path with C.
2154 if (T->isReferenceType()) {
2155 Diag(Loc, diag::err_illegal_decl_array_of_references)
2156 << getPrintableNameForEntity(Entity) << T;
2157 return QualType();
2158 }
2159
2160 if (T->isVoidType() || T->isIncompleteArrayType()) {
2161 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2162 return QualType();
2163 }
2164
2165 if (RequireNonAbstractType(Brackets.getBegin(), T,
2166 diag::err_array_of_abstract_type))
2167 return QualType();
2168
2169 // Mentioning a member pointer type for an array type causes us to lock in
2170 // an inheritance model, even if it's inside an unused typedef.
2171 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2172 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2173 if (!MPTy->getQualifier().isDependent())
2174 (void)isCompleteType(Loc, T);
2175
2176 } else {
2177 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2178 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2179 if (!T.isWebAssemblyReferenceType() &&
2181 diag::err_array_incomplete_or_sizeless_type))
2182 return QualType();
2183 }
2184
2185 // Multi-dimensional arrays of WebAssembly references are not allowed.
2186 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2187 const auto *ATy = dyn_cast<ArrayType>(T);
2188 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2189 Diag(Loc, diag::err_wasm_reftype_multidimensional_array);
2190 return QualType();
2191 }
2192 }
2193
2194 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2195 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2196 return QualType();
2197 }
2198
2199 if (T->isFunctionType()) {
2200 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2201 << getPrintableNameForEntity(Entity) << T;
2202 return QualType();
2203 }
2204
2205 if (const auto *RD = T->getAsRecordDecl()) {
2206 // If the element type is a struct or union that contains a variadic
2207 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2208 if (RD->hasFlexibleArrayMember())
2209 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2210 } else if (T->isObjCObjectType()) {
2211 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2212 return QualType();
2213 }
2214
2215 if (!checkArrayElementAlignment(T, Loc))
2216 return QualType();
2217
2218 // Do placeholder conversions on the array size expression.
2219 if (ArraySize && ArraySize->hasPlaceholderType()) {
2221 if (Result.isInvalid()) return QualType();
2222 ArraySize = Result.get();
2223 }
2224
2225 // Do lvalue-to-rvalue conversions on the array size expression.
2226 if (ArraySize && !ArraySize->isPRValue()) {
2228 if (Result.isInvalid())
2229 return QualType();
2230
2231 ArraySize = Result.get();
2232 }
2233
2234 // C99 6.7.5.2p1: The size expression shall have integer type.
2235 // C++11 allows contextual conversions to such types.
2236 if (!getLangOpts().CPlusPlus11 &&
2237 ArraySize && !ArraySize->isTypeDependent() &&
2239 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2240 << ArraySize->getType() << ArraySize->getSourceRange();
2241 return QualType();
2242 }
2243
2244 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2245 if (!ArraySize)
2246 return false;
2247
2248 // If the array size expression is a conditional expression whose branches
2249 // are both integer constant expressions, one negative and one positive,
2250 // then it's assumed to be like an old-style static assertion. e.g.,
2251 // int old_style_assert[expr ? 1 : -1];
2252 // We will accept any integer constant expressions instead of assuming the
2253 // values 1 and -1 are always used.
2254 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2255 ArraySize->IgnoreParenImpCasts())) {
2256 std::optional<llvm::APSInt> LHS =
2257 CondExpr->getLHS()->getIntegerConstantExpr(Context);
2258 std::optional<llvm::APSInt> RHS =
2259 CondExpr->getRHS()->getIntegerConstantExpr(Context);
2260 return LHS && RHS && LHS->isNegative() != RHS->isNegative();
2261 }
2262 return false;
2263 };
2264
2265 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2266 unsigned VLADiag;
2267 bool VLAIsError;
2268 if (getLangOpts().OpenCL) {
2269 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2270 VLADiag = diag::err_opencl_vla;
2271 VLAIsError = true;
2272 } else if (getLangOpts().C99) {
2273 VLADiag = diag::warn_vla_used;
2274 VLAIsError = false;
2275 } else if (isSFINAEContext()) {
2276 VLADiag = diag::err_vla_in_sfinae;
2277 VLAIsError = true;
2278 } else if (getLangOpts().OpenMP && OpenMP().isInOpenMPTaskUntiedContext()) {
2279 VLADiag = diag::err_openmp_vla_in_task_untied;
2280 VLAIsError = true;
2281 } else if (getLangOpts().CPlusPlus) {
2282 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context))
2283 VLADiag = getLangOpts().GNUMode
2284 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2285 : diag::ext_vla_cxx_static_assert;
2286 else
2287 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode
2288 : diag::ext_vla_cxx;
2289 VLAIsError = false;
2290 } else {
2291 VLADiag = diag::ext_vla;
2292 VLAIsError = false;
2293 }
2294
2295 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2296 if (!ArraySize) {
2297 if (ASM == ArraySizeModifier::Star) {
2298 Diag(Loc, VLADiag);
2299 if (VLAIsError)
2300 return QualType();
2301
2302 T = Context.getVariableArrayType(T, nullptr, ASM, IndexTypeQuals);
2303 } else {
2304 T = Context.getIncompleteArrayType(T, ASM, IndexTypeQuals);
2305 }
2306 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2307 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, IndexTypeQuals);
2308 } else {
2309 ExprResult R =
2310 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2311 if (R.isInvalid())
2312 return QualType();
2313
2314 if (!R.isUsable()) {
2315 // C99: an array with a non-ICE size is a VLA. We accept any expression
2316 // that we can fold to a non-zero positive value as a non-VLA as an
2317 // extension.
2318 T = Context.getVariableArrayType(T, ArraySize, ASM, IndexTypeQuals);
2319 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2320 !T->isConstantSizeType()) {
2321 // C99: an array with an element type that has a non-constant-size is a
2322 // VLA.
2323 // FIXME: Add a note to explain why this isn't a VLA.
2324 Diag(Loc, VLADiag);
2325 if (VLAIsError)
2326 return QualType();
2327 T = Context.getVariableArrayType(T, ArraySize, ASM, IndexTypeQuals);
2328 } else {
2329 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2330 // have a value greater than zero.
2331 // In C++, this follows from narrowing conversions being disallowed.
2332 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2333 if (Entity)
2334 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2335 << getPrintableNameForEntity(Entity)
2336 << ArraySize->getSourceRange();
2337 else
2338 Diag(ArraySize->getBeginLoc(),
2339 diag::err_typecheck_negative_array_size)
2340 << ArraySize->getSourceRange();
2341 return QualType();
2342 }
2343 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2344 if (getLangOpts().OpenCL) {
2345 Diag(ArraySize->getBeginLoc(), diag::err_typecheck_zero_array_size)
2346 << 3 << ArraySize->getSourceRange();
2347 return QualType();
2348 }
2349
2350 // GCC accepts zero sized static arrays. We allow them when
2351 // we're not in a SFINAE context.
2352 Diag(ArraySize->getBeginLoc(),
2353 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2354 : diag::ext_typecheck_zero_array_size)
2355 << 0 << ArraySize->getSourceRange();
2356 if (isSFINAEContext())
2357 return QualType();
2358 }
2359
2360 if (checkArrayTooLarge(T, ConstVal, ArraySize->getBeginLoc(),
2361 ArraySize->getSourceRange()))
2362 return QualType();
2363
2364 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM,
2365 IndexTypeQuals);
2366 }
2367 }
2368
2369 if (T->isVariableArrayType()) {
2370 if (!Context.getTargetInfo().isVLASupported()) {
2371 // CUDA device code and some other targets don't support VLAs.
2372 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2373 targetDiag(Loc,
2374 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2375 << (IsCUDADevice ? llvm::to_underlying(CUDA().CurrentTarget()) : 0);
2376 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2377 // VLAs are supported on this target, but we may need to do delayed
2378 // checking that the VLA is not being used within a coroutine.
2379 FSI->setHasVLA(Loc);
2380 }
2381 }
2382
2383 // If this is not C99, diagnose array size modifiers on non-VLAs.
2384 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2385 (ASM != ArraySizeModifier::Normal || Quals != 0)) {
2386 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2387 : diag::ext_c99_array_usage)
2388 << ASM;
2389 }
2390
2391 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2392 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2393 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2394 if (getLangOpts().OpenCL) {
2395 const QualType ArrType = Context.getBaseElementType(T);
2396 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2397 ArrType->isSamplerT() || ArrType->isImageType()) {
2398 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2399 return QualType();
2400 }
2401 }
2402
2403 return T;
2404}
2405
2407 const BitIntType *BIT,
2408 bool ForMatrixType = false) {
2409 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2410 unsigned NumBits = BIT->getNumBits();
2411 if (!llvm::isPowerOf2_32(NumBits))
2412 return S.Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2413 << ForMatrixType;
2414 return false;
2415}
2416
2417// A bool vector is stored as an integer with one bit per element and can be
2418// formed from any vector (e.g. by the conditional operator); the size bound
2419// keeps the natural alignment within TypeInfo::Align.
2420static constexpr uint64_t MaxVectorElements = llvm::IntegerType::MAX_INT_BITS;
2421static constexpr uint64_t MaxVectorSizeInBits = 1ULL << 31;
2422
2424 SourceLocation AttrLoc) {
2425 // The base type must be integer (not Boolean or enumeration) or float, and
2426 // can't already be a vector.
2427 if ((!CurType->isDependentType() &&
2428 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2429 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2430 !CurType->isBitIntType()) ||
2431 CurType->isArrayType()) {
2432 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2433 return QualType();
2434 }
2435
2436 if (const auto *BIT = CurType->getAs<BitIntType>();
2437 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2438 return QualType();
2439
2440 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2441 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2443
2444 std::optional<llvm::APSInt> VecSize =
2446 if (!VecSize) {
2447 Diag(AttrLoc, diag::err_attribute_argument_type)
2448 << "vector_size" << AANT_ArgumentIntegerConstant
2449 << SizeExpr->getSourceRange();
2450 return QualType();
2451 }
2452
2453 if (VecSize->isNegative()) {
2454 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2455 return QualType();
2456 }
2457
2458 if (CurType->isDependentType())
2459 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2461
2462 // vecSize is specified in bytes - convert to bits.
2463 if (VecSize->ugt(MaxVectorSizeInBits / 8)) {
2464 Diag(AttrLoc, diag::err_attribute_size_too_large)
2465 << SizeExpr->getSourceRange() << "vector";
2466 return QualType();
2467 }
2468 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2469 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2470
2471 if (VectorSizeBits == 0) {
2472 Diag(AttrLoc, diag::err_attribute_zero_size)
2473 << SizeExpr->getSourceRange() << "vector";
2474 return QualType();
2475 }
2476
2477 if (!TypeSize || VectorSizeBits % TypeSize) {
2478 Diag(AttrLoc, diag::err_attribute_invalid_size)
2479 << SizeExpr->getSourceRange();
2480 return QualType();
2481 }
2482
2483 if (VectorSizeBits / TypeSize > MaxVectorElements) {
2484 Diag(AttrLoc, diag::err_attribute_size_too_large)
2485 << SizeExpr->getSourceRange() << "vector";
2486 return QualType();
2487 }
2488
2489 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2491}
2492
2494 SourceLocation AttrLoc) {
2495 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2496 // in conjunction with complex types (pointers, arrays, functions, etc.).
2497 //
2498 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2499 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2500 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2501 // of bool aren't allowed.
2502 //
2503 // We explicitly allow bool elements in ext_vector_type for C/C++.
2504 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2505 if ((!T->isDependentType() && !T->isIntegerType() &&
2506 !T->isRealFloatingType()) ||
2507 T->isEnumeralType() || (IsNoBoolVecLang && T->isBooleanType())) {
2508 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2509 return QualType();
2510 }
2511
2512 if (const auto *BIT = T->getAs<BitIntType>();
2513 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2514 return QualType();
2515
2516 if (!SizeExpr->isTypeDependent() && !SizeExpr->isValueDependent()) {
2517 std::optional<llvm::APSInt> VecSize =
2519 if (!VecSize) {
2520 Diag(AttrLoc, diag::err_attribute_argument_type)
2521 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2522 << SizeExpr->getSourceRange();
2523 return QualType();
2524 }
2525
2526 if (VecSize->isNegative()) {
2527 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2528 return QualType();
2529 }
2530
2531 // Unlike gcc's vector_size attribute, the size is specified as the
2532 // number of elements, not the number of bytes.
2533 if (VecSize->ugt(MaxVectorElements)) {
2534 Diag(AttrLoc, diag::err_attribute_size_too_large)
2535 << SizeExpr->getSourceRange() << "vector";
2536 return QualType();
2537 }
2538 unsigned VectorSize = static_cast<unsigned>(VecSize->getZExtValue());
2539
2540 if (VectorSize == 0) {
2541 Diag(AttrLoc, diag::err_attribute_zero_size)
2542 << SizeExpr->getSourceRange() << "vector";
2543 return QualType();
2544 }
2545
2546 if (!T->isDependentType() &&
2547 VectorSize * Context.getTypeSize(T) > MaxVectorSizeInBits) {
2548 Diag(AttrLoc, diag::err_attribute_size_too_large)
2549 << SizeExpr->getSourceRange() << "vector";
2550 return QualType();
2551 }
2552
2553 return Context.getExtVectorType(T, VectorSize);
2554 }
2555
2556 return Context.getDependentSizedExtVectorType(T, SizeExpr, AttrLoc);
2557}
2558
2559QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2560 SourceLocation AttrLoc) {
2561 assert(Context.getLangOpts().MatrixTypes &&
2562 "Should never build a matrix type when it is disabled");
2563
2564 // Check element type, if it is not dependent.
2565 if (!ElementTy->isDependentType() &&
2567 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2568 return QualType();
2569 }
2570
2571 if (const auto *BIT = ElementTy->getAs<BitIntType>();
2572 BIT &&
2573 CheckBitIntElementType(*this, AttrLoc, BIT, /*ForMatrixType=*/true))
2574 return QualType();
2575
2576 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2577 NumRows->isValueDependent() || NumCols->isValueDependent())
2578 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2579 AttrLoc);
2580
2581 std::optional<llvm::APSInt> ValueRows =
2583 std::optional<llvm::APSInt> ValueColumns =
2585
2586 auto const RowRange = NumRows->getSourceRange();
2587 auto const ColRange = NumCols->getSourceRange();
2588
2589 // Both are row and column expressions are invalid.
2590 if (!ValueRows && !ValueColumns) {
2591 Diag(AttrLoc, diag::err_attribute_argument_type)
2592 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2593 << ColRange;
2594 return QualType();
2595 }
2596
2597 // Only the row expression is invalid.
2598 if (!ValueRows) {
2599 Diag(AttrLoc, diag::err_attribute_argument_type)
2600 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2601 return QualType();
2602 }
2603
2604 // Only the column expression is invalid.
2605 if (!ValueColumns) {
2606 Diag(AttrLoc, diag::err_attribute_argument_type)
2607 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2608 return QualType();
2609 }
2610
2611 // Check the matrix dimensions.
2612 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2613 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2614 if (MatrixRows == 0 && MatrixColumns == 0) {
2615 Diag(AttrLoc, diag::err_attribute_zero_size)
2616 << "matrix" << RowRange << ColRange;
2617 return QualType();
2618 }
2619 if (MatrixRows == 0) {
2620 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2621 return QualType();
2622 }
2623 if (MatrixColumns == 0) {
2624 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2625 return QualType();
2626 }
2627 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension &&
2628 MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2629 Diag(AttrLoc, diag::err_attribute_size_too_large)
2630 << RowRange << ColRange << "matrix row and column";
2631 return QualType();
2632 }
2633 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension) {
2634 Diag(AttrLoc, diag::err_attribute_size_too_large)
2635 << RowRange << "matrix row";
2636 return QualType();
2637 }
2638 if (MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2639 Diag(AttrLoc, diag::err_attribute_size_too_large)
2640 << ColRange << "matrix column";
2641 return QualType();
2642 }
2643 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2644}
2645
2647 if ((T->isArrayType() && !getLangOpts().allowArrayReturnTypes()) ||
2648 T->isFunctionType()) {
2649 Diag(Loc, diag::err_func_returning_array_function)
2650 << T->isFunctionType() << T;
2651 return true;
2652 }
2653
2654 // Functions cannot return half FP.
2655 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2656 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2657 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2659 return true;
2660 }
2661
2662 // Methods cannot return interface types. All ObjC objects are
2663 // passed by reference.
2664 if (T->isObjCObjectType()) {
2665 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2666 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2667 return true;
2668 }
2669
2670 // __ptrauth is illegal on a function return type.
2671 if (T.getPointerAuth()) {
2672 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
2673 return true;
2674 }
2675
2676 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2677 T.hasNonTrivialToPrimitiveCopyCUnion())
2680
2681 // C++2a [dcl.fct]p12:
2682 // A volatile-qualified return type is deprecated
2683 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2684 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2685
2686 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2687 return true;
2688 return false;
2689}
2690
2691/// Check the extended parameter information. Most of the necessary
2692/// checking should occur when applying the parameter attribute; the
2693/// only other checks required are positional restrictions.
2696 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2697 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2698
2699 bool emittedError = false;
2700 auto actualCC = EPI.ExtInfo.getCC();
2701 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2702 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2703 bool isCompatible =
2704 (required == RequiredCC::OnlySwift)
2705 ? (actualCC == CC_Swift)
2706 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2707 if (isCompatible || emittedError)
2708 return;
2709 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2711 << (required == RequiredCC::OnlySwift);
2712 emittedError = true;
2713 };
2714 for (size_t paramIndex = 0, numParams = paramTypes.size();
2715 paramIndex != numParams; ++paramIndex) {
2716 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2717 // Nothing interesting to check for orindary-ABI parameters.
2721 continue;
2722
2723 // swift_indirect_result parameters must be a prefix of the function
2724 // arguments.
2726 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2727 if (paramIndex != 0 &&
2728 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2730 S.Diag(getParamLoc(paramIndex),
2731 diag::err_swift_indirect_result_not_first);
2732 }
2733 continue;
2734
2736 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2737 continue;
2738
2739 // SwiftAsyncContext is not limited to swiftasynccall functions.
2741 continue;
2742
2743 // swift_error parameters must be preceded by a swift_context parameter.
2745 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2746 if (paramIndex == 0 ||
2747 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2749 S.Diag(getParamLoc(paramIndex),
2750 diag::err_swift_error_result_not_after_swift_context);
2751 }
2752 continue;
2753 }
2754 llvm_unreachable("bad ABI kind");
2755 }
2756}
2757
2759 MutableArrayRef<QualType> ParamTypes,
2760 SourceLocation Loc, DeclarationName Entity,
2762 bool Invalid = false;
2763
2765
2766 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2767 // FIXME: Loc is too inprecise here, should use proper locations for args.
2768 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2769 if (ParamType->isVoidType()) {
2770 Diag(Loc, diag::err_param_with_void_type);
2771 Invalid = true;
2772 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2773 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2774 // Disallow half FP arguments.
2775 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2777 Invalid = true;
2778 } else if (ParamType->isWebAssemblyTableType()) {
2779 Diag(Loc, diag::err_wasm_table_as_function_parameter);
2780 Invalid = true;
2781 } else if (ParamType.getPointerAuth()) {
2782 // __ptrauth is illegal on a function return type.
2783 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 1;
2784 Invalid = true;
2785 }
2786
2787 // C++2a [dcl.fct]p4:
2788 // A parameter with volatile-qualified type is deprecated
2789 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2790 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2791
2792 ParamTypes[Idx] = ParamType;
2793 }
2794
2795 if (EPI.ExtParameterInfos) {
2796 checkExtParameterInfos(*this, ParamTypes, EPI,
2797 [=](unsigned i) { return Loc; });
2798 }
2799
2800 if (EPI.ExtInfo.getProducesResult()) {
2801 // This is just a warning, so we can't fail to build if we see it.
2803 }
2804
2805 if (Invalid)
2806 return QualType();
2807
2808 return Context.getFunctionType(T, ParamTypes, EPI);
2809}
2810
2812 CXXRecordDecl *Cls, SourceLocation Loc,
2813 DeclarationName Entity) {
2814 if (!Cls && !isDependentScopeSpecifier(SS)) {
2815 Cls = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS));
2816 if (!Cls) {
2817 auto D =
2818 Diag(SS.getBeginLoc(), diag::err_illegal_decl_mempointer_in_nonclass)
2819 << SS.getRange();
2820 if (const IdentifierInfo *II = Entity.getAsIdentifierInfo())
2821 D << II;
2822 else
2823 D << "member pointer";
2824 return QualType();
2825 }
2826 }
2827
2828 // Verify that we're not building a pointer to pointer to function with
2829 // exception specification.
2831 Diag(Loc, diag::err_distant_exception_spec);
2832 return QualType();
2833 }
2834
2835 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2836 // with reference type, or "cv void."
2837 if (T->isReferenceType()) {
2838 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2839 << getPrintableNameForEntity(Entity) << T;
2840 return QualType();
2841 }
2842
2843 if (T->isVoidType()) {
2844 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2845 << getPrintableNameForEntity(Entity);
2846 return QualType();
2847 }
2848
2849 if (T->isFunctionType() && getLangOpts().OpenCL &&
2850 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2851 getLangOpts())) {
2852 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2853 return QualType();
2854 }
2855
2856 if (getLangOpts().HLSL && Loc.isValid()) {
2857 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2858 return QualType();
2859 }
2860
2861 // Adjust the default free function calling convention to the default method
2862 // calling convention.
2863 bool IsCtorOrDtor =
2866 if (T->isFunctionType())
2867 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
2868
2869 return Context.getMemberPointerType(T, SS.getScopeRep(), Cls);
2870}
2871
2873 SourceLocation Loc,
2874 DeclarationName Entity) {
2875 if (!T->isFunctionType()) {
2876 Diag(Loc, diag::err_nonfunction_block_type);
2877 return QualType();
2878 }
2879
2880 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2881 return QualType();
2882
2883 if (getLangOpts().OpenCL)
2885
2886 return Context.getBlockPointerType(T);
2887}
2888
2890 QualType QT = Ty.get();
2891 if (QT.isNull()) {
2892 if (TInfo) *TInfo = nullptr;
2893 return QualType();
2894 }
2895
2896 TypeSourceInfo *TSI = nullptr;
2897 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2898 QT = LIT->getType();
2899 TSI = LIT->getTypeSourceInfo();
2900 }
2901
2902 if (TInfo)
2903 *TInfo = TSI;
2904 return QT;
2905}
2906
2907static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2908 Qualifiers::ObjCLifetime ownership,
2909 unsigned chunkIndex);
2910
2911/// Given that this is the declaration of a parameter under ARC,
2912/// attempt to infer attributes and such for pointer-to-whatever
2913/// types.
2914static void inferARCWriteback(TypeProcessingState &state,
2915 QualType &declSpecType) {
2916 Sema &S = state.getSema();
2917 Declarator &declarator = state.getDeclarator();
2918
2919 // TODO: should we care about decl qualifiers?
2920
2921 // Check whether the declarator has the expected form. We walk
2922 // from the inside out in order to make the block logic work.
2923 unsigned outermostPointerIndex = 0;
2924 bool isBlockPointer = false;
2925 unsigned numPointers = 0;
2926 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2927 unsigned chunkIndex = i;
2928 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2929 switch (chunk.Kind) {
2931 // Ignore parens.
2932 break;
2933
2936 // Count the number of pointers. Treat references
2937 // interchangeably as pointers; if they're mis-ordered, normal
2938 // type building will discover that.
2939 outermostPointerIndex = chunkIndex;
2940 numPointers++;
2941 break;
2942
2944 // If we have a pointer to block pointer, that's an acceptable
2945 // indirect reference; anything else is not an application of
2946 // the rules.
2947 if (numPointers != 1) return;
2948 numPointers++;
2949 outermostPointerIndex = chunkIndex;
2950 isBlockPointer = true;
2951
2952 // We don't care about pointer structure in return values here.
2953 goto done;
2954
2955 case DeclaratorChunk::Array: // suppress if written (id[])?
2959 return;
2960 }
2961 }
2962 done:
2963
2964 // If we have *one* pointer, then we want to throw the qualifier on
2965 // the declaration-specifiers, which means that it needs to be a
2966 // retainable object type.
2967 if (numPointers == 1) {
2968 // If it's not a retainable object type, the rule doesn't apply.
2969 if (!declSpecType->isObjCRetainableType()) return;
2970
2971 // If it already has lifetime, don't do anything.
2972 if (declSpecType.getObjCLifetime()) return;
2973
2974 // Otherwise, modify the type in-place.
2975 Qualifiers qs;
2976
2977 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2979 else
2981 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2982
2983 // If we have *two* pointers, then we want to throw the qualifier on
2984 // the outermost pointer.
2985 } else if (numPointers == 2) {
2986 // If we don't have a block pointer, we need to check whether the
2987 // declaration-specifiers gave us something that will turn into a
2988 // retainable object pointer after we slap the first pointer on it.
2989 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2990 return;
2991
2992 // Look for an explicit lifetime attribute there.
2993 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2994 if (chunk.Kind != DeclaratorChunk::Pointer &&
2996 return;
2997 for (const ParsedAttr &AL : chunk.getAttrs())
2998 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2999 return;
3000
3002 outermostPointerIndex);
3003
3004 // Any other number of pointers/references does not trigger the rule.
3005 } else return;
3006
3007 // TODO: mark whether we did this inference?
3008}
3009
3010void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3011 SourceLocation FallbackLoc,
3012 SourceLocation ConstQualLoc,
3013 SourceLocation VolatileQualLoc,
3014 SourceLocation RestrictQualLoc,
3015 SourceLocation AtomicQualLoc,
3016 SourceLocation UnalignedQualLoc) {
3017 if (!Quals)
3018 return;
3019
3020 struct Qual {
3021 const char *Name;
3022 unsigned Mask;
3023 SourceLocation Loc;
3024 } const QualKinds[5] = {
3025 { "const", DeclSpec::TQ_const, ConstQualLoc },
3026 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3027 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3028 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3029 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3030 };
3031
3032 SmallString<32> QualStr;
3033 unsigned NumQuals = 0;
3034 SourceLocation Loc;
3035 FixItHint FixIts[5];
3036
3037 // Build a string naming the redundant qualifiers.
3038 for (auto &E : QualKinds) {
3039 if (Quals & E.Mask) {
3040 if (!QualStr.empty()) QualStr += ' ';
3041 QualStr += E.Name;
3042
3043 // If we have a location for the qualifier, offer a fixit.
3044 SourceLocation QualLoc = E.Loc;
3045 if (QualLoc.isValid()) {
3046 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3047 if (Loc.isInvalid() ||
3048 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
3049 Loc = QualLoc;
3050 }
3051
3052 ++NumQuals;
3053 }
3054 }
3055
3056 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3057 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3058}
3059
3060// Diagnose pointless type qualifiers on the return type of a function.
3062 Declarator &D,
3063 unsigned FunctionChunkIndex) {
3065 D.getTypeObject(FunctionChunkIndex).Fun;
3066 if (FTI.hasTrailingReturnType()) {
3067 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3068 RetTy.getLocalCVRQualifiers(),
3070 return;
3071 }
3072
3073 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3074 End = D.getNumTypeObjects();
3075 OuterChunkIndex != End; ++OuterChunkIndex) {
3076 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3077 switch (OuterChunk.Kind) {
3079 continue;
3080
3082 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3084 diag::warn_qual_return_type,
3085 PTI.TypeQuals,
3087 PTI.ConstQualLoc,
3088 PTI.VolatileQualLoc,
3089 PTI.RestrictQualLoc,
3090 PTI.AtomicQualLoc,
3091 PTI.UnalignedQualLoc);
3092 return;
3093 }
3094
3101 // FIXME: We can't currently provide an accurate source location and a
3102 // fix-it hint for these.
3103 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3104 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3105 RetTy.getCVRQualifiers() | AtomicQual,
3106 D.getIdentifierLoc());
3107 return;
3108 }
3109
3110 llvm_unreachable("unknown declarator chunk kind");
3111 }
3112
3113 // If the qualifiers come from a conversion function type, don't diagnose
3114 // them -- they're not necessarily redundant, since such a conversion
3115 // operator can be explicitly called as "x.operator const int()".
3117 return;
3118
3119 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3120 // which are present there.
3121 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3123 D.getIdentifierLoc(),
3129}
3130
3131static std::pair<QualType, TypeSourceInfo *>
3132InventTemplateParameter(TypeProcessingState &state, QualType T,
3133 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3135 Sema &S = state.getSema();
3136 Declarator &D = state.getDeclarator();
3137
3138 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3139 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3140 const bool IsParameterPack = D.hasEllipsis();
3141
3142 // If auto is mentioned in a lambda parameter or abbreviated function
3143 // template context, convert it to a template parameter type.
3144
3145 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3146 // template parameter type. Template parameters are temporarily added
3147 // to the TU until the associated TemplateDecl is created.
3148 TemplateTypeParmDecl *InventedTemplateParam = TemplateTypeParmDecl::Create(
3150 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3151 /*NameLoc=*/D.getIdentifierLoc(), TemplateParameterDepth,
3152 AutoParameterPosition,
3154 AutoParameterPosition),
3155 false, IsParameterPack,
3156 /*HasTypeConstraint=*/Auto->isConstrained());
3157 InventedTemplateParam->setImplicit();
3158 Info.TemplateParams.push_back(InventedTemplateParam);
3159
3160 // Attach type constraints to the new parameter.
3161 if (Auto->isConstrained()) {
3162 if (TrailingTSI) {
3163 // The 'auto' appears in a trailing return type we've already built;
3164 // extract its type constraints to attach to the template parameter.
3165 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3166 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3167 bool Invalid = false;
3168 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3169 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3172 Invalid = true;
3173 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3174 }
3175
3176 if (!Invalid) {
3178 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3179 AutoLoc.getNamedConcept(),
3180 /*FoundDecl=*/AutoLoc.getFoundDecl(),
3181 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3182 InventedTemplateParam, D.getEllipsisLoc());
3183 }
3184 } else {
3185 // The 'auto' appears in the decl-specifiers; we've not finished forming
3186 // TypeSourceInfo for it yet.
3188 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
3189 TemplateId->RAngleLoc);
3190 bool Invalid = false;
3191 if (TemplateId->LAngleLoc.isValid()) {
3192 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3193 TemplateId->NumArgs);
3194 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3195
3196 if (D.getEllipsisLoc().isInvalid()) {
3197 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3200 Invalid = true;
3201 break;
3202 }
3203 }
3204 }
3205 }
3206 if (!Invalid) {
3207 TemplateName TN = TemplateId->Template.get();
3213 TemplateId->TemplateNameLoc),
3214 TN,
3215 /*FoundDecl=*/
3216 USD ? cast<NamedDecl>(USD) : cast_if_present<NamedDecl>(CD),
3217 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3218 InventedTemplateParam, D.getEllipsisLoc());
3219 }
3220 }
3221 }
3222
3223 // Replace the 'auto' in the function parameter with this invented
3224 // template type parameter.
3225 // FIXME: Retain some type sugar to indicate that this was written
3226 // as 'auto'?
3227 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3228 QualType NewT = state.ReplaceAutoType(T, Replacement);
3229 TypeSourceInfo *NewTSI =
3230 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3231 : nullptr;
3232 return {NewT, NewTSI};
3233}
3234
3235static TypeSourceInfo *
3236GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3237 QualType T, TypeSourceInfo *ReturnTypeInfo);
3238
3239static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3240 TypeSourceInfo *&ReturnTypeInfo) {
3241 Sema &SemaRef = state.getSema();
3242 Declarator &D = state.getDeclarator();
3243 QualType T;
3244 ReturnTypeInfo = nullptr;
3245
3246 // The TagDecl owned by the DeclSpec.
3247 TagDecl *OwnedTagDecl = nullptr;
3248
3249 switch (D.getName().getKind()) {
3255 T = ConvertDeclSpecToType(state);
3256
3257 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3258 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3259 // Owned declaration is embedded in declarator.
3260 OwnedTagDecl->setEmbeddedInDeclarator(true);
3261 }
3262 break;
3263
3267 // Constructors and destructors don't have return types. Use
3268 // "void" instead.
3269 T = SemaRef.Context.VoidTy;
3272 break;
3273
3275 // Deduction guides have a trailing return type and no type in their
3276 // decl-specifier sequence. Use a placeholder return type for now.
3277 T = SemaRef.Context.DependentTy;
3278 break;
3279
3281 // The result type of a conversion function is the type that it
3282 // converts to.
3284 &ReturnTypeInfo);
3285 break;
3286 }
3287
3288 // Note: We don't need to distribute declaration attributes (i.e.
3289 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3290 // and those don't get distributed.
3292 state, T, SemaRef.CUDA().IdentifyTarget(D.getAttributes()));
3293
3294 // Find the deduced type in this type. Look in the trailing return type if we
3295 // have one, otherwise in the DeclSpec type.
3296 // FIXME: The standard wording doesn't currently describe this.
3297 DeducedType *Deduced = T->getContainedDeducedType();
3298 bool DeducedIsTrailingReturnType = false;
3301 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3302 DeducedIsTrailingReturnType = true;
3303 }
3304
3305 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3306 if (Deduced) {
3307 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3308 int Error = -1;
3309
3310 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3311 // class template argument deduction)?
3312 bool IsCXXAutoType =
3313 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3314 bool IsDeducedReturnType = false;
3315
3316 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3318 AutoRange = D.getName().getSourceRange();
3319
3320 switch (D.getContext()) {
3322 // Declared return type of a lambda-declarator is implicit and is always
3323 // 'auto'.
3324 break;
3327 Error = 0;
3328 break;
3330 Error = 22;
3331 break;
3334 InventedTemplateParameterInfo *Info = nullptr;
3336 // With concepts we allow 'auto' in function parameters.
3337 if (!SemaRef.getLangOpts().CPlusPlus || !Auto ||
3338 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3339 Error = 0;
3340 break;
3341 }
3342
3343 if (!SemaRef.getLangOpts().CPlusPlus20)
3344 SemaRef.DiagCompat(AutoRange.getBegin(), diag_compat::auto_param);
3345
3346 if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3347 Error = 21;
3348 break;
3349 }
3350
3351 Info = &SemaRef.InventedParameterInfos.back();
3352 } else {
3353 // In C++14, generic lambdas allow 'auto' in their parameters.
3354 if (!SemaRef.getLangOpts().CPlusPlus14 && Auto &&
3355 Auto->getKeyword() == AutoTypeKeyword::Auto) {
3356 Error = 25; // auto not allowed in lambda parameter (before C++14)
3357 break;
3358 } else if (!Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) {
3359 Error = 16; // __auto_type or decltype(auto) not allowed in lambda
3360 // parameter
3361 break;
3362 }
3363 Info = SemaRef.getCurLambda();
3364 assert(Info && "No LambdaScopeInfo on the stack!");
3365 }
3366
3367 // We'll deal with inventing template parameters for 'auto' in trailing
3368 // return types when we pick up the trailing return type when processing
3369 // the function chunk.
3370 if (!DeducedIsTrailingReturnType)
3371 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3372 break;
3373 }
3375 if (D.isStaticMember() || D.isFunctionDeclarator())
3376 break;
3377 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3378 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3379 Error = 6; // Interface member.
3380 } else {
3381 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3382 case TagTypeKind::Enum:
3383 llvm_unreachable("unhandled tag kind");
3385 Error = Cxx ? 1 : 2; /* Struct member */
3386 break;
3387 case TagTypeKind::Union:
3388 Error = Cxx ? 3 : 4; /* Union member */
3389 break;
3390 case TagTypeKind::Class:
3391 Error = 5; /* Class member */
3392 break;
3394 Error = 6; /* Interface member */
3395 break;
3396 }
3397 }
3399 Error = 20; // Friend type
3400 break;
3401 }
3404 Error = 7; // Exception declaration
3405 break;
3408 !SemaRef.getLangOpts().CPlusPlus20)
3409 Error = 19; // Template parameter (until C++20)
3410 else if (!SemaRef.getLangOpts().CPlusPlus17)
3411 Error = 8; // Template parameter (until C++17)
3412 break;
3414 Error = 9; // Block literal
3415 break;
3417 // Within a template argument list, a deduced template specialization
3418 // type will be reinterpreted as a template template argument.
3420 !D.getNumTypeObjects() &&
3422 break;
3423 [[fallthrough]];
3425 Error = 10; // Template type argument
3426 break;
3429 Error = 12; // Type alias
3430 break;
3433 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3434 Error = 13; // Function return type
3435 IsDeducedReturnType = true;
3436 break;
3438 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3439 Error = 14; // conversion-type-id
3440 IsDeducedReturnType = true;
3441 break;
3444 break;
3445 if (IsCXXAutoType && !Auto->isDecltypeAuto())
3446 break; // auto(x)
3447 [[fallthrough]];
3450 Error = 15; // Generic
3451 break;
3457 // FIXME: P0091R3 (erroneously) does not permit class template argument
3458 // deduction in conditions, for-init-statements, and other declarations
3459 // that are not simple-declarations.
3460 break;
3462 // FIXME: P0091R3 does not permit class template argument deduction here,
3463 // but we follow GCC and allow it anyway.
3464 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3465 Error = 17; // 'new' type
3466 break;
3468 Error = 18; // K&R function parameter
3469 break;
3470 }
3471
3473 Error = 11;
3474
3475 // In Objective-C it is an error to use 'auto' on a function declarator
3476 // (and everywhere for '__auto_type').
3477 if (D.isFunctionDeclarator() &&
3478 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3479 Error = 13;
3480
3481 if (Error != -1) {
3482 unsigned Kind;
3483 if (Auto) {
3484 switch (Auto->getKeyword()) {
3485 case AutoTypeKeyword::Auto: Kind = 0; break;
3486 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3487 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3488 }
3489 } else {
3491 "unknown auto type");
3492 Kind = 3;
3493 }
3494
3495 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3496 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3497
3498 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3499 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3500 << QualType(Deduced, 0) << AutoRange;
3501 if (auto *TD = TN.getAsTemplateDecl())
3502 SemaRef.NoteTemplateLocation(*TD);
3503
3504 T = SemaRef.Context.IntTy;
3505 D.setInvalidType(true);
3506 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3507 // If there was a trailing return type, we already got
3508 // warn_cxx98_compat_trailing_return_type in the parser.
3509 // If there was a decltype(auto), we already got
3510 // warn_cxx11_compat_decltype_auto_type_specifier.
3511 unsigned DiagId = 0;
3513 DiagId = diag::warn_cxx11_compat_generic_lambda;
3514 else if (IsDeducedReturnType)
3515 DiagId = diag::warn_cxx11_compat_deduced_return_type;
3516 else if (Auto->getKeyword() == AutoTypeKeyword::Auto)
3517 DiagId = diag::warn_cxx98_compat_auto_type_specifier;
3518
3519 if (DiagId)
3520 SemaRef.Diag(AutoRange.getBegin(), DiagId) << AutoRange;
3521 }
3522 }
3523
3524 if (SemaRef.getLangOpts().CPlusPlus &&
3525 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3526 // Check the contexts where C++ forbids the declaration of a new class
3527 // or enumeration in a type-specifier-seq.
3528 unsigned DiagID = 0;
3529 switch (D.getContext()) {
3532 // Class and enumeration definitions are syntactically not allowed in
3533 // trailing return types.
3534 llvm_unreachable("parser should not have allowed this");
3535 break;
3543 // C++11 [dcl.type]p3:
3544 // A type-specifier-seq shall not define a class or enumeration unless
3545 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3546 // the declaration of a template-declaration.
3548 break;
3550 DiagID = diag::err_type_defined_in_alias_template;
3551 break;
3562 DiagID = diag::err_type_defined_in_type_specifier;
3563 break;
3570 // C++ [dcl.fct]p6:
3571 // Types shall not be defined in return or parameter types.
3572 DiagID = diag::err_type_defined_in_param_type;
3573 break;
3575 // C++ 6.4p2:
3576 // The type-specifier-seq shall not contain typedef and shall not declare
3577 // a new class or enumeration.
3578 DiagID = diag::err_type_defined_in_condition;
3579 break;
3580 }
3581
3582 if (DiagID != 0) {
3583 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3584 << SemaRef.Context.getCanonicalTagType(OwnedTagDecl);
3585 D.setInvalidType(true);
3586 }
3587 }
3588
3589 assert(!T.isNull() && "This function should not return a null type");
3590 return T;
3591}
3592
3593/// Produce an appropriate diagnostic for an ambiguity between a function
3594/// declarator and a C++ direct-initializer.
3596 DeclaratorChunk &DeclType, QualType RT) {
3597 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3598 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3599
3600 // If the return type is void there is no ambiguity.
3601 if (RT->isVoidType())
3602 return;
3603
3604 // An initializer for a non-class type can have at most one argument.
3605 if (!RT->isRecordType() && FTI.NumParams > 1)
3606 return;
3607
3608 // An initializer for a reference must have exactly one argument.
3609 if (RT->isReferenceType() && FTI.NumParams != 1)
3610 return;
3611
3612 // Only warn if this declarator is declaring a function at block scope, and
3613 // doesn't have a storage class (such as 'extern') specified.
3614 if (!D.isFunctionDeclarator() ||
3618 return;
3619
3620 // Inside a condition, a direct initializer is not permitted. We allow one to
3621 // be parsed in order to give better diagnostics in condition parsing.
3623 return;
3624
3625 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3626
3627 S.Diag(DeclType.Loc,
3628 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3629 : diag::warn_empty_parens_are_function_decl)
3630 << ParenRange;
3631
3632 // If the declaration looks like:
3633 // T var1,
3634 // f();
3635 // and name lookup finds a function named 'f', then the ',' was
3636 // probably intended to be a ';'.
3637 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3638 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3640 if (Comma.getFileID() != Name.getFileID() ||
3641 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3644 if (S.LookupName(Result, S.getCurScope()))
3645 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3647 << D.getIdentifier();
3648 Result.suppressDiagnostics();
3649 }
3650 }
3651
3652 if (FTI.NumParams > 0) {
3653 // For a declaration with parameters, eg. "T var(T());", suggest adding
3654 // parens around the first parameter to turn the declaration into a
3655 // variable declaration.
3656 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3657 SourceLocation B = Range.getBegin();
3658 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3659 // FIXME: Maybe we should suggest adding braces instead of parens
3660 // in C++11 for classes that don't have an initializer_list constructor.
3661 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3663 << FixItHint::CreateInsertion(E, ")");
3664 } else {
3665 // For a declaration without parameters, eg. "T var();", suggest replacing
3666 // the parens with an initializer to turn the declaration into a variable
3667 // declaration.
3668 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3669
3670 // Empty parens mean value-initialization, and no parens mean
3671 // default initialization. These are equivalent if the default
3672 // constructor is user-provided or if zero-initialization is a
3673 // no-op.
3674 if (RD && RD->hasDefinition() &&
3676 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3677 << FixItHint::CreateRemoval(ParenRange);
3678 else {
3679 std::string Init =
3680 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3681 if (Init.empty() && S.LangOpts.CPlusPlus11)
3682 Init = "{}";
3683 if (!Init.empty())
3684 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3685 << FixItHint::CreateReplacement(ParenRange, Init);
3686 }
3687 }
3688}
3689
3690/// Produce an appropriate diagnostic for a declarator with top-level
3691/// parentheses.
3694 assert(Paren.Kind == DeclaratorChunk::Paren &&
3695 "do not have redundant top-level parentheses");
3696
3697 // This is a syntactic check; we're not interested in cases that arise
3698 // during template instantiation.
3700 return;
3701
3702 // Check whether this could be intended to be a construction of a temporary
3703 // object in C++ via a function-style cast.
3704 bool CouldBeTemporaryObject =
3705 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3706 !D.isInvalidType() && D.getIdentifier() &&
3708 (T->isRecordType() || T->isDependentType()) &&
3710
3711 bool StartsWithDeclaratorId = true;
3712 for (auto &C : D.type_objects()) {
3713 switch (C.Kind) {
3715 if (&C == &Paren)
3716 continue;
3717 [[fallthrough]];
3719 StartsWithDeclaratorId = false;
3720 continue;
3721
3723 if (!C.Arr.NumElts)
3724 CouldBeTemporaryObject = false;
3725 continue;
3726
3728 // FIXME: Suppress the warning here if there is no initializer; we're
3729 // going to give an error anyway.
3730 // We assume that something like 'T (&x) = y;' is highly likely to not
3731 // be intended to be a temporary object.
3732 CouldBeTemporaryObject = false;
3733 StartsWithDeclaratorId = false;
3734 continue;
3735
3737 // In a new-type-id, function chunks require parentheses.
3739 return;
3740 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3741 // redundant-parens warning, but we don't know whether the function
3742 // chunk was syntactically valid as an expression here.
3743 CouldBeTemporaryObject = false;
3744 continue;
3745
3749 // These cannot appear in expressions.
3750 CouldBeTemporaryObject = false;
3751 StartsWithDeclaratorId = false;
3752 continue;
3753 }
3754 }
3755
3756 // FIXME: If there is an initializer, assume that this is not intended to be
3757 // a construction of a temporary object.
3758
3759 // Check whether the name has already been declared; if not, this is not a
3760 // function-style cast.
3761 if (CouldBeTemporaryObject) {
3764 if (!S.LookupName(Result, S.getCurScope()))
3765 CouldBeTemporaryObject = false;
3766 Result.suppressDiagnostics();
3767 }
3768
3769 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3770
3771 if (!CouldBeTemporaryObject) {
3772 // If we have A (::B), the parentheses affect the meaning of the program.
3773 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3774 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3775 // formally unambiguous.
3776 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3778 for (;;) {
3779 switch (NNS.getKind()) {
3781 return;
3783 NNS = NNS.getAsType()->getPrefix();
3784 continue;
3786 NNS = NNS.getAsNamespaceAndPrefix().Prefix;
3787 continue;
3788 default:
3789 goto out;
3790 }
3791 }
3792 out:;
3793 }
3794
3795 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3796 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3798 return;
3799 }
3800
3801 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3802 << ParenRange << D.getIdentifier();
3803 auto *RD = T->getAsCXXRecordDecl();
3804 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3805 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3806 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3807 << D.getIdentifier();
3808 // FIXME: A cast to void is probably a better suggestion in cases where it's
3809 // valid (when there is no initializer and we're not in a condition).
3810 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3813 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3816}
3817
3818/// Helper for figuring out the default CC for a function declarator type. If
3819/// this is the outermost chunk, then we can determine the CC from the
3820/// declarator context. If not, then this could be either a member function
3821/// type or normal function type.
3823 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3824 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3825 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3826
3827 // Check for an explicit CC attribute.
3828 for (const ParsedAttr &AL : AttrList) {
3829 switch (AL.getKind()) {
3831 // Ignore attributes that don't validate or can't apply to the
3832 // function type. We'll diagnose the failure to apply them in
3833 // handleFunctionTypeAttr.
3834 CallingConv CC;
3835 if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr,
3836 S.CUDA().IdentifyTarget(D.getAttributes())) &&
3837 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3838 return CC;
3839 }
3840 break;
3841 }
3842
3843 default:
3844 break;
3845 }
3846 }
3847
3848 bool IsCXXInstanceMethod = false;
3849
3850 if (S.getLangOpts().CPlusPlus) {
3851 // Look inwards through parentheses to see if this chunk will form a
3852 // member pointer type or if we're the declarator. Any type attributes
3853 // between here and there will override the CC we choose here.
3854 unsigned I = ChunkIndex;
3855 bool FoundNonParen = false;
3856 while (I && !FoundNonParen) {
3857 --I;
3859 FoundNonParen = true;
3860 }
3861
3862 if (FoundNonParen) {
3863 // If we're not the declarator, we're a regular function type unless we're
3864 // in a member pointer.
3865 IsCXXInstanceMethod =
3867 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3868 // This can only be a call operator for a lambda, which is an instance
3869 // method, unless explicitly specified as 'static'.
3870 IsCXXInstanceMethod =
3872 } else {
3873 // We're the innermost decl chunk, so must be a function declarator.
3874 assert(D.isFunctionDeclarator());
3875
3876 // If we're inside a record, we're declaring a method, but it could be
3877 // explicitly or implicitly static.
3878 IsCXXInstanceMethod =
3881 !D.isStaticMember();
3882 }
3883 }
3884
3886 IsCXXInstanceMethod);
3887
3888 if (S.getLangOpts().CUDA) {
3889 // If we're compiling CUDA/HIP code and targeting HIPSPV we need to make
3890 // sure the kernels will be marked with the right calling convention so that
3891 // they will be visible by the APIs that ingest SPIR-V. We do not do this
3892 // when targeting AMDGCNSPIRV, as it does not rely on OpenCL.
3893 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
3894 if (Triple.isSPIRV() && Triple.getVendor() != llvm::Triple::AMD) {
3895 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3896 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
3897 CC = CC_DeviceKernel;
3898 break;
3899 }
3900 }
3901 }
3902 }
3903
3904 for (const ParsedAttr &AL : llvm::concat<ParsedAttr>(
3907 if (AL.getKind() == ParsedAttr::AT_DeviceKernel) {
3908 CC = CC_DeviceKernel;
3909 break;
3910 }
3911 }
3912 return CC;
3913}
3914
3915namespace {
3916 /// A simple notion of pointer kinds, which matches up with the various
3917 /// pointer declarators.
3918 enum class SimplePointerKind {
3919 Pointer,
3920 BlockPointer,
3921 MemberPointer,
3922 Array,
3923 };
3924} // end anonymous namespace
3925
3927 switch (nullability) {
3929 if (!Ident__Nonnull)
3930 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3931 return Ident__Nonnull;
3932
3934 if (!Ident__Nullable)
3935 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3936 return Ident__Nullable;
3937
3939 if (!Ident__Nullable_result)
3940 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
3941 return Ident__Nullable_result;
3942
3944 if (!Ident__Null_unspecified)
3945 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3946 return Ident__Null_unspecified;
3947 }
3948 llvm_unreachable("Unknown nullability kind.");
3949}
3950
3951/// Check whether there is a nullability attribute of any kind in the given
3952/// attribute list.
3953static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3954 for (const ParsedAttr &AL : attrs) {
3955 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3956 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3957 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
3958 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3959 return true;
3960 }
3961
3962 return false;
3963}
3964
3965namespace {
3966 /// Describes the kind of a pointer a declarator describes.
3967 enum class PointerDeclaratorKind {
3968 // Not a pointer.
3969 NonPointer,
3970 // Single-level pointer.
3971 SingleLevelPointer,
3972 // Multi-level pointer (of any pointer kind).
3974 // CFFooRef*
3975 MaybePointerToCFRef,
3976 // CFErrorRef*
3977 CFErrorRefPointer,
3978 // NSError**
3979 NSErrorPointerPointer,
3980 };
3981
3982 /// Describes a declarator chunk wrapping a pointer that marks inference as
3983 /// unexpected.
3984 // These values must be kept in sync with diagnostics.
3985 enum class PointerWrappingDeclaratorKind {
3986 /// Pointer is top-level.
3987 None = -1,
3988 /// Pointer is an array element.
3989 Array = 0,
3990 /// Pointer is the referent type of a C++ reference.
3991 Reference = 1
3992 };
3993} // end anonymous namespace
3994
3995/// Classify the given declarator, whose type-specified is \c type, based on
3996/// what kind of pointer it refers to.
3997///
3998/// This is used to determine the default nullability.
3999static PointerDeclaratorKind
4001 PointerWrappingDeclaratorKind &wrappingKind) {
4002 unsigned numNormalPointers = 0;
4003
4004 // For any dependent type, we consider it a non-pointer.
4005 if (type->isDependentType())
4006 return PointerDeclaratorKind::NonPointer;
4007
4008 // Look through the declarator chunks to identify pointers.
4009 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
4010 DeclaratorChunk &chunk = declarator.getTypeObject(i);
4011 switch (chunk.Kind) {
4013 if (numNormalPointers == 0)
4014 wrappingKind = PointerWrappingDeclaratorKind::Array;
4015 break;
4016
4019 break;
4020
4023 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4024 : PointerDeclaratorKind::SingleLevelPointer;
4025
4027 break;
4028
4030 if (numNormalPointers == 0)
4031 wrappingKind = PointerWrappingDeclaratorKind::Reference;
4032 break;
4033
4035 ++numNormalPointers;
4036 if (numNormalPointers > 2)
4037 return PointerDeclaratorKind::MultiLevelPointer;
4038 break;
4039 }
4040 }
4041
4042 // Then, dig into the type specifier itself.
4043 unsigned numTypeSpecifierPointers = 0;
4044 do {
4045 // Decompose normal pointers.
4046 if (auto ptrType = type->getAs<PointerType>()) {
4047 ++numNormalPointers;
4048
4049 if (numNormalPointers > 2)
4050 return PointerDeclaratorKind::MultiLevelPointer;
4051
4052 type = ptrType->getPointeeType();
4053 ++numTypeSpecifierPointers;
4054 continue;
4055 }
4056
4057 // Decompose block pointers.
4058 if (type->getAs<BlockPointerType>()) {
4059 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4060 : PointerDeclaratorKind::SingleLevelPointer;
4061 }
4062
4063 // Decompose member pointers.
4064 if (type->getAs<MemberPointerType>()) {
4065 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4066 : PointerDeclaratorKind::SingleLevelPointer;
4067 }
4068
4069 // Look at Objective-C object pointers.
4070 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4071 ++numNormalPointers;
4072 ++numTypeSpecifierPointers;
4073
4074 // If this is NSError**, report that.
4075 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4076 if (objcClassDecl->getIdentifier() == S.ObjC().getNSErrorIdent() &&
4077 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4078 return PointerDeclaratorKind::NSErrorPointerPointer;
4079 }
4080 }
4081
4082 break;
4083 }
4084
4085 // Look at Objective-C class types.
4086 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4087 if (objcClass->getInterface()->getIdentifier() ==
4088 S.ObjC().getNSErrorIdent()) {
4089 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4090 return PointerDeclaratorKind::NSErrorPointerPointer;
4091 }
4092
4093 break;
4094 }
4095
4096 // If at this point we haven't seen a pointer, we won't see one.
4097 if (numNormalPointers == 0)
4098 return PointerDeclaratorKind::NonPointer;
4099
4100 if (auto *recordDecl = type->getAsRecordDecl()) {
4101 // If this is CFErrorRef*, report it as such.
4102 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4103 S.ObjC().isCFError(recordDecl)) {
4104 return PointerDeclaratorKind::CFErrorRefPointer;
4105 }
4106 break;
4107 }
4108
4109 break;
4110 } while (true);
4111
4112 switch (numNormalPointers) {
4113 case 0:
4114 return PointerDeclaratorKind::NonPointer;
4115
4116 case 1:
4117 return PointerDeclaratorKind::SingleLevelPointer;
4118
4119 case 2:
4120 return PointerDeclaratorKind::MaybePointerToCFRef;
4121
4122 default:
4123 return PointerDeclaratorKind::MultiLevelPointer;
4124 }
4125}
4126
4128 SourceLocation loc) {
4129 // If we're anywhere in a function, method, or closure context, don't perform
4130 // completeness checks.
4131 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4132 if (ctx->isFunctionOrMethod())
4133 return FileID();
4134
4135 if (ctx->isFileContext())
4136 break;
4137 }
4138
4139 // We only care about the expansion location.
4140 loc = S.SourceMgr.getExpansionLoc(loc);
4141 FileID file = S.SourceMgr.getFileID(loc);
4142 if (file.isInvalid())
4143 return FileID();
4144
4145 // Retrieve file information.
4146 bool invalid = false;
4147 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4148 if (invalid || !sloc.isFile())
4149 return FileID();
4150
4151 // We don't want to perform completeness checks on the main file or in
4152 // system headers.
4153 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4154 if (fileInfo.getIncludeLoc().isInvalid())
4155 return FileID();
4156 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4158 return FileID();
4159 }
4160
4161 return file;
4162}
4163
4164/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4165/// taking into account whitespace before and after.
4166template <typename DiagBuilderT>
4167static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4168 SourceLocation PointerLoc,
4169 NullabilityKind Nullability) {
4170 assert(PointerLoc.isValid());
4171 if (PointerLoc.isMacroID())
4172 return;
4173
4174 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4175 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4176 return;
4177
4178 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4179 if (!NextChar)
4180 return;
4181
4182 SmallString<32> InsertionTextBuf{" "};
4183 InsertionTextBuf += getNullabilitySpelling(Nullability);
4184 InsertionTextBuf += " ";
4185 StringRef InsertionText = InsertionTextBuf.str();
4186
4187 if (isWhitespace(*NextChar)) {
4188 InsertionText = InsertionText.drop_back();
4189 } else if (NextChar[-1] == '[') {
4190 if (NextChar[0] == ']')
4191 InsertionText = InsertionText.drop_back().drop_front();
4192 else
4193 InsertionText = InsertionText.drop_front();
4194 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4195 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4196 InsertionText = InsertionText.drop_back().drop_front();
4197 }
4198
4199 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4200}
4201
4203 SimplePointerKind PointerKind,
4204 SourceLocation PointerLoc,
4205 SourceLocation PointerEndLoc) {
4206 assert(PointerLoc.isValid());
4207
4208 if (PointerKind == SimplePointerKind::Array) {
4209 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4210 } else {
4211 S.Diag(PointerLoc, diag::warn_nullability_missing)
4212 << static_cast<unsigned>(PointerKind);
4213 }
4214
4215 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4216 if (FixItLoc.isMacroID())
4217 return;
4218
4219 auto addFixIt = [&](NullabilityKind Nullability) {
4220 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4221 Diag << static_cast<unsigned>(Nullability);
4222 Diag << static_cast<unsigned>(PointerKind);
4223 fixItNullability(S, Diag, FixItLoc, Nullability);
4224 };
4225 addFixIt(NullabilityKind::Nullable);
4226 addFixIt(NullabilityKind::NonNull);
4227}
4228
4229/// Complains about missing nullability if the file containing \p pointerLoc
4230/// has other uses of nullability (either the keywords or the \c assume_nonnull
4231/// pragma).
4232///
4233/// If the file has \e not seen other uses of nullability, this particular
4234/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4235static void
4236checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4237 SourceLocation pointerLoc,
4238 SourceLocation pointerEndLoc = SourceLocation()) {
4239 // Determine which file we're performing consistency checking for.
4240 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4241 if (file.isInvalid())
4242 return;
4243
4244 // If we haven't seen any type nullability in this file, we won't warn now
4245 // about anything.
4246 FileNullability &fileNullability = S.NullabilityMap[file];
4247 if (!fileNullability.SawTypeNullability) {
4248 // If this is the first pointer declarator in the file, and the appropriate
4249 // warning is on, record it in case we need to diagnose it retroactively.
4250 diag::kind diagKind;
4251 if (pointerKind == SimplePointerKind::Array)
4252 diagKind = diag::warn_nullability_missing_array;
4253 else
4254 diagKind = diag::warn_nullability_missing;
4255
4256 if (fileNullability.PointerLoc.isInvalid() &&
4257 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4258 fileNullability.PointerLoc = pointerLoc;
4259 fileNullability.PointerEndLoc = pointerEndLoc;
4260 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4261 }
4262
4263 return;
4264 }
4265
4266 // Complain about missing nullability.
4267 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4268}
4269
4270/// Marks that a nullability feature has been used in the file containing
4271/// \p loc.
4272///
4273/// If this file already had pointer types in it that were missing nullability,
4274/// the first such instance is retroactively diagnosed.
4275///
4276/// \sa checkNullabilityConsistency
4279 if (file.isInvalid())
4280 return;
4281
4282 FileNullability &fileNullability = S.NullabilityMap[file];
4283 if (fileNullability.SawTypeNullability)
4284 return;
4285 fileNullability.SawTypeNullability = true;
4286
4287 // If we haven't seen any type nullability before, now we have. Retroactively
4288 // diagnose the first unannotated pointer, if there was one.
4289 if (fileNullability.PointerLoc.isInvalid())
4290 return;
4291
4292 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4294 fileNullability.PointerEndLoc);
4295}
4296
4297/// Returns true if any of the declarator chunks before \p endIndex include a
4298/// level of indirection: array, pointer, reference, or pointer-to-member.
4299///
4300/// Because declarator chunks are stored in outer-to-inner order, testing
4301/// every chunk before \p endIndex is testing all chunks that embed the current
4302/// chunk as part of their type.
4303///
4304/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4305/// end index, in which case all chunks are tested.
4306static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4307 unsigned i = endIndex;
4308 while (i != 0) {
4309 // Walk outwards along the declarator chunks.
4310 --i;
4311 const DeclaratorChunk &DC = D.getTypeObject(i);
4312 switch (DC.Kind) {
4314 break;
4319 return true;
4323 // These are invalid anyway, so just ignore.
4324 break;
4325 }
4326 }
4327 return false;
4328}
4329
4330static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4331 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4332 Chunk.Kind == DeclaratorChunk::Array);
4333}
4334
4335template<typename AttrT>
4336static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4337 AL.setUsedAsTypeAttr();
4338 return ::new (Ctx) AttrT(Ctx, AL);
4339}
4340
4342 NullabilityKind NK) {
4343 switch (NK) {
4346
4349
4352
4355 }
4356 llvm_unreachable("unknown NullabilityKind");
4357}
4358
4359// Diagnose whether this is a case with the multiple addr spaces.
4360// Returns true if this is an invalid case.
4361// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4362// by qualifiers for two or more different address spaces."
4364 LangAS ASNew,
4365 SourceLocation AttrLoc) {
4366 if (ASOld != LangAS::Default) {
4367 if (ASOld != ASNew) {
4368 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4369 return true;
4370 }
4371 // Emit a warning if they are identical; it's likely unintended.
4372 S.Diag(AttrLoc,
4373 diag::warn_attribute_address_multiple_identical_qualifiers);
4374 }
4375 return false;
4376}
4377
4378// Whether this is a type broadly expected to have nullability attached.
4379// These types are affected by `#pragma assume_nonnull`, and missing nullability
4380// will be diagnosed with -Wnullability-completeness.
4382 return T->canHaveNullability(/*ResultIfUnknown=*/false) &&
4383 // For now, do not infer/require nullability on C++ smart pointers.
4384 // It's unclear whether the pragma's behavior is useful for C++.
4385 // e.g. treating type-aliases and template-type-parameters differently
4386 // from types of declarations can be surprising.
4388 T->getCanonicalTypeInternal());
4389}
4390
4391static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4392 QualType declSpecType,
4393 TypeSourceInfo *TInfo) {
4394 // The TypeSourceInfo that this function returns will not be a null type.
4395 // If there is an error, this function will fill in a dummy type as fallback.
4396 QualType T = declSpecType;
4397 Declarator &D = state.getDeclarator();
4398 Sema &S = state.getSema();
4399 ASTContext &Context = S.Context;
4400 const LangOptions &LangOpts = S.getLangOpts();
4401
4402 // The name we're declaring, if any.
4403 DeclarationName Name;
4404 if (D.getIdentifier())
4405 Name = D.getIdentifier();
4406
4407 // Does this declaration declare a typedef-name?
4408 bool IsTypedefName =
4412
4413 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4414 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4415 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4416 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4417
4418 // If T is 'decltype(auto)', the only declarators we can have are parens
4419 // and at most one function declarator if this is a function declaration.
4420 // If T is a deduced class template specialization type, only parentheses
4421 // are allowed.
4422 if (auto *DT = T->getAs<DeducedType>(); DT && !T->containsErrors()) {
4423 const AutoType *AT = T->getAs<AutoType>();
4424 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4425 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4426 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4427 unsigned Index = E - I - 1;
4428 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4429 unsigned DiagId = IsClassTemplateDeduction
4430 ? diag::err_deduced_class_template_compound_type
4431 : diag::err_decltype_auto_compound_type;
4432 unsigned DiagKind = 0;
4433 switch (DeclChunk.Kind) {
4435 continue;
4437 if (IsClassTemplateDeduction) {
4438 DiagKind = 3;
4439 break;
4440 }
4441 unsigned FnIndex;
4443 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4444 continue;
4445 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4446 break;
4447 }
4451 DiagKind = 0;
4452 break;
4454 DiagKind = 1;
4455 break;
4457 DiagKind = 2;
4458 break;
4460 break;
4461 }
4462
4463 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4464 D.setInvalidType(true);
4465 break;
4466 }
4467 }
4468 }
4469
4470 // Determine whether we should infer _Nonnull on pointer types.
4471 NullabilityKindOrNone inferNullability = std::nullopt;
4472 bool inferNullabilityCS = false;
4473 bool inferNullabilityInnerOnly = false;
4474 bool inferNullabilityInnerOnlyComplete = false;
4475
4476 // Are we in an assume-nonnull region?
4477 bool inAssumeNonNullRegion = false;
4478 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4479 if (assumeNonNullLoc.isValid()) {
4480 inAssumeNonNullRegion = true;
4481 recordNullabilitySeen(S, assumeNonNullLoc);
4482 }
4483
4484 // Whether to complain about missing nullability specifiers or not.
4485 enum {
4486 /// Never complain.
4487 CAMN_No,
4488 /// Complain on the inner pointers (but not the outermost
4489 /// pointer).
4490 CAMN_InnerPointers,
4491 /// Complain about any pointers that don't have nullability
4492 /// specified or inferred.
4493 CAMN_Yes
4494 } complainAboutMissingNullability = CAMN_No;
4495 unsigned NumPointersRemaining = 0;
4496 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4497
4498 if (IsTypedefName) {
4499 // For typedefs, we do not infer any nullability (the default),
4500 // and we only complain about missing nullability specifiers on
4501 // inner pointers.
4502 complainAboutMissingNullability = CAMN_InnerPointers;
4503
4504 if (shouldHaveNullability(T) && !T->getNullability()) {
4505 // Note that we allow but don't require nullability on dependent types.
4506 ++NumPointersRemaining;
4507 }
4508
4509 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4510 DeclaratorChunk &chunk = D.getTypeObject(i);
4511 switch (chunk.Kind) {
4515 break;
4516
4519 ++NumPointersRemaining;
4520 break;
4521
4524 continue;
4525
4527 ++NumPointersRemaining;
4528 continue;
4529 }
4530 }
4531 } else {
4532 bool isFunctionOrMethod = false;
4533 switch (auto context = state.getDeclarator().getContext()) {
4539 isFunctionOrMethod = true;
4540 [[fallthrough]];
4541
4543 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4544 complainAboutMissingNullability = CAMN_No;
4545 break;
4546 }
4547
4548 // Weak properties are inferred to be nullable.
4549 if (state.getDeclarator().isObjCWeakProperty()) {
4550 // Weak properties cannot be nonnull, and should not complain about
4551 // missing nullable attributes during completeness checks.
4552 complainAboutMissingNullability = CAMN_No;
4553 if (inAssumeNonNullRegion) {
4554 inferNullability = NullabilityKind::Nullable;
4555 }
4556 break;
4557 }
4558
4559 [[fallthrough]];
4560
4563 complainAboutMissingNullability = CAMN_Yes;
4564
4565 // Nullability inference depends on the type and declarator.
4566 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4567 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4568 case PointerDeclaratorKind::NonPointer:
4569 case PointerDeclaratorKind::MultiLevelPointer:
4570 // Cannot infer nullability.
4571 break;
4572
4573 case PointerDeclaratorKind::SingleLevelPointer:
4574 // Infer _Nonnull if we are in an assumes-nonnull region.
4575 if (inAssumeNonNullRegion) {
4576 complainAboutInferringWithinChunk = wrappingKind;
4577 inferNullability = NullabilityKind::NonNull;
4578 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4580 }
4581 break;
4582
4583 case PointerDeclaratorKind::CFErrorRefPointer:
4584 case PointerDeclaratorKind::NSErrorPointerPointer:
4585 // Within a function or method signature, infer _Nullable at both
4586 // levels.
4587 if (isFunctionOrMethod && inAssumeNonNullRegion)
4588 inferNullability = NullabilityKind::Nullable;
4589 break;
4590
4591 case PointerDeclaratorKind::MaybePointerToCFRef:
4592 if (isFunctionOrMethod) {
4593 // On pointer-to-pointer parameters marked cf_returns_retained or
4594 // cf_returns_not_retained, if the outer pointer is explicit then
4595 // infer the inner pointer as _Nullable.
4596 auto hasCFReturnsAttr =
4597 [](const ParsedAttributesView &AttrList) -> bool {
4598 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4599 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4600 };
4601 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4602 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4603 hasCFReturnsAttr(D.getAttributes()) ||
4604 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4605 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4606 inferNullability = NullabilityKind::Nullable;
4607 inferNullabilityInnerOnly = true;
4608 }
4609 }
4610 }
4611 break;
4612 }
4613 break;
4614 }
4615
4617 complainAboutMissingNullability = CAMN_Yes;
4618 break;
4619
4639 // Don't infer in these contexts.
4640 break;
4641 }
4642 }
4643
4644 // Local function that returns true if its argument looks like a va_list.
4645 auto isVaList = [&S](QualType T) -> bool {
4646 auto *typedefTy = T->getAs<TypedefType>();
4647 if (!typedefTy)
4648 return false;
4649 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4650 do {
4651 if (typedefTy->getDecl() == vaListTypedef)
4652 return true;
4653 if (auto *name = typedefTy->getDecl()->getIdentifier())
4654 if (name->isStr("va_list"))
4655 return true;
4656 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4657 } while (typedefTy);
4658 return false;
4659 };
4660
4661 // Local function that checks the nullability for a given pointer declarator.
4662 // Returns true if _Nonnull was inferred.
4663 auto inferPointerNullability =
4664 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4665 SourceLocation pointerEndLoc,
4666 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4667 // We've seen a pointer.
4668 if (NumPointersRemaining > 0)
4669 --NumPointersRemaining;
4670
4671 // If a nullability attribute is present, there's nothing to do.
4672 if (hasNullabilityAttr(attrs))
4673 return nullptr;
4674
4675 // If we're supposed to infer nullability, do so now.
4676 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4677 ParsedAttr::Form form =
4678 inferNullabilityCS
4679 ? ParsedAttr::Form::ContextSensitiveKeyword()
4680 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4681 false /*IsRegularKeywordAttribute*/);
4682 ParsedAttr *nullabilityAttr = Pool.create(
4683 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4684 AttributeScopeInfo(), nullptr, 0, form);
4685
4686 attrs.addAtEnd(nullabilityAttr);
4687
4688 if (inferNullabilityCS) {
4689 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4690 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4691 }
4692
4693 if (pointerLoc.isValid() &&
4694 complainAboutInferringWithinChunk !=
4695 PointerWrappingDeclaratorKind::None) {
4696 auto Diag =
4697 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4698 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4700 }
4701
4702 if (inferNullabilityInnerOnly)
4703 inferNullabilityInnerOnlyComplete = true;
4704 return nullabilityAttr;
4705 }
4706
4707 // If we're supposed to complain about missing nullability, do so
4708 // now if it's truly missing.
4709 switch (complainAboutMissingNullability) {
4710 case CAMN_No:
4711 break;
4712
4713 case CAMN_InnerPointers:
4714 if (NumPointersRemaining == 0)
4715 break;
4716 [[fallthrough]];
4717
4718 case CAMN_Yes:
4719 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4720 }
4721 return nullptr;
4722 };
4723
4724 // If the type itself could have nullability but does not, infer pointer
4725 // nullability and perform consistency checking.
4726 if (S.CodeSynthesisContexts.empty()) {
4727 if (shouldHaveNullability(T) && !T->getNullability()) {
4728 if (isVaList(T)) {
4729 // Record that we've seen a pointer, but do nothing else.
4730 if (NumPointersRemaining > 0)
4731 --NumPointersRemaining;
4732 } else {
4733 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4734 if (T->isBlockPointerType())
4735 pointerKind = SimplePointerKind::BlockPointer;
4736 else if (T->isMemberPointerType())
4737 pointerKind = SimplePointerKind::MemberPointer;
4738
4739 if (auto *attr = inferPointerNullability(
4740 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4741 D.getDeclSpec().getEndLoc(),
4744 T = state.getAttributedType(
4745 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4746 }
4747 }
4748 }
4749
4750 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
4751 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
4753 checkNullabilityConsistency(S, SimplePointerKind::Array,
4755 }
4756 }
4757
4758 bool ExpectNoDerefChunk =
4759 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4760
4761 // Walk the DeclTypeInfo, building the recursive type as we go.
4762 // DeclTypeInfos are ordered from the identifier out, which is
4763 // opposite of what we want :).
4764
4765 // Track if the produced type matches the structure of the declarator.
4766 // This is used later to decide if we can fill `TypeLoc` from
4767 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
4768 // an error by replacing the type with `int`.
4769 bool AreDeclaratorChunksValid = true;
4770 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4771 unsigned chunkIndex = e - i - 1;
4772 state.setCurrentChunkIndex(chunkIndex);
4773 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4774 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4775 switch (DeclType.Kind) {
4777 if (i == 0)
4779 T = S.BuildParenType(T);
4780 break;
4782 // If blocks are disabled, emit an error.
4783 if (!LangOpts.Blocks)
4784 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4785
4786 // Handle pointer nullability.
4787 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4788 DeclType.EndLoc, DeclType.getAttrs(),
4789 state.getDeclarator().getAttributePool());
4790
4791 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4792 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4793 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4794 // qualified with const.
4795 if (LangOpts.OpenCL)
4796 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4797 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4798 }
4799 break;
4801 // Verify that we're not building a pointer to pointer to function with
4802 // exception specification.
4803 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4804 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4805 D.setInvalidType(true);
4806 // Build the type anyway.
4807 }
4808
4809 // Handle pointer nullability
4810 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4811 DeclType.EndLoc, DeclType.getAttrs(),
4812 state.getDeclarator().getAttributePool());
4813
4814 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4815 T = Context.getObjCObjectPointerType(T);
4816 if (DeclType.Ptr.TypeQuals)
4817 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4818 break;
4819 }
4820
4821 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4822 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4823 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4824 if (LangOpts.OpenCL) {
4825 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4826 T->isBlockPointerType()) {
4827 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4828 D.setInvalidType(true);
4829 }
4830 }
4831
4832 T = S.BuildPointerType(T, DeclType.Loc, Name);
4833 if (DeclType.Ptr.TypeQuals)
4834 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4835 if (DeclType.Ptr.OverflowBehaviorLoc.isValid()) {
4836 auto OBState = DeclType.Ptr.OverflowBehaviorIsWrap
4839 S.Diag(DeclType.Ptr.OverflowBehaviorLoc,
4840 diag::err_overflow_behavior_non_integer_type)
4841 << DeclSpec::getSpecifierName(OBState) << T.getAsString() << 1;
4842 D.setInvalidType(true);
4843 }
4844 break;
4846 // Verify that we're not building a reference to pointer to function with
4847 // exception specification.
4848 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4849 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4850 D.setInvalidType(true);
4851 // Build the type anyway.
4852 }
4853 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4854
4855 if (DeclType.Ref.HasRestrict)
4857 break;
4858 }
4860 // Verify that we're not building an array of pointers to function with
4861 // exception specification.
4862 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4863 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4864 D.setInvalidType(true);
4865 // Build the type anyway.
4866 }
4867 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4868 Expr *ArraySize = ATI.NumElts;
4870
4871 // Microsoft property fields can have multiple sizeless array chunks
4872 // (i.e. int x[][][]). Skip all of these except one to avoid creating
4873 // bad incomplete array types.
4874 if (chunkIndex != 0 && !ArraySize &&
4876 // This is a sizeless chunk. If the next is also, skip this one.
4877 DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1);
4878 if (NextDeclType.Kind == DeclaratorChunk::Array &&
4879 !NextDeclType.Arr.NumElts)
4880 break;
4881 }
4882
4883 if (ATI.isStar)
4885 else if (ATI.hasStatic)
4887 else
4889 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) {
4890 // FIXME: This check isn't quite right: it allows star in prototypes
4891 // for function definitions, and disallows some edge cases detailed
4892 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4893 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4895 D.setInvalidType(true);
4896 }
4897
4898 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4899 // shall appear only in a declaration of a function parameter with an
4900 // array type, ...
4901 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) {
4902 if (!(D.isPrototypeContext() ||
4904 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype)
4905 << (ASM == ArraySizeModifier::Static ? "'static'"
4906 : "type qualifier");
4907 // Remove the 'static' and the type qualifiers.
4908 if (ASM == ArraySizeModifier::Static)
4910 ATI.TypeQuals = 0;
4911 D.setInvalidType(true);
4912 }
4913
4914 // C99 6.7.5.2p1: ... and then only in the outermost array type
4915 // derivation.
4916 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4917 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost)
4918 << (ASM == ArraySizeModifier::Static ? "'static'"
4919 : "type qualifier");
4920 if (ASM == ArraySizeModifier::Static)
4922 ATI.TypeQuals = 0;
4923 D.setInvalidType(true);
4924 }
4925 }
4926
4927 // Array parameters can be marked nullable as well, although it's not
4928 // necessary if they're marked 'static'.
4929 if (complainAboutMissingNullability == CAMN_Yes &&
4930 !hasNullabilityAttr(DeclType.getAttrs()) &&
4932 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4933 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4934 }
4935
4936 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4937 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4938 break;
4939 }
4941 // If the function declarator has a prototype (i.e. it is not () and
4942 // does not have a K&R-style identifier list), then the arguments are part
4943 // of the type, otherwise the argument list is ().
4944 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4945 IsQualifiedFunction =
4947
4948 auto IsClassType = [&](CXXScopeSpec &SS) {
4949 // If there already was an problem with the scope, don’t issue another
4950 // error about the explicit object parameter.
4951 return SS.isInvalid() ||
4952 isa_and_present<CXXRecordDecl>(
4953 S.computeDeclContext(SS, /*EnteringContext=*/true));
4954 };
4955
4956 // C++23 [dcl.fct]p6:
4957 //
4958 // An explicit-object-parameter-declaration is a parameter-declaration
4959 // with a this specifier. An explicit-object-parameter-declaration shall
4960 // appear only as the first parameter-declaration of a
4961 // parameter-declaration-list of one of:
4962 //
4963 // - a declaration of a member function or member function template
4964 // ([class.mem]), or
4965 //
4966 // - an explicit instantiation ([temp.explicit]) or explicit
4967 // specialization ([temp.expl.spec]) of a templated member function,
4968 // or
4969 //
4970 // - a lambda-declarator [expr.prim.lambda].
4973 FTI.NumParams ? dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param)
4974 : nullptr;
4975
4976 bool IsFunctionDecl = D.getInnermostNonParenChunk() == &DeclType;
4977 if (First && First->isExplicitObjectParameter() &&
4979
4980 // Either not a member or nested declarator in a member.
4981 //
4982 // Note that e.g. 'static' or 'friend' declarations are accepted
4983 // here; we diagnose them later when we build the member function
4984 // because it's easier that way.
4985 (C != DeclaratorContext::Member || !IsFunctionDecl) &&
4986
4987 // Allow out-of-line definitions of member functions.
4988 !IsClassType(D.getCXXScopeSpec())) {
4989 if (IsFunctionDecl)
4990 S.Diag(First->getBeginLoc(),
4991 diag::err_explicit_object_parameter_nonmember)
4992 << /*non-member*/ 2 << /*function*/ 0 << First->getSourceRange();
4993 else
4994 S.Diag(First->getBeginLoc(),
4995 diag::err_explicit_object_parameter_invalid)
4996 << First->getSourceRange();
4997
4998 // Do let non-member function have explicit parameters
4999 // to not break assumptions elsewhere in the code.
5000 First->setExplicitObjectParameterLoc(SourceLocation());
5001 D.setInvalidType();
5002 AreDeclaratorChunksValid = false;
5003 }
5004
5005 // Check for auto functions and trailing return type and adjust the
5006 // return type accordingly.
5007 if (!D.isInvalidType()) {
5008 // trailing-return-type is only required if we're declaring a function,
5009 // and not, for instance, a pointer to a function.
5010 if (D.getDeclSpec().hasAutoTypeSpec() &&
5011 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
5012 if (!S.getLangOpts().CPlusPlus14) {
5015 ? diag::err_auto_missing_trailing_return
5016 : diag::err_deduced_return_type);
5017 T = Context.IntTy;
5018 D.setInvalidType(true);
5019 AreDeclaratorChunksValid = false;
5020 } else {
5022 diag::warn_cxx11_compat_deduced_return_type);
5023 }
5024 } else if (FTI.hasTrailingReturnType()) {
5025 // T must be exactly 'auto' at this point. See CWG issue 681.
5026 if (isa<ParenType>(T)) {
5027 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
5028 << T << D.getSourceRange();
5029 D.setInvalidType(true);
5030 // FIXME: recover and fill decls in `TypeLoc`s.
5031 AreDeclaratorChunksValid = false;
5032 } else if (D.getName().getKind() ==
5034 if (T != Context.DependentTy) {
5036 diag::err_deduction_guide_with_complex_decl)
5037 << D.getSourceRange();
5038 D.setInvalidType(true);
5039 // FIXME: recover and fill decls in `TypeLoc`s.
5040 AreDeclaratorChunksValid = false;
5041 }
5042 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
5043 (T.hasQualifiers() || !isa<AutoType>(T) ||
5044 cast<AutoType>(T)->getKeyword() !=
5046 cast<AutoType>(T)->isConstrained())) {
5047 // Attach a valid source location for diagnostics on functions with
5048 // trailing return types missing 'auto'. Attempt to get the location
5049 // from the declared type; if invalid, fall back to the trailing
5050 // return type's location.
5053 if (Loc.isInvalid()) {
5054 Loc = FTI.getTrailingReturnTypeLoc();
5055 SR = D.getSourceRange();
5056 }
5057 S.Diag(Loc, diag::err_trailing_return_without_auto) << T << SR;
5058 D.setInvalidType(true);
5059 // FIXME: recover and fill decls in `TypeLoc`s.
5060 AreDeclaratorChunksValid = false;
5061 }
5062 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5063 if (T.isNull()) {
5064 // An error occurred parsing the trailing return type.
5065 T = Context.IntTy;
5066 D.setInvalidType(true);
5067 } else if (AutoType *Auto = T->getContainedAutoType()) {
5068 // If the trailing return type contains an `auto`, we may need to
5069 // invent a template parameter for it, for cases like
5070 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5071 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5073 InventedParamInfo = &S.InventedParameterInfos.back();
5075 InventedParamInfo = S.getCurLambda();
5076 if (InventedParamInfo) {
5077 std::tie(T, TInfo) = InventTemplateParameter(
5078 state, T, TInfo, Auto, *InventedParamInfo);
5079 }
5080 }
5081 } else {
5082 // This function type is not the type of the entity being declared,
5083 // so checking the 'auto' is not the responsibility of this chunk.
5084 }
5085 }
5086
5087 // C99 6.7.5.3p1: The return type may not be a function or array type.
5088 // For conversion functions, we'll diagnose this particular error later.
5089 if (!D.isInvalidType() &&
5090 ((T->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
5091 T->isFunctionType()) &&
5092 (D.getName().getKind() !=
5094 unsigned diagID = diag::err_func_returning_array_function;
5095 // Last processing chunk in block context means this function chunk
5096 // represents the block.
5097 if (chunkIndex == 0 &&
5099 diagID = diag::err_block_returning_array_function;
5100 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5101 T = Context.IntTy;
5102 D.setInvalidType(true);
5103 AreDeclaratorChunksValid = false;
5104 }
5105
5106 // Do not allow returning half FP value.
5107 // FIXME: This really should be in BuildFunctionType.
5108 if (T->isHalfType()) {
5109 if (S.getLangOpts().OpenCL) {
5110 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5111 S.getLangOpts())) {
5112 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5113 << T << 0 /*pointer hint*/;
5114 D.setInvalidType(true);
5115 }
5116 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5118 S.Diag(D.getIdentifierLoc(),
5119 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5120 D.setInvalidType(true);
5121 }
5122 }
5123
5124 // __ptrauth is illegal on a function return type.
5125 if (T.getPointerAuth()) {
5126 S.Diag(DeclType.Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
5127 }
5128
5129 if (LangOpts.OpenCL) {
5130 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5131 // function.
5132 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5133 T->isPipeType()) {
5134 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5135 << T << 1 /*hint off*/;
5136 D.setInvalidType(true);
5137 }
5138 // OpenCL doesn't support variadic functions and blocks
5139 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5140 // We also allow here any toolchain reserved identifiers.
5141 if (FTI.isVariadic &&
5143 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5144 !(D.getIdentifier() &&
5145 ((D.getIdentifier()->getName() == "printf" &&
5146 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5147 D.getIdentifier()->getName().starts_with("__")))) {
5148 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5149 D.setInvalidType(true);
5150 }
5151 }
5152
5153 // Methods cannot return interface types. All ObjC objects are
5154 // passed by reference.
5155 if (T->isObjCObjectType()) {
5156 SourceLocation DiagLoc, FixitLoc;
5157 if (TInfo) {
5158 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5159 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5160 } else {
5161 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5162 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5163 }
5164 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5165 << 0 << T
5166 << FixItHint::CreateInsertion(FixitLoc, "*");
5167
5168 T = Context.getObjCObjectPointerType(T);
5169 if (TInfo) {
5170 TypeLocBuilder TLB;
5171 TLB.pushFullCopy(TInfo->getTypeLoc());
5173 TLoc.setStarLoc(FixitLoc);
5174 TInfo = TLB.getTypeSourceInfo(Context, T);
5175 } else {
5176 AreDeclaratorChunksValid = false;
5177 }
5178
5179 D.setInvalidType(true);
5180 }
5181
5182 // cv-qualifiers on return types are pointless except when the type is a
5183 // class type in C++.
5184 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5185 // A dependent type or an undeduced type might later become a class
5186 // type.
5187 !(S.getLangOpts().CPlusPlus &&
5188 (T->isRecordType() || T->isDependentType() ||
5189 T->isUndeducedAutoType()))) {
5190 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5193 // [6.9.1/3] qualified void return is invalid on a C
5194 // function definition. Apparently ok on declarations and
5195 // in C++ though (!)
5196 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5197 } else
5198 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5199 }
5200
5201 // C++2a [dcl.fct]p12:
5202 // A volatile-qualified return type is deprecated
5203 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5204 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5205
5206 // Objective-C ARC ownership qualifiers are ignored on the function
5207 // return type (by type canonicalization). Complain if this attribute
5208 // was written here.
5209 if (T.getQualifiers().hasObjCLifetime()) {
5210 SourceLocation AttrLoc;
5211 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5212 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5213 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5214 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5215 AttrLoc = AL.getLoc();
5216 break;
5217 }
5218 }
5219 }
5220 if (AttrLoc.isInvalid()) {
5221 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5222 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5223 AttrLoc = AL.getLoc();
5224 break;
5225 }
5226 }
5227 }
5228
5229 if (AttrLoc.isValid()) {
5230 // The ownership attributes are almost always written via
5231 // the predefined
5232 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5233 if (AttrLoc.isMacroID())
5234 AttrLoc =
5236
5237 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5238 << T.getQualifiers().getObjCLifetime();
5239 }
5240 }
5241
5242 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5243 // C++ [dcl.fct]p6:
5244 // Types shall not be defined in return or parameter types.
5246 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5247 << Context.getCanonicalTagType(Tag);
5248 }
5249
5250 // Exception specs are not allowed in typedefs. Complain, but add it
5251 // anyway.
5252 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5254 diag::err_exception_spec_in_typedef)
5257
5258 // If we see "T var();" or "T var(T());" at block scope, it is probably
5259 // an attempt to initialize a variable, not a function declaration.
5260 if (FTI.isAmbiguous)
5261 warnAboutAmbiguousFunction(S, D, DeclType, T);
5262
5264 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5265
5266 // OpenCL disallows functions without a prototype, but it doesn't enforce
5267 // strict prototypes as in C23 because it allows a function definition to
5268 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5269 if (!FTI.NumParams && !FTI.isVariadic &&
5270 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5271 // Simple void foo(), where the incoming T is the result type.
5272 T = Context.getFunctionNoProtoType(T, EI);
5273 } else {
5274 // We allow a zero-parameter variadic function in C if the
5275 // function is marked with the "overloadable" attribute. Scan
5276 // for this attribute now. We also allow it in C23 per WG14 N2975.
5277 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5278 if (LangOpts.C23)
5279 S.Diag(FTI.getEllipsisLoc(),
5280 diag::warn_c17_compat_ellipsis_only_parameter);
5282 ParsedAttr::AT_Overloadable) &&
5284 ParsedAttr::AT_Overloadable) &&
5286 ParsedAttr::AT_Overloadable))
5287 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5288 }
5289
5290 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5291 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5292 // definition.
5293 S.Diag(FTI.Params[0].IdentLoc,
5294 diag::err_ident_list_in_fn_declaration);
5295 D.setInvalidType(true);
5296 // Recover by creating a K&R-style function type, if possible.
5297 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5298 ? Context.getFunctionNoProtoType(T, EI)
5299 : Context.IntTy;
5300 AreDeclaratorChunksValid = false;
5301 break;
5302 }
5303
5305 EPI.ExtInfo = EI;
5306 EPI.Variadic = FTI.isVariadic;
5307 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5311 : 0);
5314 : RQ_RValue;
5315
5316 // Otherwise, we have a function with a parameter list that is
5317 // potentially variadic.
5319 ParamTys.reserve(FTI.NumParams);
5320
5322 ExtParameterInfos(FTI.NumParams);
5323 bool HasAnyInterestingExtParameterInfos = false;
5324
5325 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5326 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5327 QualType ParamTy = Param->getType();
5328 assert(!ParamTy.isNull() && "Couldn't parse type?");
5329
5330 // Look for 'void'. void is allowed only as a single parameter to a
5331 // function with no other parameters (C99 6.7.5.3p10). We record
5332 // int(void) as a FunctionProtoType with an empty parameter list.
5333 if (ParamTy->isVoidType()) {
5334 // If this is something like 'float(int, void)', reject it. 'void'
5335 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5336 // have parameters of incomplete type.
5337 if (FTI.NumParams != 1 || FTI.isVariadic) {
5338 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5339 ParamTy = Context.IntTy;
5340 Param->setType(ParamTy);
5341 } else if (FTI.Params[i].Ident) {
5342 // Reject, but continue to parse 'int(void abc)'.
5343 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5344 ParamTy = Context.IntTy;
5345 Param->setType(ParamTy);
5346 } else {
5347 // Reject, but continue to parse 'float(const void)'.
5348 if (ParamTy.hasQualifiers())
5349 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5350
5351 for (const auto *A : Param->attrs()) {
5352 S.Diag(A->getLoc(), diag::warn_attribute_on_void_param)
5353 << A << A->getRange();
5354 }
5355
5356 // Reject, but continue to parse 'float(this void)' as
5357 // 'float(void)'.
5358 if (Param->isExplicitObjectParameter()) {
5359 S.Diag(Param->getLocation(),
5360 diag::err_void_explicit_object_param);
5361 Param->setExplicitObjectParameterLoc(SourceLocation());
5362 }
5363
5364 // Do not add 'void' to the list.
5365 break;
5366 }
5367 } else if (ParamTy->isHalfType()) {
5368 // Disallow half FP parameters.
5369 // FIXME: This really should be in BuildFunctionType.
5370 if (S.getLangOpts().OpenCL) {
5371 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5372 S.getLangOpts())) {
5373 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5374 << ParamTy << 0;
5375 D.setInvalidType();
5376 Param->setInvalidDecl();
5377 }
5378 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5380 S.Diag(Param->getLocation(),
5381 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5382 D.setInvalidType();
5383 }
5384 } else if (!FTI.hasPrototype) {
5385 if (Context.isPromotableIntegerType(ParamTy)) {
5386 ParamTy = Context.getPromotedIntegerType(ParamTy);
5387 Param->setKNRPromoted(true);
5388 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5389 if (BTy->getKind() == BuiltinType::Float) {
5390 ParamTy = Context.DoubleTy;
5391 Param->setKNRPromoted(true);
5392 }
5393 }
5394 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5395 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5396 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5397 << ParamTy << 1 /*hint off*/;
5398 D.setInvalidType();
5399 }
5400
5401 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5402 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5403 HasAnyInterestingExtParameterInfos = true;
5404 }
5405
5406 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5407 ExtParameterInfos[i] =
5408 ExtParameterInfos[i].withABI(attr->getABI());
5409 HasAnyInterestingExtParameterInfos = true;
5410 }
5411
5412 if (Param->hasAttr<PassObjectSizeAttr>()) {
5413 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5414 HasAnyInterestingExtParameterInfos = true;
5415 }
5416
5417 if (Param->hasAttr<NoEscapeAttr>()) {
5418 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5419 HasAnyInterestingExtParameterInfos = true;
5420 }
5421
5422 ParamTys.push_back(ParamTy);
5423 }
5424
5425 if (HasAnyInterestingExtParameterInfos) {
5426 EPI.ExtParameterInfos = ExtParameterInfos.data();
5427 checkExtParameterInfos(S, ParamTys, EPI,
5428 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5429 }
5430
5431 SmallVector<QualType, 4> Exceptions;
5432 SmallVector<ParsedType, 2> DynamicExceptions;
5433 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5434 Expr *NoexceptExpr = nullptr;
5435
5436 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5437 // FIXME: It's rather inefficient to have to split into two vectors
5438 // here.
5439 unsigned N = FTI.getNumExceptions();
5440 DynamicExceptions.reserve(N);
5441 DynamicExceptionRanges.reserve(N);
5442 for (unsigned I = 0; I != N; ++I) {
5443 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5444 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5445 }
5446 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5447 NoexceptExpr = FTI.NoexceptExpr;
5448 }
5449
5452 DynamicExceptions,
5453 DynamicExceptionRanges,
5454 NoexceptExpr,
5455 Exceptions,
5456 EPI.ExceptionSpec);
5457
5458 // FIXME: Set address space from attrs for C++ mode here.
5459 // OpenCLCPlusPlus: A class member function has an address space.
5460 auto IsClassMember = [&]() {
5461 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5462 state.getDeclarator()
5463 .getCXXScopeSpec()
5464 .getScopeRep()
5465 .getKind() == NestedNameSpecifier::Kind::Type) ||
5466 state.getDeclarator().getContext() ==
5468 state.getDeclarator().getContext() ==
5470 };
5471
5472 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5473 LangAS ASIdx = LangAS::Default;
5474 // Take address space attr if any and mark as invalid to avoid adding
5475 // them later while creating QualType.
5476 if (FTI.MethodQualifiers)
5478 LangAS ASIdxNew = attr.asOpenCLLangAS();
5479 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5480 attr.getLoc()))
5481 D.setInvalidType(true);
5482 else
5483 ASIdx = ASIdxNew;
5484 }
5485 // If a class member function's address space is not set, set it to
5486 // __generic.
5487 LangAS AS =
5489 : ASIdx);
5490 EPI.TypeQuals.addAddressSpace(AS);
5491 }
5492 T = Context.getFunctionType(T, ParamTys, EPI);
5493 }
5494 break;
5495 }
5497 // The scope spec must refer to a class, or be dependent.
5498 CXXScopeSpec &SS = DeclType.Mem.Scope();
5499
5500 // Handle pointer nullability.
5501 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5502 DeclType.EndLoc, DeclType.getAttrs(),
5503 state.getDeclarator().getAttributePool());
5504
5505 if (SS.isInvalid()) {
5506 // Avoid emitting extra errors if we already errored on the scope.
5507 D.setInvalidType(true);
5508 AreDeclaratorChunksValid = false;
5509 } else {
5510 T = S.BuildMemberPointerType(T, SS, /*Cls=*/nullptr, DeclType.Loc,
5511 D.getIdentifier());
5512 }
5513
5514 if (T.isNull()) {
5515 T = Context.IntTy;
5516 D.setInvalidType(true);
5517 AreDeclaratorChunksValid = false;
5518 } else if (DeclType.Mem.TypeQuals) {
5519 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5520 }
5521 break;
5522 }
5523
5524 case DeclaratorChunk::Pipe: {
5525 T = S.BuildReadPipeType(T, DeclType.Loc);
5526 if (!T.isNull())
5529 break;
5530 }
5531 }
5532
5533 if (T.isNull()) {
5534 D.setInvalidType(true);
5535 T = Context.IntTy;
5536 AreDeclaratorChunksValid = false;
5537 }
5538
5539 // See if there are any attributes on this declarator chunk.
5540 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs(),
5542
5543 if (DeclType.Kind != DeclaratorChunk::Paren) {
5544 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5545 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5546
5547 ExpectNoDerefChunk = state.didParseNoDeref();
5548 }
5549 }
5550
5551 if (ExpectNoDerefChunk)
5552 S.Diag(state.getDeclarator().getBeginLoc(),
5553 diag::warn_noderef_on_non_pointer_or_array);
5554
5555 // GNU warning -Wstrict-prototypes
5556 // Warn if a function declaration or definition is without a prototype.
5557 // This warning is issued for all kinds of unprototyped function
5558 // declarations (i.e. function type typedef, function pointer etc.)
5559 // C99 6.7.5.3p14:
5560 // The empty list in a function declarator that is not part of a definition
5561 // of that function specifies that no information about the number or types
5562 // of the parameters is supplied.
5563 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5564 // function declarations whose behavior changes in C23.
5565 if (!LangOpts.requiresStrictPrototypes()) {
5566 bool IsBlock = false;
5567 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5568 switch (DeclType.Kind) {
5570 IsBlock = true;
5571 break;
5573 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5574 // We suppress the warning when there's no LParen location, as this
5575 // indicates the declaration was an implicit declaration, which gets
5576 // warned about separately via -Wimplicit-function-declaration. We also
5577 // suppress the warning when we know the function has a prototype.
5578 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5579 FTI.getLParenLoc().isValid())
5580 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5581 << IsBlock
5582 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5583 IsBlock = false;
5584 break;
5585 }
5586 default:
5587 break;
5588 }
5589 }
5590 }
5591
5592 assert(!T.isNull() && "T must not be null after this point");
5593
5594 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5595 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5596 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5597
5598 // C++ 8.3.5p4:
5599 // A cv-qualifier-seq shall only be part of the function type
5600 // for a nonstatic member function, the function type to which a pointer
5601 // to member refers, or the top-level function type of a function typedef
5602 // declaration.
5603 //
5604 // Core issue 547 also allows cv-qualifiers on function types that are
5605 // top-level template type arguments.
5606 enum {
5607 NonMember,
5608 Member,
5609 ExplicitObjectMember,
5610 DeductionGuide
5611 } Kind = NonMember;
5613 Kind = DeductionGuide;
5614 else if (!D.getCXXScopeSpec().isSet()) {
5618 Kind = Member;
5619 } else {
5621 if (!DC || DC->isRecord())
5622 Kind = Member;
5623 }
5624
5625 if (Kind == Member) {
5626 unsigned I;
5627 if (D.isFunctionDeclarator(I)) {
5628 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5629 if (Chunk.Fun.NumParams) {
5630 auto *P = dyn_cast_or_null<ParmVarDecl>(Chunk.Fun.Params->Param);
5631 if (P && P->isExplicitObjectParameter())
5632 Kind = ExplicitObjectMember;
5633 }
5634 }
5635 }
5636
5637 // C++11 [dcl.fct]p6 (w/DR1417):
5638 // An attempt to specify a function type with a cv-qualifier-seq or a
5639 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5640 // - the function type for a non-static member function,
5641 // - the function type to which a pointer to member refers,
5642 // - the top-level function type of a function typedef declaration or
5643 // alias-declaration,
5644 // - the type-id in the default argument of a type-parameter, or
5645 // - the type-id of a template-argument for a type-parameter
5646 //
5647 // C++23 [dcl.fct]p6 (P0847R7)
5648 // ... A member-declarator with an explicit-object-parameter-declaration
5649 // shall not include a ref-qualifier or a cv-qualifier-seq and shall not be
5650 // declared static or virtual ...
5651 //
5652 // FIXME: Checking this here is insufficient. We accept-invalid on:
5653 //
5654 // template<typename T> struct S { void f(T); };
5655 // S<int() const> s;
5656 //
5657 // ... for instance.
5658 if (IsQualifiedFunction &&
5659 // Check for non-static member function and not and
5660 // explicit-object-parameter-declaration
5661 (Kind != Member || D.isExplicitObjectMemberFunction() ||
5664 D.isStaticMember())) &&
5665 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5668 SourceLocation Loc = D.getBeginLoc();
5669 SourceRange RemovalRange;
5670 unsigned I;
5671 if (D.isFunctionDeclarator(I)) {
5673 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5674 assert(Chunk.Kind == DeclaratorChunk::Function);
5675
5676 if (Chunk.Fun.hasRefQualifier())
5677 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5678
5679 if (Chunk.Fun.hasMethodTypeQualifiers())
5681 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5682 SourceLocation SL) { RemovalLocs.push_back(SL); });
5683
5684 if (!RemovalLocs.empty()) {
5685 llvm::sort(RemovalLocs,
5687 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5688 Loc = RemovalLocs.front();
5689 }
5690 }
5691
5692 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5693 << Kind << D.isFunctionDeclarator() << T
5695 << FixItHint::CreateRemoval(RemovalRange);
5696
5697 // Strip the cv-qualifiers and ref-qualifiers from the type.
5700 EPI.RefQualifier = RQ_None;
5701
5702 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5703 EPI);
5704 // Rebuild any parens around the identifier in the function type.
5705 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5707 break;
5708 T = S.BuildParenType(T);
5709 }
5710 }
5711 }
5712
5713 // Apply any undistributed attributes from the declaration or declarator.
5714 ParsedAttributesView NonSlidingAttrs;
5715 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5716 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5717 NonSlidingAttrs.addAtEnd(&AL);
5718 }
5719 }
5720 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5722
5723 // Diagnose any ignored type attributes.
5724 state.diagnoseIgnoredTypeAttrs(T);
5725
5726 // C++0x [dcl.constexpr]p9:
5727 // A constexpr specifier used in an object declaration declares the object
5728 // as const.
5730 T->isObjectType())
5731 T.addConst();
5732
5733 // C++2a [dcl.fct]p4:
5734 // A parameter with volatile-qualified type is deprecated
5735 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5738 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5739
5740 // If there was an ellipsis in the declarator, the declaration declares a
5741 // parameter pack whose type may be a pack expansion type.
5742 if (D.hasEllipsis()) {
5743 // C++0x [dcl.fct]p13:
5744 // A declarator-id or abstract-declarator containing an ellipsis shall
5745 // only be used in a parameter-declaration. Such a parameter-declaration
5746 // is a parameter pack (14.5.3). [...]
5747 switch (D.getContext()) {
5751 // C++0x [dcl.fct]p13:
5752 // [...] When it is part of a parameter-declaration-clause, the
5753 // parameter pack is a function parameter pack (14.5.3). The type T
5754 // of the declarator-id of the function parameter pack shall contain
5755 // a template parameter pack; each template parameter pack in T is
5756 // expanded by the function parameter pack.
5757 //
5758 // We represent function parameter packs as function parameters whose
5759 // type is a pack expansion.
5760 if (!T->containsUnexpandedParameterPack() &&
5761 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5762 S.Diag(D.getEllipsisLoc(),
5763 diag::err_function_parameter_pack_without_parameter_packs)
5764 << T << D.getSourceRange();
5766 } else {
5767 T = Context.getPackExpansionType(T, std::nullopt,
5768 /*ExpectPackInType=*/false);
5769 }
5770 break;
5772 // C++0x [temp.param]p15:
5773 // If a template-parameter is a [...] is a parameter-declaration that
5774 // declares a parameter pack (8.3.5), then the template-parameter is a
5775 // template parameter pack (14.5.3).
5776 //
5777 // Note: core issue 778 clarifies that, if there are any unexpanded
5778 // parameter packs in the type of the non-type template parameter, then
5779 // it expands those parameter packs.
5780 if (T->containsUnexpandedParameterPack())
5781 T = Context.getPackExpansionType(T, std::nullopt);
5782 else
5783 S.DiagCompat(D.getEllipsisLoc(), diag_compat::variadic_templates);
5784 break;
5785
5788 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5789 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
5810 // FIXME: We may want to allow parameter packs in block-literal contexts
5811 // in the future.
5812 S.Diag(D.getEllipsisLoc(),
5813 diag::err_ellipsis_in_declarator_not_parameter);
5815 break;
5816 }
5817 }
5818
5819 assert(!T.isNull() && "T must not be null at the end of this function");
5820 if (!AreDeclaratorChunksValid)
5821 return Context.getTrivialTypeSourceInfo(T);
5822
5823 if (state.didParseHLSLParamMod() && !T->isConstantArrayType())
5825 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5826}
5827
5829 // Determine the type of the declarator. Not all forms of declarator
5830 // have a type.
5831
5832 TypeProcessingState state(*this, D);
5833
5834 TypeSourceInfo *ReturnTypeInfo = nullptr;
5835 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5836 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5837 inferARCWriteback(state, T);
5838
5839 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5840}
5841
5843 QualType &declSpecTy,
5844 Qualifiers::ObjCLifetime ownership) {
5845 if (declSpecTy->isObjCRetainableType() &&
5846 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5847 Qualifiers qs;
5848 qs.addObjCLifetime(ownership);
5849 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5850 }
5851}
5852
5853static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5854 Qualifiers::ObjCLifetime ownership,
5855 unsigned chunkIndex) {
5856 Sema &S = state.getSema();
5857 Declarator &D = state.getDeclarator();
5858
5859 // Look for an explicit lifetime attribute.
5860 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5861 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5862 return;
5863
5864 const char *attrStr = nullptr;
5865 switch (ownership) {
5866 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5867 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5868 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5869 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5870 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5871 }
5872
5873 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5874 Arg->setIdentifierInfo(&S.Context.Idents.get(attrStr));
5875
5876 ArgsUnion Args(Arg);
5877
5878 // If there wasn't one, add one (with an invalid source location
5879 // so that we don't make an AttributedType for it).
5880 ParsedAttr *attr =
5881 D.getAttributePool().create(&S.Context.Idents.get("objc_ownership"),
5883 /*args*/ &Args, 1, ParsedAttr::Form::GNU());
5884 chunk.getAttrs().addAtEnd(attr);
5885 // TODO: mark whether we did this inference?
5886}
5887
5888/// Used for transferring ownership in casts resulting in l-values.
5889static void transferARCOwnership(TypeProcessingState &state,
5890 QualType &declSpecTy,
5891 Qualifiers::ObjCLifetime ownership) {
5892 Sema &S = state.getSema();
5893 Declarator &D = state.getDeclarator();
5894
5895 int inner = -1;
5896 bool hasIndirection = false;
5897 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5898 DeclaratorChunk &chunk = D.getTypeObject(i);
5899 switch (chunk.Kind) {
5901 // Ignore parens.
5902 break;
5903
5907 if (inner != -1)
5908 hasIndirection = true;
5909 inner = i;
5910 break;
5911
5913 if (inner != -1)
5914 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5915 return;
5916
5920 return;
5921 }
5922 }
5923
5924 if (inner == -1)
5925 return;
5926
5927 DeclaratorChunk &chunk = D.getTypeObject(inner);
5928 if (chunk.Kind == DeclaratorChunk::Pointer) {
5929 if (declSpecTy->isObjCRetainableType())
5930 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5931 if (declSpecTy->isObjCObjectType() && hasIndirection)
5932 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5933 } else {
5934 assert(chunk.Kind == DeclaratorChunk::Array ||
5936 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5937 }
5938}
5939
5941 TypeProcessingState state(*this, D);
5942
5943 TypeSourceInfo *ReturnTypeInfo = nullptr;
5944 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5945
5946 if (getLangOpts().ObjC) {
5947 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5948 if (ownership != Qualifiers::OCL_None)
5949 transferARCOwnership(state, declSpecTy, ownership);
5950 }
5951
5952 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5953}
5954
5956 TypeProcessingState &State) {
5957 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5958}
5959
5961 TypeProcessingState &State) {
5963 State.getSema().HLSL().TakeLocForHLSLAttribute(TL.getTypePtr());
5964 TL.setSourceRange(LocInfo.Range);
5966}
5967
5969 const ParsedAttributesView &Attrs) {
5970 for (const ParsedAttr &AL : Attrs) {
5971 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
5972 MTL.setAttrNameLoc(AL.getLoc());
5973 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
5974 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
5976 return;
5977 }
5978 }
5979
5980 llvm_unreachable("no matrix_type attribute found at the expected location!");
5981}
5982
5983static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5984 SourceLocation Loc;
5985 switch (Chunk.Kind) {
5990 llvm_unreachable("cannot be _Atomic qualified");
5991
5993 Loc = Chunk.Ptr.AtomicQualLoc;
5994 break;
5995
5999 // FIXME: Provide a source location for the _Atomic keyword.
6000 break;
6001 }
6002
6003 ATL.setKWLoc(Loc);
6005}
6006
6007namespace {
6008 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
6009 Sema &SemaRef;
6010 ASTContext &Context;
6011 TypeProcessingState &State;
6012 const DeclSpec &DS;
6013
6014 public:
6015 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
6016 const DeclSpec &DS)
6017 : SemaRef(S), Context(Context), State(State), DS(DS) {}
6018
6019 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6020 Visit(TL.getModifiedLoc());
6021 fillAttributedTypeLoc(TL, State);
6022 }
6023 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6024 Visit(TL.getWrappedLoc());
6025 }
6026 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
6027 Visit(TL.getWrappedLoc());
6028 }
6029 void VisitHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL) {
6030 Visit(TL.getWrappedLoc());
6032 }
6033 void VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {}
6034 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6035 Visit(TL.getInnerLoc());
6036 TL.setExpansionLoc(
6037 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6038 }
6039 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6040 Visit(TL.getUnqualifiedLoc());
6041 }
6042 // Allow to fill pointee's type locations, e.g.,
6043 // int __attr * __attr * __attr *p;
6044 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
6045 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6046 if (DS.getTypeSpecType() == TST_typename) {
6047 TypeSourceInfo *TInfo = nullptr;
6049 if (TInfo) {
6050 TL.copy(TInfo->getTypeLoc().castAs<TypedefTypeLoc>());
6051 return;
6052 }
6053 }
6054 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6055 ? DS.getTypeSpecTypeLoc()
6056 : SourceLocation(),
6059 }
6060 void VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6061 if (DS.getTypeSpecType() == TST_typename) {
6062 TypeSourceInfo *TInfo = nullptr;
6064 if (TInfo) {
6065 TL.copy(TInfo->getTypeLoc().castAs<UnresolvedUsingTypeLoc>());
6066 return;
6067 }
6068 }
6069 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6070 ? DS.getTypeSpecTypeLoc()
6071 : SourceLocation(),
6074 }
6075 void VisitUsingTypeLoc(UsingTypeLoc TL) {
6076 if (DS.getTypeSpecType() == TST_typename) {
6077 TypeSourceInfo *TInfo = nullptr;
6079 if (TInfo) {
6080 TL.copy(TInfo->getTypeLoc().castAs<UsingTypeLoc>());
6081 return;
6082 }
6083 }
6084 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6085 ? DS.getTypeSpecTypeLoc()
6086 : SourceLocation(),
6089 }
6090 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6092 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6093 // addition field. What we have is good enough for display of location
6094 // of 'fixit' on interface name.
6095 TL.setNameEndLoc(DS.getEndLoc());
6096 }
6097 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6098 TypeSourceInfo *RepTInfo = nullptr;
6099 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6100 TL.copy(RepTInfo->getTypeLoc());
6101 }
6102 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6103 TypeSourceInfo *RepTInfo = nullptr;
6104 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6105 TL.copy(RepTInfo->getTypeLoc());
6106 }
6107 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6108 TypeSourceInfo *TInfo = nullptr;
6110
6111 // If we got no declarator info from previous Sema routines,
6112 // just fill with the typespec loc.
6113 if (!TInfo) {
6114 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
6115 return;
6116 }
6117
6118 TypeLoc OldTL = TInfo->getTypeLoc();
6119 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6120 assert(TL.getRAngleLoc() ==
6121 OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6122 }
6123 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6128 }
6129 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6134 assert(DS.getRepAsType());
6135 TypeSourceInfo *TInfo = nullptr;
6137 TL.setUnmodifiedTInfo(TInfo);
6138 }
6139 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6143 }
6144 void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6146 TypeSourceInfo *TInfo = nullptr;
6148 TL.copy(TInfo->getTypeLoc());
6149 }
6150 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6151 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6154 assert(DS.getRepAsType());
6155 TypeSourceInfo *TInfo = nullptr;
6157 TL.setUnderlyingTInfo(TInfo);
6158 }
6159 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6160 // By default, use the source location of the type specifier.
6162 if (TL.needsExtraLocalData()) {
6163 // Set info for the written builtin specifiers.
6165 // Try to have a meaningful source location.
6166 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6168 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6170 }
6171 }
6172 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6173 assert(DS.getTypeSpecType() == TST_typename);
6174 TypeSourceInfo *TInfo = nullptr;
6176 assert(TInfo);
6177 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6178 }
6179 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6180 assert(DS.getTypeSpecType() == TST_auto ||
6187 if (!DS.isConstrainedAuto())
6188 return;
6189 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6190 if (!TemplateId)
6191 return;
6192
6193 NestedNameSpecifierLoc NNS =
6194 (DS.getTypeSpecScope().isNotEmpty()
6196 : NestedNameSpecifierLoc());
6197 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6198 TemplateId->RAngleLoc);
6199 if (TemplateId->NumArgs > 0) {
6200 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6201 TemplateId->NumArgs);
6202 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6203 }
6204 DeclarationNameInfo DNI = Context.getNameForTemplate(
6205 TL.getTypePtr()->getTypeConstraintConcept(),
6206 TemplateId->TemplateNameLoc);
6207
6208 NamedDecl *FoundDecl;
6209 if (auto TN = TemplateId->Template.get();
6210 UsingShadowDecl *USD = TN.getAsUsingShadowDecl())
6211 FoundDecl = cast<NamedDecl>(USD);
6212 else
6213 FoundDecl = cast_if_present<NamedDecl>(TN.getAsTemplateDecl());
6214
6215 auto *CR = ConceptReference::Create(
6216 Context, NNS, TemplateId->TemplateKWLoc, DNI, FoundDecl,
6217 /*NamedDecl=*/TL.getTypePtr()->getTypeConstraintConcept(),
6218 ASTTemplateArgumentListInfo::Create(Context, TemplateArgsInfo));
6219 TL.setConceptReference(CR);
6220 }
6221 void VisitDeducedTemplateSpecializationTypeLoc(
6222 DeducedTemplateSpecializationTypeLoc TL) {
6223 assert(DS.getTypeSpecType() == TST_typename);
6224 TypeSourceInfo *TInfo = nullptr;
6226 assert(TInfo);
6227 TL.copy(
6228 TInfo->getTypeLoc().castAs<DeducedTemplateSpecializationTypeLoc>());
6229 }
6230 void VisitTagTypeLoc(TagTypeLoc TL) {
6231 if (DS.getTypeSpecType() == TST_typename) {
6232 TypeSourceInfo *TInfo = nullptr;
6234 if (TInfo) {
6235 TL.copy(TInfo->getTypeLoc().castAs<TagTypeLoc>());
6236 return;
6237 }
6238 }
6239 TL.setElaboratedKeywordLoc(TL.getTypePtr()->getKeyword() !=
6240 ElaboratedTypeKeyword::None
6241 ? DS.getTypeSpecTypeLoc()
6242 : SourceLocation());
6245 }
6246 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6247 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6248 // or an _Atomic qualifier.
6252
6253 TypeSourceInfo *TInfo = nullptr;
6255 assert(TInfo);
6257 } else {
6258 TL.setKWLoc(DS.getAtomicSpecLoc());
6259 // No parens, to indicate this was spelled as an _Atomic qualifier.
6260 TL.setParensRange(SourceRange());
6261 Visit(TL.getValueLoc());
6262 }
6263 }
6264
6265 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6267
6268 TypeSourceInfo *TInfo = nullptr;
6271 }
6272
6273 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6275 }
6276
6277 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6279 }
6280
6281 void VisitTypeLoc(TypeLoc TL) {
6282 // FIXME: add other typespec types and change this to an assert.
6283 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6284 }
6285 };
6286
6287 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6288 ASTContext &Context;
6289 TypeProcessingState &State;
6290 const DeclaratorChunk &Chunk;
6291
6292 public:
6293 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6294 const DeclaratorChunk &Chunk)
6295 : Context(Context), State(State), Chunk(Chunk) {}
6296
6297 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6298 llvm_unreachable("qualified type locs not expected here!");
6299 }
6300 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6301 llvm_unreachable("decayed type locs not expected here!");
6302 }
6303 void VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6304 llvm_unreachable("array parameter type locs not expected here!");
6305 }
6306
6307 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6308 fillAttributedTypeLoc(TL, State);
6309 }
6310 void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
6311 // nothing
6312 }
6313 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6314 // nothing
6315 }
6316 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
6317 // nothing
6318 }
6319 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6320 // nothing
6321 }
6322 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6323 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6324 TL.setCaretLoc(Chunk.Loc);
6325 }
6326 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6327 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6328 TL.setStarLoc(Chunk.Loc);
6329 }
6330 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6331 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6332 TL.setStarLoc(Chunk.Loc);
6333 }
6334 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6335 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6336 TL.setStarLoc(Chunk.Mem.StarLoc);
6337 TL.setQualifierLoc(Chunk.Mem.Scope().getWithLocInContext(Context));
6338 }
6339 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6340 assert(Chunk.Kind == DeclaratorChunk::Reference);
6341 // 'Amp' is misleading: this might have been originally
6342 /// spelled with AmpAmp.
6343 TL.setAmpLoc(Chunk.Loc);
6344 }
6345 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6346 assert(Chunk.Kind == DeclaratorChunk::Reference);
6347 assert(!Chunk.Ref.LValueRef);
6348 TL.setAmpAmpLoc(Chunk.Loc);
6349 }
6350 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6351 assert(Chunk.Kind == DeclaratorChunk::Array);
6352 TL.setLBracketLoc(Chunk.Loc);
6353 TL.setRBracketLoc(Chunk.EndLoc);
6354 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6355 }
6356 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6357 assert(Chunk.Kind == DeclaratorChunk::Function);
6358 TL.setLocalRangeBegin(Chunk.Loc);
6359 TL.setLocalRangeEnd(Chunk.EndLoc);
6360
6361 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6362 TL.setLParenLoc(FTI.getLParenLoc());
6363 TL.setRParenLoc(FTI.getRParenLoc());
6364 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6365 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6366 TL.setParam(tpi++, Param);
6367 }
6369 }
6370 void VisitParenTypeLoc(ParenTypeLoc TL) {
6371 assert(Chunk.Kind == DeclaratorChunk::Paren);
6372 TL.setLParenLoc(Chunk.Loc);
6373 TL.setRParenLoc(Chunk.EndLoc);
6374 }
6375 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6376 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6377 TL.setKWLoc(Chunk.Loc);
6378 }
6379 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6380 TL.setNameLoc(Chunk.Loc);
6381 }
6382 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6383 TL.setExpansionLoc(Chunk.Loc);
6384 }
6385 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6386 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6387 TL.setNameLoc(Chunk.Loc);
6388 }
6389 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6390 TL.setNameLoc(Chunk.Loc);
6391 }
6392 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6393 fillAtomicQualLoc(TL, Chunk);
6394 }
6395 void
6396 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6397 TL.setNameLoc(Chunk.Loc);
6398 }
6399 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6400 fillMatrixTypeLoc(TL, Chunk.getAttrs());
6401 }
6402
6403 void VisitTypeLoc(TypeLoc TL) {
6404 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6405 }
6406 };
6407} // end anonymous namespace
6408
6412 for (const ParsedAttributesView *Attrs : AttrLists) {
6413 for (const ParsedAttr &AL : *Attrs) {
6414 // Skip invalid or malformed attributes; they did not produce a type.
6415 if (AL.getKind() != ParsedAttr::AT_AddressSpace || AL.isInvalid() ||
6416 AL.getNumArgs() != 1 || !AL.isArgExpr(0))
6417 continue;
6418 DASTL.setAttrNameLoc(AL.getLoc());
6419 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6421 return;
6422 }
6423 }
6424
6425 llvm_unreachable(
6426 "no address_space attribute found at the expected location!");
6427}
6428
6429/// Create and instantiate a TypeSourceInfo with type source information.
6430///
6431/// \param T QualType referring to the type as written in source code.
6432///
6433/// \param ReturnTypeInfo For declarators whose return type does not show
6434/// up in the normal place in the declaration specifiers (such as a C++
6435/// conversion function), this pointer will refer to a type source information
6436/// for that return type.
6437static TypeSourceInfo *
6438GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6439 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6440 Sema &S = State.getSema();
6441 Declarator &D = State.getDeclarator();
6442
6444 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6445
6446 // Handle parameter packs whose type is a pack expansion.
6448 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6449 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6450 }
6451
6452 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6453 // Microsoft property fields can have multiple sizeless array chunks
6454 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6455 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6457 continue;
6458
6459 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6460 // declarator chunk.
6461 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6463 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6464 }
6465
6466 bool HasDesugaredTypeLoc = true;
6467 while (HasDesugaredTypeLoc) {
6468 switch (CurrTL.getTypeLocClass()) {
6469 case TypeLoc::MacroQualified: {
6470 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6471 TL.setExpansionLoc(
6472 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6473 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6474 break;
6475 }
6476
6477 case TypeLoc::Attributed: {
6478 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6479 fillAttributedTypeLoc(TL, State);
6480 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6481 break;
6482 }
6483
6484 case TypeLoc::Adjusted:
6485 case TypeLoc::BTFTagAttributed: {
6486 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6487 break;
6488 }
6489
6490 case TypeLoc::DependentAddressSpace: {
6491 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6492 // An attribute written after the declarator-id appertains to the
6493 // declared entity, not to a chunk, so every attribute list of the
6494 // declarator has to be searched.
6496 &D.getAttributes(),
6499 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6500 break;
6501 }
6502
6503 default:
6504 HasDesugaredTypeLoc = false;
6505 break;
6506 }
6507 }
6508
6509 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6510 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6511 }
6512
6513 // If we have different source information for the return type, use
6514 // that. This really only applies to C++ conversion functions.
6515 if (ReturnTypeInfo) {
6516 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6517 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6518 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6519 } else {
6520 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6521 }
6522
6523 return TInfo;
6524}
6525
6526/// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6528 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6529 // and Sema during declaration parsing. Try deallocating/caching them when
6530 // it's appropriate, instead of allocating them and keeping them around.
6531 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(sizeof(LocInfoType),
6532 alignof(LocInfoType));
6533 new (LocT) LocInfoType(T, TInfo);
6534 assert(LocT->getTypeClass() != T->getTypeClass() &&
6535 "LocInfoType's TypeClass conflicts with an existing Type class");
6536 return ParsedType::make(QualType(LocT, 0));
6537}
6538
6540 const PrintingPolicy &Policy) const {
6541 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6542 " was used directly instead of getting the QualType through"
6543 " GetTypeFromParser");
6544}
6545
6547 // C99 6.7.6: Type names have no identifier. This is already validated by
6548 // the parser.
6549 assert(D.getIdentifier() == nullptr &&
6550 "Type name should have no identifier!");
6551
6553 QualType T = TInfo->getType();
6554 if (D.isInvalidType())
6555 return true;
6556
6557 // Make sure there are no unused decl attributes on the declarator.
6558 // We don't want to do this for ObjC parameters because we're going
6559 // to apply them to the actual parameter declaration.
6560 // Likewise, we don't want to do this for alias declarations, because
6561 // we are actually going to build a declaration from this eventually.
6566
6567 if (getLangOpts().CPlusPlus) {
6568 // Check that there are no default arguments (C++ only).
6570 }
6571
6572 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
6573 const AutoType *AT = TL.getTypePtr();
6574 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
6575 }
6576 return CreateParsedType(T, TInfo);
6577}
6578
6579//===----------------------------------------------------------------------===//
6580// Type Attribute Processing
6581//===----------------------------------------------------------------------===//
6582
6583/// Build an AddressSpace index from a constant expression and diagnose any
6584/// errors related to invalid address_spaces. Returns true on successfully
6585/// building an AddressSpace index.
6586static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6587 const Expr *AddrSpace,
6588 SourceLocation AttrLoc) {
6589 if (!AddrSpace->isValueDependent()) {
6590 std::optional<llvm::APSInt> OptAddrSpace =
6591 AddrSpace->getIntegerConstantExpr(S.Context);
6592 if (!OptAddrSpace) {
6593 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6594 << "'address_space'" << AANT_ArgumentIntegerConstant
6595 << AddrSpace->getSourceRange();
6596 return false;
6597 }
6598 llvm::APSInt &addrSpace = *OptAddrSpace;
6599
6600 // Bounds checking.
6601 if (addrSpace.isSigned()) {
6602 if (addrSpace.isNegative()) {
6603 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6604 << AddrSpace->getSourceRange();
6605 return false;
6606 }
6607 addrSpace.setIsSigned(false);
6608 }
6609
6610 llvm::APSInt max(addrSpace.getBitWidth());
6611 max =
6613
6614 if (addrSpace > max) {
6615 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6616 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6617 return false;
6618 }
6619
6620 ASIdx =
6621 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6622 return true;
6623 }
6624
6625 // Default value for DependentAddressSpaceTypes
6626 ASIdx = LangAS::Default;
6627 return true;
6628}
6629
6631 SourceLocation AttrLoc) {
6632 if (!AddrSpace->isValueDependent()) {
6633 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6634 AttrLoc))
6635 return QualType();
6636
6637 return Context.getAddrSpaceQualType(T, ASIdx);
6638 }
6639
6640 // A check with similar intentions as checking if a type already has an
6641 // address space except for on a dependent types, basically if the
6642 // current type is already a DependentAddressSpaceType then its already
6643 // lined up to have another address space on it and we can't have
6644 // multiple address spaces on the one pointer indirection
6645 if (T->getAs<DependentAddressSpaceType>()) {
6646 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6647 return QualType();
6648 }
6649
6650 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6651}
6652
6654 SourceLocation AttrLoc) {
6655 LangAS ASIdx;
6656 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6657 return QualType();
6658 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6659}
6660
6662 TypeProcessingState &State) {
6663 Sema &S = State.getSema();
6664
6665 // Ensure the argument is a string.
6666 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6667 if (!StrLiteral) {
6668 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6670 Attr.setInvalid();
6671 return;
6672 }
6673
6674 ASTContext &Ctx = S.Context;
6675 StringRef BTFTypeTag = StrLiteral->getString();
6676 Type = State.getBTFTagAttributedType(
6677 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6678}
6679
6680/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6681/// specified type. The attribute contains 1 argument, the id of the address
6682/// space for the type.
6684 const ParsedAttr &Attr,
6685 TypeProcessingState &State) {
6686 Sema &S = State.getSema();
6687
6688 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6689 // qualified by an address-space qualifier."
6690 if (Type->isFunctionType()) {
6691 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6692 Attr.setInvalid();
6693 return;
6694 }
6695
6696 LangAS ASIdx;
6697 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6698
6699 // Check the attribute arguments.
6700 if (Attr.getNumArgs() != 1) {
6701 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6702 << 1;
6703 Attr.setInvalid();
6704 return;
6705 }
6706
6707 Expr *ASArgExpr = Attr.getArgAsExpr(0);
6708 LangAS ASIdx;
6709 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6710 Attr.setInvalid();
6711 return;
6712 }
6713
6714 ASTContext &Ctx = S.Context;
6715 auto *ASAttr =
6716 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6717
6718 // If the expression is not value dependent (not templated), then we can
6719 // apply the address space qualifiers just to the equivalent type.
6720 // Otherwise, we make an AttributedType with the modified and equivalent
6721 // type the same, and wrap it in a DependentAddressSpaceType. When this
6722 // dependent type is resolved, the qualifier is added to the equivalent type
6723 // later.
6724 QualType T;
6725 if (!ASArgExpr->isValueDependent()) {
6726 QualType EquivType =
6727 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6728 if (EquivType.isNull()) {
6729 Attr.setInvalid();
6730 return;
6731 }
6732 T = State.getAttributedType(ASAttr, Type, EquivType);
6733 } else {
6734 T = State.getAttributedType(ASAttr, Type, Type);
6735 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6736 }
6737
6738 if (!T.isNull())
6739 Type = T;
6740 else
6741 Attr.setInvalid();
6742 } else {
6743 // The keyword-based type attributes imply which address space to use.
6744 // The SYCL address space attributes are available in both SYCL host and
6745 // device compilation.
6746 ASIdx =
6747 S.getLangOpts().isSYCL() ? Attr.asSYCLLangAS() : Attr.asOpenCLLangAS();
6748 if (S.getLangOpts().HLSL)
6749 ASIdx = Attr.asHLSLLangAS();
6750
6751 if (ASIdx == LangAS::Default)
6752 llvm_unreachable("Invalid address space");
6753
6754 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6755 Attr.getLoc())) {
6756 Attr.setInvalid();
6757 return;
6758 }
6759
6761 }
6762}
6763
6765 TypeProcessingState &State) {
6766 Sema &S = State.getSema();
6767
6768 // Check for -fexperimental-overflow-behavior-types
6769 if (!S.getLangOpts().OverflowBehaviorTypes) {
6770 S.Diag(Attr.getLoc(), diag::warn_overflow_behavior_attribute_disabled)
6771 << Attr << 1;
6772 Attr.setInvalid();
6773 return;
6774 }
6775
6776 // Check the number of attribute arguments.
6777 if (Attr.getNumArgs() != 1) {
6778 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6779 << Attr << 1;
6780 Attr.setInvalid();
6781 return;
6782 }
6783
6784 // Verify we aren't dealing with an atomic type
6785 if (Type->isAtomicType()) {
6786 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_atomic_type)
6787 << Attr << Type.getAsString() << 0; // 0 for attribute
6788 Attr.setInvalid();
6789 return;
6790 }
6791
6792 // Check that the underlying type is an integer type
6793 if (!Type->isIntegerType()) {
6794 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_non_integer_type)
6795 << Attr << Type.getAsString() << 0; // 0 for attribute
6796 Attr.setInvalid();
6797 return;
6798 }
6799
6800 StringRef KindName = "";
6801 IdentifierInfo *Ident = nullptr;
6802
6803 if (Attr.isArgIdent(0)) {
6804 Ident = Attr.getArgAsIdent(0)->getIdentifierInfo();
6805 KindName = Ident->getName();
6806 }
6807
6808 // Support identifier or string argument types. Failure to provide one of
6809 // these two types results in a diagnostic that hints towards using string
6810 // arguments (either "wrap" or "trap") as this is the most common use
6811 // pattern.
6812 if (!Ident) {
6813 auto *Str = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6814 if (Str)
6815 KindName = Str->getString();
6816 else {
6817 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6819 Attr.setInvalid();
6820 return;
6821 }
6822 }
6823
6824 OverflowBehaviorType::OverflowBehaviorKind Kind;
6825 if (KindName == "wrap") {
6826 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
6827 } else if (KindName == "trap") {
6828 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
6829 } else {
6830 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_unknown_ident)
6831 << KindName << Attr;
6832 Attr.setInvalid();
6833 return;
6834 }
6835
6836 // Check for mixed specifier/attribute usage
6837 const DeclSpec &DS = State.getDeclarator().getDeclSpec();
6838 if (DS.isWrapSpecified() || DS.isTrapSpecified()) {
6839 // We have both specifier and attribute on the same type. If
6840 // OverflowBehaviorKinds are the same we can just warn.
6841 OverflowBehaviorType::OverflowBehaviorKind SpecifierKind =
6842 DS.isWrapSpecified() ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
6843 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
6844
6845 if (SpecifierKind != Kind) {
6846 StringRef SpecifierName = DS.isWrapSpecified() ? "wrap" : "trap";
6847 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors)
6848 << 1 << SpecifierName << KindName;
6849 Attr.setInvalid();
6850 return;
6851 }
6852 S.Diag(Attr.getLoc(), diag::warn_redundant_overflow_behaviors_mixed)
6853 << KindName;
6854 Attr.setInvalid();
6855 return;
6856 }
6857
6858 // Check for conflicting overflow behavior attributes
6859 if (const auto *ExistingOBT = Type->getAs<OverflowBehaviorType>()) {
6860 OverflowBehaviorType::OverflowBehaviorKind ExistingKind =
6861 ExistingOBT->getBehaviorKind();
6862 if (ExistingKind != Kind) {
6863 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors) << 0;
6864 if (Kind == OverflowBehaviorType::OverflowBehaviorKind::Trap) {
6865 Type = State.getOverflowBehaviorType(Kind,
6866 ExistingOBT->getUnderlyingType());
6867 }
6868 return;
6869 }
6870 } else {
6871 Type = State.getOverflowBehaviorType(Kind, Type);
6872 }
6873}
6874
6875/// handleObjCOwnershipTypeAttr - Process an objc_ownership
6876/// attribute on the specified type.
6877///
6878/// Returns 'true' if the attribute was handled.
6879static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6881 bool NonObjCPointer = false;
6882
6883 if (!type->isDependentType() && !type->isUndeducedType()) {
6884 if (const PointerType *ptr = type->getAs<PointerType>()) {
6885 QualType pointee = ptr->getPointeeType();
6886 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6887 return false;
6888 // It is important not to lose the source info that there was an attribute
6889 // applied to non-objc pointer. We will create an attributed type but
6890 // its type will be the same as the original type.
6891 NonObjCPointer = true;
6892 } else if (!type->isObjCRetainableType()) {
6893 return false;
6894 }
6895
6896 // Don't accept an ownership attribute in the declspec if it would
6897 // just be the return type of a block pointer.
6898 if (state.isProcessingDeclSpec()) {
6899 Declarator &D = state.getDeclarator();
6901 /*onlyBlockPointers=*/true))
6902 return false;
6903 }
6904 }
6905
6906 Sema &S = state.getSema();
6907 SourceLocation AttrLoc = attr.getLoc();
6908 if (AttrLoc.isMacroID())
6909 AttrLoc =
6911
6912 if (!attr.isArgIdent(0)) {
6913 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6915 attr.setInvalid();
6916 return true;
6917 }
6918
6919 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
6920 Qualifiers::ObjCLifetime lifetime;
6921 if (II->isStr("none"))
6923 else if (II->isStr("strong"))
6924 lifetime = Qualifiers::OCL_Strong;
6925 else if (II->isStr("weak"))
6926 lifetime = Qualifiers::OCL_Weak;
6927 else if (II->isStr("autoreleasing"))
6929 else {
6930 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6931 attr.setInvalid();
6932 return true;
6933 }
6934
6935 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6936 // outside of ARC mode.
6937 if (!S.getLangOpts().ObjCAutoRefCount &&
6938 lifetime != Qualifiers::OCL_Weak &&
6939 lifetime != Qualifiers::OCL_ExplicitNone) {
6940 return true;
6941 }
6942
6943 SplitQualType underlyingType = type.split();
6944
6945 // Check for redundant/conflicting ownership qualifiers.
6946 if (Qualifiers::ObjCLifetime previousLifetime
6947 = type.getQualifiers().getObjCLifetime()) {
6948 // If it's written directly, that's an error.
6950 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6951 << type;
6952 return true;
6953 }
6954
6955 // Otherwise, if the qualifiers actually conflict, pull sugar off
6956 // and remove the ObjCLifetime qualifiers.
6957 if (previousLifetime != lifetime) {
6958 // It's possible to have multiple local ObjCLifetime qualifiers. We
6959 // can't stop after we reach a type that is directly qualified.
6960 const Type *prevTy = nullptr;
6961 while (!prevTy || prevTy != underlyingType.Ty) {
6962 prevTy = underlyingType.Ty;
6963 underlyingType = underlyingType.getSingleStepDesugaredType();
6964 }
6965 underlyingType.Quals.removeObjCLifetime();
6966 }
6967 }
6968
6969 underlyingType.Quals.addObjCLifetime(lifetime);
6970
6971 if (NonObjCPointer) {
6972 StringRef name = attr.getAttrName()->getName();
6973 switch (lifetime) {
6976 break;
6977 case Qualifiers::OCL_Strong: name = "__strong"; break;
6978 case Qualifiers::OCL_Weak: name = "__weak"; break;
6979 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6980 }
6981 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6983 }
6984
6985 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6986 // because having both 'T' and '__unsafe_unretained T' exist in the type
6987 // system causes unfortunate widespread consistency problems. (For example,
6988 // they're not considered compatible types, and we mangle them identicially
6989 // as template arguments.) These problems are all individually fixable,
6990 // but it's easier to just not add the qualifier and instead sniff it out
6991 // in specific places using isObjCInertUnsafeUnretainedType().
6992 //
6993 // Doing this does means we miss some trivial consistency checks that
6994 // would've triggered in ARC, but that's better than trying to solve all
6995 // the coexistence problems with __unsafe_unretained.
6996 if (!S.getLangOpts().ObjCAutoRefCount &&
6997 lifetime == Qualifiers::OCL_ExplicitNone) {
6998 type = state.getAttributedType(
7000 type, type);
7001 return true;
7002 }
7003
7004 QualType origType = type;
7005 if (!NonObjCPointer)
7006 type = S.Context.getQualifiedType(underlyingType);
7007
7008 // If we have a valid source location for the attribute, use an
7009 // AttributedType instead.
7010 if (AttrLoc.isValid()) {
7011 type = state.getAttributedType(::new (S.Context)
7012 ObjCOwnershipAttr(S.Context, attr, II),
7013 origType, type);
7014 }
7015
7016 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
7017 unsigned diagnostic, QualType type) {
7022 diagnostic, type, /*ignored*/ 0));
7023 } else {
7024 S.Diag(loc, diagnostic);
7025 }
7026 };
7027
7028 // Sometimes, __weak isn't allowed.
7029 if (lifetime == Qualifiers::OCL_Weak &&
7030 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
7031
7032 // Use a specialized diagnostic if the runtime just doesn't support them.
7033 unsigned diagnostic =
7034 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
7035 : diag::err_arc_weak_no_runtime);
7036
7037 // In any case, delay the diagnostic until we know what we're parsing.
7038 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
7039
7040 attr.setInvalid();
7041 return true;
7042 }
7043
7044 // Forbid __weak for class objects marked as
7045 // objc_arc_weak_reference_unavailable
7046 if (lifetime == Qualifiers::OCL_Weak) {
7047 if (const ObjCObjectPointerType *ObjT =
7048 type->getAs<ObjCObjectPointerType>()) {
7049 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
7050 if (Class->isArcWeakrefUnavailable()) {
7051 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
7052 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
7053 diag::note_class_declared);
7054 }
7055 }
7056 }
7057 }
7058
7059 return true;
7060}
7061
7062/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
7063/// attribute on the specified type. Returns true to indicate that
7064/// the attribute was handled, false to indicate that the type does
7065/// not permit the attribute.
7066static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7067 QualType &type) {
7068 Sema &S = state.getSema();
7069
7070 // Delay if this isn't some kind of pointer.
7071 if (!type->isPointerType() &&
7072 !type->isObjCObjectPointerType() &&
7073 !type->isBlockPointerType())
7074 return false;
7075
7076 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7077 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
7078 attr.setInvalid();
7079 return true;
7080 }
7081
7082 // Check the attribute arguments.
7083 if (!attr.isArgIdent(0)) {
7084 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
7086 attr.setInvalid();
7087 return true;
7088 }
7089 Qualifiers::GC GCAttr;
7090 if (attr.getNumArgs() > 1) {
7091 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
7092 << 1;
7093 attr.setInvalid();
7094 return true;
7095 }
7096
7097 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
7098 if (II->isStr("weak"))
7099 GCAttr = Qualifiers::Weak;
7100 else if (II->isStr("strong"))
7101 GCAttr = Qualifiers::Strong;
7102 else {
7103 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
7104 << attr << II;
7105 attr.setInvalid();
7106 return true;
7107 }
7108
7109 QualType origType = type;
7110 type = S.Context.getObjCGCQualType(origType, GCAttr);
7111
7112 // Make an attributed type to preserve the source information.
7113 if (attr.getLoc().isValid())
7114 type = state.getAttributedType(
7115 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
7116
7117 return true;
7118}
7119
7120namespace {
7121 /// A helper class to unwrap a type down to a function for the
7122 /// purposes of applying attributes there.
7123 ///
7124 /// Use:
7125 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
7126 /// if (unwrapped.isFunctionType()) {
7127 /// const FunctionType *fn = unwrapped.get();
7128 /// // change fn somehow
7129 /// T = unwrapped.wrap(fn);
7130 /// }
7131 struct FunctionTypeUnwrapper {
7132 enum WrapKind {
7133 Desugar,
7134 Attributed,
7135 Parens,
7136 Array,
7137 Pointer,
7138 BlockPointer,
7139 Reference,
7140 MemberPointer,
7141 MacroQualified,
7142 };
7143
7144 QualType Original;
7145 const FunctionType *Fn;
7146 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7147
7148 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7149 while (true) {
7150 const Type *Ty = T.getTypePtr();
7151 if (isa<FunctionType>(Ty)) {
7152 Fn = cast<FunctionType>(Ty);
7153 return;
7154 } else if (isa<ParenType>(Ty)) {
7155 T = cast<ParenType>(Ty)->getInnerType();
7156 Stack.push_back(Parens);
7157 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
7159 T = cast<ArrayType>(Ty)->getElementType();
7160 Stack.push_back(Array);
7161 } else if (isa<PointerType>(Ty)) {
7162 T = cast<PointerType>(Ty)->getPointeeType();
7163 Stack.push_back(Pointer);
7164 } else if (isa<BlockPointerType>(Ty)) {
7165 T = cast<BlockPointerType>(Ty)->getPointeeType();
7166 Stack.push_back(BlockPointer);
7167 } else if (isa<MemberPointerType>(Ty)) {
7168 T = cast<MemberPointerType>(Ty)->getPointeeType();
7169 Stack.push_back(MemberPointer);
7170 } else if (isa<ReferenceType>(Ty)) {
7171 T = cast<ReferenceType>(Ty)->getPointeeType();
7172 Stack.push_back(Reference);
7173 } else if (isa<AttributedType>(Ty)) {
7174 T = cast<AttributedType>(Ty)->getEquivalentType();
7175 Stack.push_back(Attributed);
7176 } else if (isa<MacroQualifiedType>(Ty)) {
7177 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
7178 Stack.push_back(MacroQualified);
7179 } else {
7180 const Type *DTy = Ty->getUnqualifiedDesugaredType();
7181 if (Ty == DTy) {
7182 Fn = nullptr;
7183 return;
7184 }
7185
7186 T = QualType(DTy, 0);
7187 Stack.push_back(Desugar);
7188 }
7189 }
7190 }
7191
7192 bool isFunctionType() const { return (Fn != nullptr); }
7193 const FunctionType *get() const { return Fn; }
7194
7195 QualType wrap(Sema &S, const FunctionType *New) {
7196 // If T wasn't modified from the unwrapped type, do nothing.
7197 if (New == get()) return Original;
7198
7199 Fn = New;
7200 return wrap(S.Context, Original, 0);
7201 }
7202
7203 private:
7204 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7205 if (I == Stack.size())
7206 return C.getQualifiedType(Fn, Old.getQualifiers());
7207
7208 // Build up the inner type, applying the qualifiers from the old
7209 // type to the new type.
7210 SplitQualType SplitOld = Old.split();
7211
7212 // As a special case, tail-recurse if there are no qualifiers.
7213 if (SplitOld.Quals.empty())
7214 return wrap(C, SplitOld.Ty, I);
7215 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
7216 }
7217
7218 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7219 if (I == Stack.size()) return QualType(Fn, 0);
7220
7221 switch (static_cast<WrapKind>(Stack[I++])) {
7222 case Desugar:
7223 // This is the point at which we potentially lose source
7224 // information.
7225 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
7226
7227 case Attributed:
7228 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7229
7230 case Parens: {
7231 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7232 return C.getParenType(New);
7233 }
7234
7235 case MacroQualified:
7236 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7237
7238 case Array: {
7239 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7240 QualType New = wrap(C, CAT->getElementType(), I);
7241 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7242 CAT->getSizeModifier(),
7243 CAT->getIndexTypeCVRQualifiers());
7244 }
7245
7246 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7247 QualType New = wrap(C, VAT->getElementType(), I);
7248 return C.getVariableArrayType(New, VAT->getSizeExpr(),
7249 VAT->getSizeModifier(),
7250 VAT->getIndexTypeCVRQualifiers());
7251 }
7252
7253 const auto *IAT = cast<IncompleteArrayType>(Old);
7254 QualType New = wrap(C, IAT->getElementType(), I);
7255 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7256 IAT->getIndexTypeCVRQualifiers());
7257 }
7258
7259 case Pointer: {
7260 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7261 return C.getPointerType(New);
7262 }
7263
7264 case BlockPointer: {
7265 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7266 return C.getBlockPointerType(New);
7267 }
7268
7269 case MemberPointer: {
7270 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7271 QualType New = wrap(C, OldMPT->getPointeeType(), I);
7272 return C.getMemberPointerType(New, OldMPT->getQualifier(),
7273 OldMPT->getMostRecentCXXRecordDecl());
7274 }
7275
7276 case Reference: {
7277 const ReferenceType *OldRef = cast<ReferenceType>(Old);
7278 QualType New = wrap(C, OldRef->getPointeeType(), I);
7279 if (isa<LValueReferenceType>(OldRef))
7280 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7281 else
7282 return C.getRValueReferenceType(New);
7283 }
7284 }
7285
7286 llvm_unreachable("unknown wrapping kind");
7287 }
7288 };
7289} // end anonymous namespace
7290
7291static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7292 ParsedAttr &PAttr, QualType &Type) {
7293 Sema &S = State.getSema();
7294
7295 Attr *A;
7296 switch (PAttr.getKind()) {
7297 default: llvm_unreachable("Unknown attribute kind");
7298 case ParsedAttr::AT_Ptr32:
7300 break;
7301 case ParsedAttr::AT_Ptr64:
7303 break;
7304 case ParsedAttr::AT_SPtr:
7305 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7306 break;
7307 case ParsedAttr::AT_UPtr:
7308 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7309 break;
7310 }
7311
7312 std::bitset<attr::LastAttr> Attrs;
7313 QualType Desugared = Type;
7314 for (;;) {
7315 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7316 Desugared = TT->desugar();
7317 continue;
7318 }
7319 const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7320 if (!AT)
7321 break;
7322 Attrs[AT->getAttrKind()] = true;
7323 Desugared = AT->getModifiedType();
7324 }
7325
7326 // You cannot specify duplicate type attributes, so if the attribute has
7327 // already been applied, flag it.
7328 attr::Kind NewAttrKind = A->getKind();
7329 if (Attrs[NewAttrKind]) {
7330 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7331 return true;
7332 }
7333 Attrs[NewAttrKind] = true;
7334
7335 // You cannot have both __sptr and __uptr on the same type, nor can you
7336 // have __ptr32 and __ptr64.
7337 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7338 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7339 << "'__ptr32'"
7340 << "'__ptr64'" << /*isRegularKeyword=*/0;
7341 return true;
7342 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7343 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7344 << "'__sptr'"
7345 << "'__uptr'" << /*isRegularKeyword=*/0;
7346 return true;
7347 }
7348
7349 // Check the raw (i.e., desugared) Canonical type to see if it
7350 // is a pointer type.
7351 if (!isa<PointerType>(Desugared)) {
7352 // Pointer type qualifiers can only operate on pointer types, but not
7353 // pointer-to-member types.
7355 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7356 else
7357 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7358 return true;
7359 }
7360
7361 // Add address space to type based on its attributes.
7362 LangAS ASIdx = LangAS::Default;
7363 uint64_t PtrWidth =
7365 if (PtrWidth == 32) {
7366 if (Attrs[attr::Ptr64])
7367 ASIdx = LangAS::ptr64;
7368 else if (Attrs[attr::UPtr])
7369 ASIdx = LangAS::ptr32_uptr;
7370 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7371 if (S.Context.getTargetInfo().getTriple().isOSzOS() || Attrs[attr::UPtr])
7372 ASIdx = LangAS::ptr32_uptr;
7373 else
7374 ASIdx = LangAS::ptr32_sptr;
7375 }
7376
7377 QualType Pointee = Type->getPointeeType();
7378 if (ASIdx != LangAS::Default)
7379 Pointee = S.Context.getAddrSpaceQualType(
7380 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7381
7383 S.Context.getPointerType(Pointee), Type.getQualifiers());
7384 Type = State.getAttributedType(A, Type, Equivalent);
7385 return false;
7386}
7387
7388static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7389 QualType &QT, ParsedAttr &PAttr) {
7390 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7391
7392 Sema &S = State.getSema();
7394
7395 std::bitset<attr::LastAttr> Attrs;
7396 attr::Kind NewAttrKind = A->getKind();
7397 const auto *AT = dyn_cast<AttributedType>(QT);
7398 while (AT) {
7399 Attrs[AT->getAttrKind()] = true;
7400 AT = dyn_cast<AttributedType>(AT->getModifiedType());
7401 }
7402
7403 // You cannot specify duplicate type attributes, so if the attribute has
7404 // already been applied, flag it.
7405 if (Attrs[NewAttrKind]) {
7406 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7407 return true;
7408 }
7409
7410 // Check that the type is a function pointer type.
7411 QualType Desugared = QT.getDesugaredType(S.Context);
7412 const auto *Ptr = dyn_cast<PointerType>(Desugared);
7413 if (!Ptr || !Ptr->getPointeeType()->isFunctionType()) {
7414 S.Diag(PAttr.getLoc(), diag::err_attribute_webassembly_funcref);
7415 return true;
7416 }
7417
7418 // Add address space to type based on its attributes.
7420 QualType Pointee = QT->getPointeeType();
7421 Pointee = S.Context.getAddrSpaceQualType(
7422 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7423
7425 S.Context.getPointerType(Pointee), QT.getQualifiers());
7426 QT = State.getAttributedType(A, QT, Equivalent);
7427 return false;
7428}
7429
7430static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL,
7431 QualType &QT, ParsedAttr &PAttr) {
7432 if (TAL == TAL_DeclName)
7433 return;
7434
7435 Sema &S = State.getSema();
7436 auto &D = State.getDeclarator();
7437
7438 // If the attribute appears in declaration specifiers
7439 // it should be handled as a declaration attribute,
7440 // unless it's associated with a type or a function
7441 // prototype (i.e. appears on a parameter or result type).
7442 if (State.isProcessingDeclSpec()) {
7443 if (!(D.isPrototypeContext() ||
7444 D.getContext() == DeclaratorContext::TypeName))
7445 return;
7446
7447 if (auto *chunk = D.getInnermostNonParenChunk()) {
7448 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7449 const_cast<DeclaratorChunk *>(chunk)->getAttrs());
7450 return;
7451 }
7452 }
7453
7454 StringRef Str;
7455 if (!S.checkStringLiteralArgumentAttr(PAttr, 0, Str)) {
7456 PAttr.setInvalid();
7457 return;
7458 }
7459
7460 // If the attribute as attached to a paren move it closer to
7461 // the declarator. This can happen in block declarations when
7462 // an attribute is placed before `^` i.e. `(__attribute__((...)) ^)`.
7463 //
7464 // Note that it's actually invalid to use GNU style attributes
7465 // in a block but such cases are currently handled gracefully
7466 // but the parser and behavior should be consistent between
7467 // cases when attribute appears before/after block's result
7468 // type and inside (^).
7469 if (TAL == TAL_DeclChunk) {
7470 auto chunkIdx = State.getCurrentChunkIndex();
7471 if (chunkIdx >= 1 &&
7472 D.getTypeObject(chunkIdx).Kind == DeclaratorChunk::Paren) {
7473 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7474 D.getTypeObject(chunkIdx - 1).getAttrs());
7475 return;
7476 }
7477 }
7478
7479 auto *A = ::new (S.Context) SwiftAttrAttr(S.Context, PAttr, Str);
7480 QT = State.getAttributedType(A, QT, QT);
7481 PAttr.setUsedAsTypeAttr();
7482}
7483
7484/// Rebuild an attributed type without the nullability attribute on it.
7486 QualType Type) {
7487 auto Attributed = dyn_cast<AttributedType>(Type.getTypePtr());
7488 if (!Attributed)
7489 return Type;
7490
7491 // Skip the nullability attribute; we're done.
7492 if (Attributed->getImmediateNullability())
7493 return Attributed->getModifiedType();
7494
7495 // Build the modified type.
7497 Ctx, Attributed->getModifiedType());
7498 assert(Modified.getTypePtr() != Attributed->getModifiedType().getTypePtr());
7499 return Ctx.getAttributedType(Attributed->getAttrKind(), Modified,
7500 Attributed->getEquivalentType(),
7501 Attributed->getAttr());
7502}
7503
7504/// Map a nullability attribute kind to a nullability kind.
7506 switch (kind) {
7507 case ParsedAttr::AT_TypeNonNull:
7509
7510 case ParsedAttr::AT_TypeNullable:
7512
7513 case ParsedAttr::AT_TypeNullableResult:
7515
7516 case ParsedAttr::AT_TypeNullUnspecified:
7518
7519 default:
7520 llvm_unreachable("not a nullability attribute kind");
7521 }
7522}
7523
7525 Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT,
7526 NullabilityKind Nullability, SourceLocation NullabilityLoc,
7527 bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting) {
7528 bool Implicit = (State == nullptr);
7529 if (!Implicit)
7530 recordNullabilitySeen(S, NullabilityLoc);
7531
7532 // Check for existing nullability attributes on the type.
7533 QualType Desugared = QT;
7534 while (auto *Attributed = dyn_cast<AttributedType>(Desugared.getTypePtr())) {
7535 // Check whether there is already a null
7536 if (auto ExistingNullability = Attributed->getImmediateNullability()) {
7537 // Duplicated nullability.
7538 if (Nullability == *ExistingNullability) {
7539 if (Implicit)
7540 break;
7541
7542 S.Diag(NullabilityLoc, diag::warn_nullability_duplicate)
7543 << DiagNullabilityKind(Nullability, IsContextSensitive)
7544 << FixItHint::CreateRemoval(NullabilityLoc);
7545
7546 break;
7547 }
7548
7549 if (!OverrideExisting) {
7550 // Conflicting nullability.
7551 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7552 << DiagNullabilityKind(Nullability, IsContextSensitive)
7553 << DiagNullabilityKind(*ExistingNullability, false);
7554 return true;
7555 }
7556
7557 // Rebuild the attributed type, dropping the existing nullability.
7559 }
7560
7561 Desugared = Attributed->getModifiedType();
7562 }
7563
7564 // If there is already a different nullability specifier, complain.
7565 // This (unlike the code above) looks through typedefs that might
7566 // have nullability specifiers on them, which means we cannot
7567 // provide a useful Fix-It.
7568 if (auto ExistingNullability = Desugared->getNullability()) {
7569 if (Nullability != *ExistingNullability && !Implicit) {
7570 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7571 << DiagNullabilityKind(Nullability, IsContextSensitive)
7572 << DiagNullabilityKind(*ExistingNullability, false);
7573
7574 // Try to find the typedef with the existing nullability specifier.
7575 if (auto TT = Desugared->getAs<TypedefType>()) {
7576 TypedefNameDecl *typedefDecl = TT->getDecl();
7577 QualType underlyingType = typedefDecl->getUnderlyingType();
7578 if (auto typedefNullability =
7579 AttributedType::stripOuterNullability(underlyingType)) {
7580 if (*typedefNullability == *ExistingNullability) {
7581 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7582 << DiagNullabilityKind(*ExistingNullability, false);
7583 }
7584 }
7585 }
7586
7587 return true;
7588 }
7589 }
7590
7591 // If this definitely isn't a pointer type, reject the specifier.
7592 if (!Desugared->canHaveNullability() &&
7593 !(AllowOnArrayType && Desugared->isArrayType())) {
7594 if (!Implicit)
7595 S.Diag(NullabilityLoc, diag::err_nullability_nonpointer)
7596 << DiagNullabilityKind(Nullability, IsContextSensitive) << QT;
7597
7598 return true;
7599 }
7600
7601 // For the context-sensitive keywords/Objective-C property
7602 // attributes, require that the type be a single-level pointer.
7603 if (IsContextSensitive) {
7604 // Make sure that the pointee isn't itself a pointer type.
7605 const Type *pointeeType = nullptr;
7606 if (Desugared->isArrayType())
7608 else if (Desugared->isAnyPointerType())
7609 pointeeType = Desugared->getPointeeType().getTypePtr();
7610
7611 if (pointeeType && (pointeeType->isAnyPointerType() ||
7612 pointeeType->isObjCObjectPointerType() ||
7613 pointeeType->isMemberPointerType())) {
7614 S.Diag(NullabilityLoc, diag::err_nullability_cs_multilevel)
7615 << DiagNullabilityKind(Nullability, true) << QT;
7616 S.Diag(NullabilityLoc, diag::note_nullability_type_specifier)
7617 << DiagNullabilityKind(Nullability, false) << QT
7618 << FixItHint::CreateReplacement(NullabilityLoc,
7619 getNullabilitySpelling(Nullability));
7620 return true;
7621 }
7622 }
7623
7624 // Form the attributed type.
7625 if (State) {
7626 assert(PAttr);
7627 Attr *A = createNullabilityAttr(S.Context, *PAttr, Nullability);
7628 QT = State->getAttributedType(A, QT, QT);
7629 } else {
7630 QT = S.Context.getAttributedType(Nullability, QT, QT);
7631 }
7632 return false;
7633}
7634
7635static bool CheckNullabilityTypeSpecifier(TypeProcessingState &State,
7637 bool AllowOnArrayType) {
7639 SourceLocation NullabilityLoc = Attr.getLoc();
7640 bool IsContextSensitive = Attr.isContextSensitiveKeywordAttribute();
7641
7642 return CheckNullabilityTypeSpecifier(State.getSema(), &State, &Attr, Type,
7643 Nullability, NullabilityLoc,
7644 IsContextSensitive, AllowOnArrayType,
7645 /*overrideExisting*/ false);
7646}
7647
7649 NullabilityKind Nullability,
7650 SourceLocation DiagLoc,
7651 bool AllowArrayTypes,
7652 bool OverrideExisting) {
7654 *this, nullptr, nullptr, Type, Nullability, DiagLoc,
7655 /*isContextSensitive*/ false, AllowArrayTypes, OverrideExisting);
7656}
7657
7659 QualType T = VD->getType();
7660
7661 // Check that the variable's type can fit in the specified address space. This
7662 // is determined by how far a pointer in that address space can reach.
7663 llvm::APInt MaxSizeForAddrSpace =
7664 llvm::APInt::getMaxValue(Context.getTargetInfo().getPointerWidth(AS));
7665 std::optional<CharUnits> TSizeInChars = Context.getTypeSizeInCharsIfKnown(T);
7666 if (TSizeInChars && static_cast<uint64_t>(TSizeInChars->getQuantity()) >
7667 MaxSizeForAddrSpace.getZExtValue()) {
7668 Diag(VD->getLocation(), diag::err_type_too_large_for_address_space)
7669 << T << MaxSizeForAddrSpace;
7670 return false;
7671 }
7672
7673 return true;
7674}
7675
7676/// Check the application of the Objective-C '__kindof' qualifier to
7677/// the given type.
7678static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7679 ParsedAttr &attr) {
7680 Sema &S = state.getSema();
7681
7683 // Build the attributed type to record where __kindof occurred.
7684 type = state.getAttributedType(
7686 return false;
7687 }
7688
7689 // Find out if it's an Objective-C object or object pointer type;
7690 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7691 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7692 : type->getAs<ObjCObjectType>();
7693
7694 // If not, we can't apply __kindof.
7695 if (!objType) {
7696 // FIXME: Handle dependent types that aren't yet object types.
7697 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7698 << type;
7699 return true;
7700 }
7701
7702 // Rebuild the "equivalent" type, which pushes __kindof down into
7703 // the object type.
7704 // There is no need to apply kindof on an unqualified id type.
7705 QualType equivType = S.Context.getObjCObjectType(
7706 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7707 objType->getProtocols(),
7708 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7709
7710 // If we started with an object pointer type, rebuild it.
7711 if (ptrType) {
7712 equivType = S.Context.getObjCObjectPointerType(equivType);
7713 if (auto nullability = type->getNullability()) {
7714 // We create a nullability attribute from the __kindof attribute.
7715 // Make sure that will make sense.
7716 assert(attr.getAttributeSpellingListIndex() == 0 &&
7717 "multiple spellings for __kindof?");
7718 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7719 A->setImplicit(true);
7720 equivType = state.getAttributedType(A, equivType, equivType);
7721 }
7722 }
7723
7724 // Build the attributed type to record where __kindof occurred.
7725 type = state.getAttributedType(
7727 return false;
7728}
7729
7730/// Distribute a nullability type attribute that cannot be applied to
7731/// the type specifier to a pointer, block pointer, or member pointer
7732/// declarator, complaining if necessary.
7733///
7734/// \returns true if the nullability annotation was distributed, false
7735/// otherwise.
7736static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7738 Declarator &declarator = state.getDeclarator();
7739
7740 /// Attempt to move the attribute to the specified chunk.
7741 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7742 // If there is already a nullability attribute there, don't add
7743 // one.
7744 if (hasNullabilityAttr(chunk.getAttrs()))
7745 return false;
7746
7747 // Complain about the nullability qualifier being in the wrong
7748 // place.
7749 enum {
7750 PK_Pointer,
7751 PK_BlockPointer,
7752 PK_MemberPointer,
7753 PK_FunctionPointer,
7754 PK_MemberFunctionPointer,
7755 } pointerKind
7756 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7757 : PK_Pointer)
7758 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7759 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7760
7761 auto diag = state.getSema().Diag(attr.getLoc(),
7762 diag::warn_nullability_declspec)
7764 attr.isContextSensitiveKeywordAttribute())
7765 << type
7766 << static_cast<unsigned>(pointerKind);
7767
7768 // FIXME: MemberPointer chunks don't carry the location of the *.
7769 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7772 state.getSema().getPreprocessor().getLocForEndOfToken(
7773 chunk.Loc),
7774 " " + attr.getAttrName()->getName().str() + " ");
7775 }
7776
7777 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7778 chunk.getAttrs());
7779 return true;
7780 };
7781
7782 // Move it to the outermost pointer, member pointer, or block
7783 // pointer declarator.
7784 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7785 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7786 switch (chunk.Kind) {
7790 return moveToChunk(chunk, false);
7791
7794 continue;
7795
7797 // Try to move past the return type to a function/block/member
7798 // function pointer.
7800 declarator, i,
7801 /*onlyBlockPointers=*/false)) {
7802 return moveToChunk(*dest, true);
7803 }
7804
7805 return false;
7806
7807 // Don't walk through these.
7810 return false;
7811 }
7812 }
7813
7814 return false;
7815}
7816
7818 assert(!Attr.isInvalid());
7819 switch (Attr.getKind()) {
7820 default:
7821 llvm_unreachable("not a calling convention attribute");
7822 case ParsedAttr::AT_CDecl:
7823 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7824 case ParsedAttr::AT_FastCall:
7826 case ParsedAttr::AT_StdCall:
7828 case ParsedAttr::AT_ThisCall:
7830 case ParsedAttr::AT_RegCall:
7832 case ParsedAttr::AT_Pascal:
7834 case ParsedAttr::AT_SwiftCall:
7836 case ParsedAttr::AT_SwiftAsyncCall:
7838 case ParsedAttr::AT_VectorCall:
7840 case ParsedAttr::AT_AArch64VectorPcs:
7842 case ParsedAttr::AT_AArch64SVEPcs:
7844 case ParsedAttr::AT_ArmStreaming:
7846 case ParsedAttr::AT_Pcs: {
7847 // The attribute may have had a fixit applied where we treated an
7848 // identifier as a string literal. The contents of the string are valid,
7849 // but the form may not be.
7850 StringRef Str;
7851 if (Attr.isArgExpr(0))
7852 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7853 else
7854 Str = Attr.getArgAsIdent(0)->getIdentifierInfo()->getName();
7855 PcsAttr::PCSType Type;
7856 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7857 llvm_unreachable("already validated the attribute");
7858 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7859 }
7860 case ParsedAttr::AT_IntelOclBicc:
7862 case ParsedAttr::AT_MSABI:
7863 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7864 case ParsedAttr::AT_SysVABI:
7866 case ParsedAttr::AT_PreserveMost:
7868 case ParsedAttr::AT_PreserveAll:
7870 case ParsedAttr::AT_M68kRTD:
7872 case ParsedAttr::AT_PreserveNone:
7874 case ParsedAttr::AT_RISCVVectorCC:
7876 case ParsedAttr::AT_RISCVVLSCC: {
7877 // If the riscv_abi_vlen doesn't have any argument, we set set it to default
7878 // value 128.
7879 unsigned ABIVLen = 128;
7880 if (Attr.getNumArgs()) {
7881 std::optional<llvm::APSInt> MaybeABIVLen =
7882 Attr.getArgAsExpr(0)->getIntegerConstantExpr(Ctx);
7883 if (!MaybeABIVLen)
7884 llvm_unreachable("Invalid RISC-V ABI VLEN");
7885 ABIVLen = MaybeABIVLen->getZExtValue();
7886 }
7887
7888 return ::new (Ctx) RISCVVLSCCAttr(Ctx, Attr, ABIVLen);
7889 }
7890 }
7891 llvm_unreachable("unexpected attribute kind!");
7892}
7893
7894std::optional<FunctionEffectMode>
7895Sema::ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName) {
7896 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent())
7898
7899 std::optional<llvm::APSInt> ConditionValue =
7901 if (!ConditionValue) {
7902 // FIXME: err_attribute_argument_type doesn't quote the attribute
7903 // name but needs to; users are inconsistent.
7904 Diag(CondExpr->getExprLoc(), diag::err_attribute_argument_type)
7905 << AttributeName << AANT_ArgumentIntegerConstant
7906 << CondExpr->getSourceRange();
7907 return std::nullopt;
7908 }
7909 return !ConditionValue->isZero() ? FunctionEffectMode::True
7911}
7912
7913static bool
7914handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState,
7915 ParsedAttr &PAttr, QualType &QT,
7916 FunctionTypeUnwrapper &Unwrapped) {
7917 // Delay if this is not a function type.
7918 if (!Unwrapped.isFunctionType())
7919 return false;
7920
7921 Sema &S = TPState.getSema();
7922
7923 // Require FunctionProtoType.
7924 auto *FPT = Unwrapped.get()->getAs<FunctionProtoType>();
7925 if (FPT == nullptr) {
7926 S.Diag(PAttr.getLoc(), diag::err_func_with_effects_no_prototype)
7927 << PAttr.getAttrName()->getName();
7928 return true;
7929 }
7930
7931 // Parse the new attribute.
7932 // non/blocking or non/allocating? Or conditional (computed)?
7933 bool IsNonBlocking = PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7934 PAttr.getKind() == ParsedAttr::AT_Blocking;
7935
7937 Expr *CondExpr = nullptr; // only valid if dependent
7938
7939 if (PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7940 PAttr.getKind() == ParsedAttr::AT_NonAllocating) {
7941 if (!PAttr.checkAtMostNumArgs(S, 1)) {
7942 PAttr.setInvalid();
7943 return true;
7944 }
7945
7946 // Parse the condition, if any.
7947 if (PAttr.getNumArgs() == 1) {
7948 CondExpr = PAttr.getArgAsExpr(0);
7949 std::optional<FunctionEffectMode> MaybeMode =
7950 S.ActOnEffectExpression(CondExpr, PAttr.getAttrName()->getName());
7951 if (!MaybeMode) {
7952 PAttr.setInvalid();
7953 return true;
7954 }
7955 NewMode = *MaybeMode;
7956 if (NewMode != FunctionEffectMode::Dependent)
7957 CondExpr = nullptr;
7958 } else {
7959 NewMode = FunctionEffectMode::True;
7960 }
7961 } else {
7962 // This is the `blocking` or `allocating` attribute.
7963 if (S.CheckAttrNoArgs(PAttr)) {
7964 // The attribute has been marked invalid.
7965 return true;
7966 }
7967 NewMode = FunctionEffectMode::False;
7968 }
7969
7970 const FunctionEffect::Kind FEKind =
7971 (NewMode == FunctionEffectMode::False)
7972 ? (IsNonBlocking ? FunctionEffect::Kind::Blocking
7974 : (IsNonBlocking ? FunctionEffect::Kind::NonBlocking
7976 const FunctionEffectWithCondition NewEC{FunctionEffect(FEKind),
7977 EffectConditionExpr(CondExpr)};
7978
7979 if (S.diagnoseConflictingFunctionEffect(FPT->getFunctionEffects(), NewEC,
7980 PAttr.getLoc())) {
7981 PAttr.setInvalid();
7982 return true;
7983 }
7984
7985 // Add the effect to the FunctionProtoType.
7986 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7989 [[maybe_unused]] bool Success = FX.insert(NewEC, Errs);
7990 assert(Success && "effect conflicts should have been diagnosed above");
7992
7993 QualType NewType = S.Context.getFunctionType(FPT->getReturnType(),
7994 FPT->getParamTypes(), EPI);
7995 QT = Unwrapped.wrap(S, NewType->getAs<FunctionType>());
7996 return true;
7997}
7998
7999static bool checkMutualExclusion(TypeProcessingState &state,
8002 AttributeCommonInfo::Kind OtherKind) {
8003 auto OtherAttr = llvm::find_if(
8004 state.getCurrentAttributes(),
8005 [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
8006 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid())
8007 return false;
8008
8009 Sema &S = state.getSema();
8010 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
8011 << *OtherAttr << Attr
8012 << (OtherAttr->isRegularKeywordAttribute() ||
8014 S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute);
8015 Attr.setInvalid();
8016 return true;
8017}
8018
8021 ParsedAttr &Attr) {
8022 if (!Attr.getNumArgs()) {
8023 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
8024 Attr.setInvalid();
8025 return true;
8026 }
8027
8028 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
8029 StringRef StateName;
8030 SourceLocation LiteralLoc;
8031 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
8032 return true;
8033
8034 if (StateName != "sme_za_state") {
8035 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
8036 Attr.setInvalid();
8037 return true;
8038 }
8039
8040 if (EPI.AArch64SMEAttributes &
8042 S.Diag(Attr.getLoc(), diag::err_conflicting_attributes_arm_agnostic);
8043 Attr.setInvalid();
8044 return true;
8045 }
8046
8048 }
8049
8050 return false;
8051}
8052
8057 if (!Attr.getNumArgs()) {
8058 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
8059 Attr.setInvalid();
8060 return true;
8061 }
8062
8063 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
8064 StringRef StateName;
8065 SourceLocation LiteralLoc;
8066 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
8067 return true;
8068
8069 unsigned Shift;
8070 FunctionType::ArmStateValue ExistingState;
8071 if (StateName == "za") {
8074 } else if (StateName == "zt0") {
8077 } else {
8078 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
8079 Attr.setInvalid();
8080 return true;
8081 }
8082
8084 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_agnostic);
8085 Attr.setInvalid();
8086 return true;
8087 }
8088
8089 // __arm_in(S), __arm_out(S), __arm_inout(S) and __arm_preserves(S)
8090 // are all mutually exclusive for the same S, so check if there are
8091 // conflicting attributes.
8092 if (ExistingState != FunctionType::ARM_None && ExistingState != State) {
8093 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_state)
8094 << StateName;
8095 Attr.setInvalid();
8096 return true;
8097 }
8098
8100 (FunctionType::AArch64SMETypeAttributes)((State << Shift)));
8101 }
8102 return false;
8103}
8104
8105/// Process an individual function attribute. Returns true to
8106/// indicate that the attribute was handled, false if it wasn't.
8107static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
8109 Sema &S = state.getSema();
8110
8111 FunctionTypeUnwrapper unwrapped(S, type);
8112
8113 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
8114 if (S.CheckAttrNoArgs(attr))
8115 return true;
8116
8117 // Delay if this is not a function type.
8118 if (!unwrapped.isFunctionType())
8119 return false;
8120
8121 // Otherwise we can process right away.
8122 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
8123 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8124 return true;
8125 }
8126
8127 if (attr.getKind() == ParsedAttr::AT_CFIUncheckedCallee) {
8128 // Delay if this is not a prototyped function type.
8129 if (!unwrapped.isFunctionType())
8130 return false;
8131
8132 if (!unwrapped.get()->isFunctionProtoType()) {
8133 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
8134 << attr << attr.isRegularKeywordAttribute()
8136 attr.setInvalid();
8137 return true;
8138 }
8139
8140 const auto *FPT = unwrapped.get()->getAs<FunctionProtoType>();
8142 FPT->getReturnType(), FPT->getParamTypes(),
8143 FPT->getExtProtoInfo().withCFIUncheckedCallee(true));
8144 type = unwrapped.wrap(S, cast<FunctionType>(type.getTypePtr()));
8145 return true;
8146 }
8147
8148 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
8149 // Delay if this is not a function type.
8150 if (!unwrapped.isFunctionType())
8151 return false;
8152
8153 // Ignore if we don't have CMSE enabled.
8154 if (!S.getLangOpts().Cmse) {
8155 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
8156 attr.setInvalid();
8157 return true;
8158 }
8159
8160 // Otherwise we can process right away.
8162 unwrapped.get()->getExtInfo().withCmseNSCall(true);
8163 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8164 return true;
8165 }
8166
8167 // ns_returns_retained is not always a type attribute, but if we got
8168 // here, we're treating it as one right now.
8169 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
8170 if (attr.getNumArgs()) return true;
8171
8172 // Delay if this is not a function type.
8173 if (!unwrapped.isFunctionType())
8174 return false;
8175
8176 // Check whether the return type is reasonable.
8178 attr.getLoc(), unwrapped.get()->getReturnType()))
8179 return true;
8180
8181 // Only actually change the underlying type in ARC builds.
8182 QualType origType = type;
8183 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
8185 = unwrapped.get()->getExtInfo().withProducesResult(true);
8186 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8187 }
8188 type = state.getAttributedType(
8190 origType, type);
8191 return true;
8192 }
8193
8194 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
8196 return true;
8197
8198 // Delay if this is not a function type.
8199 if (!unwrapped.isFunctionType())
8200 return false;
8201
8203 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
8204 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8205 return true;
8206 }
8207
8208 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
8209 if (!S.getLangOpts().CFProtectionBranch) {
8210 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
8211 attr.setInvalid();
8212 return true;
8213 }
8214
8216 return true;
8217
8218 // If this is not a function type, warning will be asserted by subject
8219 // check.
8220 if (!unwrapped.isFunctionType())
8221 return true;
8222
8224 unwrapped.get()->getExtInfo().withNoCfCheck(true);
8225 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8226 return true;
8227 }
8228
8229 if (attr.getKind() == ParsedAttr::AT_Regparm) {
8230 unsigned value;
8231 if (S.CheckRegparmAttr(attr, value))
8232 return true;
8233
8234 // Delay if this is not a function type.
8235 if (!unwrapped.isFunctionType())
8236 return false;
8237
8238 // Diagnose regparm with fastcall.
8239 const FunctionType *fn = unwrapped.get();
8240 CallingConv CC = fn->getCallConv();
8241 if (CC == CC_X86FastCall) {
8242 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8243 << FunctionType::getNameForCallConv(CC) << "regparm"
8244 << attr.isRegularKeywordAttribute();
8245 attr.setInvalid();
8246 return true;
8247 }
8248
8250 unwrapped.get()->getExtInfo().withRegParm(value);
8251 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8252 return true;
8253 }
8254
8255 if (attr.getKind() == ParsedAttr::AT_CFISalt) {
8256 if (attr.getNumArgs() != 1)
8257 return true;
8258
8259 StringRef Argument;
8260 if (!S.checkStringLiteralArgumentAttr(attr, 0, Argument))
8261 return true;
8262
8263 // Delay if this is not a function type.
8264 if (!unwrapped.isFunctionType())
8265 return false;
8266
8267 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8268 if (!FnTy) {
8269 S.Diag(attr.getLoc(), diag::err_attribute_wrong_decl_type)
8270 << attr << attr.isRegularKeywordAttribute()
8272 attr.setInvalid();
8273 return true;
8274 }
8275
8276 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8277 EPI.ExtraAttributeInfo.CFISalt = Argument;
8278
8279 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8280 FnTy->getParamTypes(), EPI);
8281 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8282 return true;
8283 }
8284
8285 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8286 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible ||
8287 attr.getKind() == ParsedAttr::AT_ArmPreserves ||
8288 attr.getKind() == ParsedAttr::AT_ArmIn ||
8289 attr.getKind() == ParsedAttr::AT_ArmOut ||
8290 attr.getKind() == ParsedAttr::AT_ArmInOut ||
8291 attr.getKind() == ParsedAttr::AT_ArmAgnostic) {
8292 if (S.CheckAttrTarget(attr))
8293 return true;
8294
8295 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8296 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible)
8297 if (S.CheckAttrNoArgs(attr))
8298 return true;
8299
8300 if (!unwrapped.isFunctionType())
8301 return false;
8302
8303 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8304 if (!FnTy) {
8305 // SME ACLE attributes are not supported on K&R-style unprototyped C
8306 // functions.
8307 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
8308 << attr << attr.isRegularKeywordAttribute()
8310 attr.setInvalid();
8311 return false;
8312 }
8313
8314 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8315 switch (attr.getKind()) {
8316 case ParsedAttr::AT_ArmStreaming:
8317 if (checkMutualExclusion(state, EPI, attr,
8318 ParsedAttr::AT_ArmStreamingCompatible))
8319 return true;
8321 break;
8322 case ParsedAttr::AT_ArmStreamingCompatible:
8323 if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming))
8324 return true;
8326 break;
8327 case ParsedAttr::AT_ArmPreserves:
8329 return true;
8330 break;
8331 case ParsedAttr::AT_ArmIn:
8333 return true;
8334 break;
8335 case ParsedAttr::AT_ArmOut:
8337 return true;
8338 break;
8339 case ParsedAttr::AT_ArmInOut:
8341 return true;
8342 break;
8343 case ParsedAttr::AT_ArmAgnostic:
8344 if (handleArmAgnosticAttribute(S, EPI, attr))
8345 return true;
8346 break;
8347 default:
8348 llvm_unreachable("Unsupported attribute");
8349 }
8350
8351 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8352 FnTy->getParamTypes(), EPI);
8353 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8354 return true;
8355 }
8356
8357 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
8358 // Delay if this is not a function type.
8359 if (!unwrapped.isFunctionType())
8360 return false;
8361
8362 if (S.CheckAttrNoArgs(attr)) {
8363 attr.setInvalid();
8364 return true;
8365 }
8366
8367 // Otherwise we can process right away.
8368 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
8369
8370 // MSVC ignores nothrow if it is in conflict with an explicit exception
8371 // specification.
8372 if (Proto->hasExceptionSpec()) {
8373 switch (Proto->getExceptionSpecType()) {
8374 case EST_None:
8375 llvm_unreachable("This doesn't have an exception spec!");
8376
8377 case EST_DynamicNone:
8378 case EST_BasicNoexcept:
8379 case EST_NoexceptTrue:
8380 case EST_NoThrow:
8381 // Exception spec doesn't conflict with nothrow, so don't warn.
8382 [[fallthrough]];
8383 case EST_Unparsed:
8384 case EST_Uninstantiated:
8386 case EST_Unevaluated:
8387 // We don't have enough information to properly determine if there is a
8388 // conflict, so suppress the warning.
8389 break;
8390 case EST_Dynamic:
8391 case EST_MSAny:
8392 case EST_NoexceptFalse:
8393 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
8394 break;
8395 }
8396 return true;
8397 }
8398
8399 type = unwrapped.wrap(
8400 S, S.Context
8402 QualType{Proto, 0},
8404 ->getAs<FunctionType>());
8405 return true;
8406 }
8407
8408 if (attr.getKind() == ParsedAttr::AT_NonBlocking ||
8409 attr.getKind() == ParsedAttr::AT_NonAllocating ||
8410 attr.getKind() == ParsedAttr::AT_Blocking ||
8411 attr.getKind() == ParsedAttr::AT_Allocating) {
8412 return handleNonBlockingNonAllocatingTypeAttr(state, attr, type, unwrapped);
8413 }
8414
8415 // Delay if the type didn't work out to a function.
8416 if (!unwrapped.isFunctionType()) return false;
8417
8418 // Otherwise, a calling convention.
8419 CallingConv CC;
8420 if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/nullptr, CFT))
8421 return true;
8422
8423 const FunctionType *fn = unwrapped.get();
8424 CallingConv CCOld = fn->getCallConv();
8425 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
8426
8427 if (CCOld != CC) {
8428 // Error out on when there's already an attribute on the type
8429 // and the CCs don't match.
8431 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8434 << attr.isRegularKeywordAttribute();
8435 attr.setInvalid();
8436 return true;
8437 }
8438 }
8439
8440 // Diagnose use of variadic functions with calling conventions that
8441 // don't support them (e.g. because they're callee-cleanup).
8442 // We delay warning about this on unprototyped function declarations
8443 // until after redeclaration checking, just in case we pick up a
8444 // prototype that way. And apparently we also "delay" warning about
8445 // unprototyped function types in general, despite not necessarily having
8446 // much ability to diagnose it later.
8447 if (!supportsVariadicCall(CC)) {
8448 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
8449 if (FnP && FnP->isVariadic()) {
8450 // stdcall and fastcall are ignored with a warning for GCC and MS
8451 // compatibility.
8452 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
8453 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
8456
8457 attr.setInvalid();
8458 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
8460 }
8461 }
8462
8463 // Also diagnose fastcall with regparm.
8464 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
8465 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8467 << attr.isRegularKeywordAttribute();
8468 attr.setInvalid();
8469 return true;
8470 }
8471
8472 // Modify the CC from the wrapped function type, wrap it all back, and then
8473 // wrap the whole thing in an AttributedType as written. The modified type
8474 // might have a different CC if we ignored the attribute.
8476 if (CCOld == CC) {
8477 Equivalent = type;
8478 } else {
8479 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
8480 Equivalent =
8481 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8482 }
8483 type = state.getAttributedType(CCAttr, type, Equivalent);
8484 return true;
8485}
8486
8488 const AttributedType *AT;
8489
8490 // Stop if we'd be stripping off a typedef sugar node to reach the
8491 // AttributedType.
8492 while ((AT = T->getAs<AttributedType>()) &&
8493 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
8494 if (AT->isCallingConv())
8495 return true;
8496 T = AT->getModifiedType();
8497 }
8498 return false;
8499}
8500
8501void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
8502 bool IsCtorOrDtor, SourceLocation Loc) {
8503 FunctionTypeUnwrapper Unwrapped(*this, T);
8504 const FunctionType *FT = Unwrapped.get();
8505 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
8506 cast<FunctionProtoType>(FT)->isVariadic());
8507 CallingConv CurCC = FT->getCallConv();
8508 CallingConv ToCC =
8509 Context.getDefaultCallingConvention(IsVariadic, HasThisPointer);
8510
8511 if (CurCC == ToCC)
8512 return;
8513
8514 // MS compiler ignores explicit calling convention attributes on structors. We
8515 // should do the same.
8516 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
8517 // Issue a warning on ignored calling convention -- except of __stdcall.
8518 // Again, this is what MS compiler does.
8519 if (CurCC != CC_X86StdCall)
8520 Diag(Loc, diag::warn_cconv_unsupported)
8523 // Default adjustment.
8524 } else {
8525 // Only adjust types with the default convention. For example, on Windows
8526 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8527 // __thiscall type to __cdecl for static methods.
8528 CallingConv DefaultCC =
8529 Context.getDefaultCallingConvention(IsVariadic, !HasThisPointer);
8530
8531 if (CurCC != DefaultCC)
8532 return;
8533
8535 return;
8536 }
8537
8538 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
8539 QualType Wrapped = Unwrapped.wrap(*this, FT);
8540 T = Context.getAdjustedType(T, Wrapped);
8541}
8542
8543/// HandleVectorSizeAttribute - this attribute is only applicable to integral
8544/// and float scalars, although arrays, pointers, and function return values are
8545/// allowed in conjunction with this construct. Aggregates with this attribute
8546/// are invalid, even if they are of the same size as a corresponding scalar.
8547/// The raw attribute should contain precisely 1 argument, the vector size for
8548/// the variable, measured in bytes. If curType and rawAttr are well formed,
8549/// this routine will return a new vector type.
8550static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8551 Sema &S) {
8552 // Check the attribute arguments.
8553 if (Attr.getNumArgs() != 1) {
8554 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8555 << 1;
8556 Attr.setInvalid();
8557 return;
8558 }
8559
8560 Expr *SizeExpr = Attr.getArgAsExpr(0);
8561 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
8562 if (!T.isNull())
8563 CurType = T;
8564 else
8565 Attr.setInvalid();
8566}
8567
8568/// Process the OpenCL-like ext_vector_type attribute when it occurs on
8569/// a type.
8571 Sema &S) {
8572 Expr *SizeExpr = Attr.getArgAsExpr(0);
8573 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
8574 if (!T.isNull())
8575 CurType = T;
8576}
8577
8578static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) {
8579 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8580 if (!BTy)
8581 return false;
8582
8583 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8584
8585 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8586 // now.
8587 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8588 Triple.getArch() == llvm::Triple::aarch64_32 ||
8589 Triple.getArch() == llvm::Triple::aarch64_be;
8590 if (VecKind == VectorKind::NeonPoly) {
8591 if (IsPolyUnsigned) {
8592 // AArch64 polynomial vectors are unsigned.
8593 return BTy->getKind() == BuiltinType::UChar ||
8594 BTy->getKind() == BuiltinType::UShort ||
8595 BTy->getKind() == BuiltinType::ULong ||
8596 BTy->getKind() == BuiltinType::ULongLong;
8597 } else {
8598 // AArch32 polynomial vectors are signed.
8599 return BTy->getKind() == BuiltinType::SChar ||
8600 BTy->getKind() == BuiltinType::Short ||
8601 BTy->getKind() == BuiltinType::LongLong;
8602 }
8603 }
8604
8605 // Non-polynomial vector types: the usual suspects are allowed, as well as
8606 // float64_t on AArch64.
8607 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8608 BTy->getKind() == BuiltinType::Double)
8609 return true;
8610
8611 return BTy->getKind() == BuiltinType::SChar ||
8612 BTy->getKind() == BuiltinType::UChar ||
8613 BTy->getKind() == BuiltinType::Short ||
8614 BTy->getKind() == BuiltinType::UShort ||
8615 BTy->getKind() == BuiltinType::Int ||
8616 BTy->getKind() == BuiltinType::UInt ||
8617 BTy->getKind() == BuiltinType::Long ||
8618 BTy->getKind() == BuiltinType::ULong ||
8619 BTy->getKind() == BuiltinType::LongLong ||
8620 BTy->getKind() == BuiltinType::ULongLong ||
8621 BTy->getKind() == BuiltinType::Float ||
8622 BTy->getKind() == BuiltinType::Half ||
8623 BTy->getKind() == BuiltinType::BFloat16 ||
8624 BTy->getKind() == BuiltinType::MFloat8;
8625}
8626
8628 llvm::APSInt &Result) {
8629 const auto *AttrExpr = Attr.getArgAsExpr(0);
8630 if (!AttrExpr->isTypeDependent()) {
8631 if (std::optional<llvm::APSInt> Res =
8632 AttrExpr->getIntegerConstantExpr(S.Context)) {
8633 Result = *Res;
8634 return true;
8635 }
8636 }
8637 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8638 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8639 Attr.setInvalid();
8640 return false;
8641}
8642
8643/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8644/// "neon_polyvector_type" attributes are used to create vector types that
8645/// are mangled according to ARM's ABI. Otherwise, these types are identical
8646/// to those created with the "vector_size" attribute. Unlike "vector_size"
8647/// the argument to these Neon attributes is the number of vector elements,
8648/// not the vector size in bytes. The vector width and element type must
8649/// match one of the standard Neon vector types.
8651 Sema &S, VectorKind VecKind) {
8652 bool IsTargetOffloading = S.getLangOpts().isTargetDevice();
8653
8654 // Target must have NEON (or MVE, whose vectors are similar enough
8655 // not to need a separate attribute)
8656 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8657 VecKind == VectorKind::Neon &&
8658 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8659 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8660 << Attr << "'mve'";
8661 Attr.setInvalid();
8662 return;
8663 }
8664 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8665 VecKind == VectorKind::NeonPoly &&
8666 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8667 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8668 << Attr << "'mve'";
8669 Attr.setInvalid();
8670 return;
8671 }
8672
8673 // The number of elements must be an ICE.
8674 llvm::APSInt numEltsInt(32);
8675 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8676 return;
8677
8678 // Only certain element types are supported for Neon vectors.
8679 if (!isPermittedNeonBaseType(CurType, VecKind, S) && !IsTargetOffloading) {
8680 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8681 Attr.setInvalid();
8682 return;
8683 }
8684
8685 // The total size of the vector must be 64 or 128 bits.
8686 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8687 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8688 unsigned vecSize = typeSize * numElts;
8689 if (vecSize != 64 && vecSize != 128) {
8690 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8691 Attr.setInvalid();
8692 return;
8693 }
8694
8695 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8696}
8697
8698/// Handle the __ptrauth qualifier.
8700 const ParsedAttr &Attr, Sema &S) {
8701
8702 assert((Attr.getNumArgs() > 0 && Attr.getNumArgs() <= 3) &&
8703 "__ptrauth qualifier takes between 1 and 3 arguments");
8704 Expr *KeyArg = Attr.getArgAsExpr(0);
8705 Expr *IsAddressDiscriminatedArg =
8706 Attr.getNumArgs() >= 2 ? Attr.getArgAsExpr(1) : nullptr;
8707 Expr *ExtraDiscriminatorArg =
8708 Attr.getNumArgs() >= 3 ? Attr.getArgAsExpr(2) : nullptr;
8709
8710 unsigned Key;
8711 if (S.checkConstantPointerAuthKey(KeyArg, Key)) {
8712 Attr.setInvalid();
8713 return;
8714 }
8715 assert(Key <= PointerAuthQualifier::MaxKey && "ptrauth key is out of range");
8716
8717 bool IsInvalid = false;
8718 unsigned IsAddressDiscriminated, ExtraDiscriminator;
8719 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(IsAddressDiscriminatedArg,
8721 IsAddressDiscriminated);
8722 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(
8723 ExtraDiscriminatorArg, PointerAuthDiscArgKind::Extra, ExtraDiscriminator);
8724
8725 if (IsInvalid) {
8726 Attr.setInvalid();
8727 return;
8728 }
8729
8730 if (!T->isSignableType(Ctx) && !T->isDependentType()) {
8731 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_invalid_target) << T;
8732 Attr.setInvalid();
8733 return;
8734 }
8735
8736 if (T.getPointerAuth()) {
8737 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_redundant) << T;
8738 Attr.setInvalid();
8739 return;
8740 }
8741
8742 if (!S.getLangOpts().PointerAuthIntrinsics) {
8743 S.Diag(Attr.getLoc(), diag::err_ptrauth_disabled) << Attr.getRange();
8744 Attr.setInvalid();
8745 return;
8746 }
8747
8748 assert((!IsAddressDiscriminatedArg || IsAddressDiscriminated <= 1) &&
8749 "address discriminator arg should be either 0 or 1");
8751 Key, IsAddressDiscriminated, ExtraDiscriminator,
8752 PointerAuthenticationMode::SignAndAuth, /*IsIsaPointer=*/false,
8753 /*AuthenticatesNullValues=*/false);
8754 T = S.Context.getPointerAuthType(T, Qual);
8755}
8756
8757/// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8758/// used to create fixed-length versions of sizeless SVE types defined by
8759/// the ACLE, such as svint32_t and svbool_t.
8761 Sema &S) {
8762 // Target must have SVE.
8763 if (!S.Context.getTargetInfo().hasFeature("sve")) {
8764 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8765 Attr.setInvalid();
8766 return;
8767 }
8768
8769 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8770 // if <bits>+ syntax is used.
8771 if (!S.getLangOpts().VScaleMin ||
8772 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8773 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8774 << Attr;
8775 Attr.setInvalid();
8776 return;
8777 }
8778
8779 // The vector size must be an integer constant expression.
8780 llvm::APSInt SveVectorSizeInBits(32);
8781 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8782 return;
8783
8784 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8785
8786 // The attribute vector size must match -msve-vector-bits.
8787 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8788 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8789 << VecSize << S.getLangOpts().VScaleMin * 128;
8790 Attr.setInvalid();
8791 return;
8792 }
8793
8794 // Attribute can only be attached to a single SVE vector or predicate type.
8795 if (!CurType->isSveVLSBuiltinType()) {
8796 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8797 << Attr << CurType;
8798 Attr.setInvalid();
8799 return;
8800 }
8801
8802 const auto *BT = CurType->castAs<BuiltinType>();
8803
8804 QualType EltType = CurType->getSveEltType(S.Context);
8805 unsigned TypeSize = S.Context.getTypeSize(EltType);
8807 if (BT->getKind() == BuiltinType::SveBool) {
8808 // Predicates are represented as i8.
8809 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8811 } else
8812 VecSize /= TypeSize;
8813 CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8814}
8815
8816static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8817 QualType &CurType,
8818 ParsedAttr &Attr) {
8819 const VectorType *VT = dyn_cast<VectorType>(CurType);
8820 if (!VT || VT->getVectorKind() != VectorKind::Neon) {
8821 State.getSema().Diag(Attr.getLoc(),
8822 diag::err_attribute_arm_mve_polymorphism);
8823 Attr.setInvalid();
8824 return;
8825 }
8826
8827 CurType =
8828 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8829 State.getSema().Context, Attr),
8830 CurType, CurType);
8831}
8832
8833/// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8834/// used to create fixed-length versions of sizeless RVV types such as
8835/// vint8m1_t_t.
8837 ParsedAttr &Attr, Sema &S) {
8838 // Target must have vector extension.
8839 if (!S.Context.getTargetInfo().hasFeature("zve32x")) {
8840 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8841 << Attr << "'zve32x'";
8842 Attr.setInvalid();
8843 return;
8844 }
8845
8846 auto VScale = S.Context.getTargetInfo().getVScaleRange(
8848 if (!VScale || !VScale->first || VScale->first != VScale->second) {
8849 S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported)
8850 << Attr;
8851 Attr.setInvalid();
8852 return;
8853 }
8854
8855 // The vector size must be an integer constant expression.
8856 llvm::APSInt RVVVectorSizeInBits(32);
8857 if (!verifyValidIntegerConstantExpr(S, Attr, RVVVectorSizeInBits))
8858 return;
8859
8860 // Attribute can only be attached to a single RVV vector type.
8861 if (!CurType->isRVVVLSBuiltinType()) {
8862 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type)
8863 << Attr << CurType;
8864 Attr.setInvalid();
8865 return;
8866 }
8867
8868 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8869
8872 unsigned MinElts = Info.EC.getKnownMinValue();
8873
8874 VectorKind VecKind;
8875 unsigned ExpectedSize = VScale->first * MinElts;
8876 QualType EltType = CurType->getRVVEltType(S.Context);
8877 unsigned EltSize = S.Context.getTypeSize(EltType);
8878 unsigned NumElts;
8879 if (Info.ElementType == S.Context.BoolTy) {
8880 // A mask is stored in bytes. One with fewer than 8 lanes takes a single
8881 // byte, and its lane count is recorded in the vector kind.
8882 NumElts = VecSize / S.Context.getCharWidth();
8883 unsigned SubByteLanes = 0;
8884 if (!NumElts) {
8885 NumElts = 1;
8886 if (VecSize == 1 || VecSize == 2 || VecSize == 4)
8887 SubByteLanes = VecSize;
8888 }
8889 // Record the ratio of the vbool<R>_t type in the vector kind, so that
8890 // later stages do not have to re-derive it from VLEN and the lane count.
8891 // vbool<R>_t has RVVBitsPerBlock / R lanes at vscale=1.
8893 llvm::Log2_32(llvm::RISCV::RVVBitsPerBlock / MinElts), SubByteLanes);
8894 } else {
8895 ExpectedSize *= EltSize;
8896 NumElts = VecSize / EltSize;
8897
8898 // Record the LMUL of the sizeless type in the vector kind, so that later
8899 // stages do not have to re-derive it from VLEN and the element count.
8900 // LMUL = MinElts * EltSize / RVVBitsPerBlock
8902 int(llvm::Log2_32(MinElts * EltSize)) -
8903 int(llvm::Log2_32(llvm::RISCV::RVVBitsPerBlock)));
8904 }
8905
8906 // The attribute vector size must match -mrvv-vector-bits.
8907 if (VecSize != ExpectedSize) {
8908 S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size)
8909 << VecSize << ExpectedSize;
8910 Attr.setInvalid();
8911 return;
8912 }
8913
8914 CurType = S.Context.getVectorType(EltType, NumElts, VecKind);
8915}
8916
8917/// Handle OpenCL Access Qualifier Attribute.
8918static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8919 Sema &S) {
8920 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8921 if (!(CurType->isImageType() || CurType->isPipeType())) {
8922 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8923 Attr.setInvalid();
8924 return;
8925 }
8926
8927 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8928 QualType BaseTy = TypedefTy->desugar();
8929
8930 std::string PrevAccessQual;
8931 if (BaseTy->isPipeType()) {
8932 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8933 OpenCLAccessAttr *Attr =
8934 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8935 PrevAccessQual = Attr->getSpelling();
8936 } else {
8937 PrevAccessQual = "read_only";
8938 }
8939 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8940
8941 switch (ImgType->getKind()) {
8942 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8943 case BuiltinType::Id: \
8944 PrevAccessQual = #Access; \
8945 break;
8946 #include "clang/Basic/OpenCLImageTypes.def"
8947 default:
8948 llvm_unreachable("Unable to find corresponding image type.");
8949 }
8950 } else {
8951 llvm_unreachable("unexpected type");
8952 }
8953 StringRef AttrName = Attr.getAttrName()->getName();
8954 if (PrevAccessQual == AttrName.ltrim("_")) {
8955 // Duplicated qualifiers
8956 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8957 << AttrName << Attr.getRange();
8958 } else {
8959 // Contradicting qualifiers
8960 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8961 }
8962
8963 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8964 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8965 } else if (CurType->isPipeType()) {
8966 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8967 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8968 CurType = S.Context.getWritePipeType(ElemType);
8969 }
8970 }
8971}
8972
8973/// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8974static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8975 Sema &S) {
8976 if (!S.getLangOpts().MatrixTypes) {
8977 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8978 return;
8979 }
8980
8981 Expr *RowsExpr = Attr.getArgAsExpr(0);
8982 Expr *ColsExpr = Attr.getArgAsExpr(1);
8983 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8984 if (!T.isNull())
8985 CurType = T;
8986}
8987
8988static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8989 QualType &CurType, const ParsedAttr &PA) {
8990 Sema &S = State.getSema();
8991
8992 if (PA.getNumArgs() < 1) {
8993 S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
8994 return;
8995 }
8996
8997 // Make sure that there is a string literal as the annotation's first
8998 // argument.
8999 StringRef Str;
9000 if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
9001 return;
9002
9004 Args.reserve(PA.getNumArgs() - 1);
9005 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
9006 assert(!PA.isArgIdent(Idx));
9007 Args.push_back(PA.getArgAsExpr(Idx));
9008 }
9009 if (!S.ConstantFoldAttrArgs(PA, Args))
9010 return;
9011 auto *AnnotateTypeAttr =
9012 AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
9013 CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
9014}
9015
9016static void HandleLifetimeBoundAttr(TypeProcessingState &State,
9017 QualType &CurType,
9018 ParsedAttr &Attr) {
9019 if (State.getDeclarator().isDeclarationOfFunction()) {
9020 CurType = State.getAttributedType(
9021 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
9022 CurType, CurType);
9023 return;
9024 }
9025 State.getSema().Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
9028}
9029
9030static void HandleLifetimeCaptureByAttr(TypeProcessingState &State,
9031 QualType &CurType, ParsedAttr &PA) {
9032 if (State.getDeclarator().isDeclarationOfFunction()) {
9033 auto *Attr = State.getSema().ParseLifetimeCaptureByAttr(PA, "this");
9034 if (Attr)
9035 CurType = State.getAttributedType(Attr, CurType, CurType);
9036 }
9037}
9038
9039static void HandleHLSLParamModifierAttr(TypeProcessingState &State,
9040 QualType &CurType,
9041 const ParsedAttr &Attr, Sema &S) {
9042 // Don't apply this attribute to template dependent types. It is applied on
9043 // substitution during template instantiation. Also skip parsing this if we've
9044 // already modified the type based on an earlier attribute.
9045 if (CurType->isDependentType() || State.didParseHLSLParamMod())
9046 return;
9047 if (Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout ||
9048 Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out) {
9049 State.setParsedHLSLParamMod(true);
9050 }
9051}
9052
9054 // A DeclSpec attribute runs this once per declarator, as in
9055 // `IP __counted_by(n) a, b;`. Reuse one node, as the eager path does, so no
9056 // node is left without a count.
9057 if (LA.TypeToComplete) {
9058 QT = QualType(LA.TypeToComplete, 0);
9059 return true;
9060 }
9061
9062 // Nesting is checked once the enclosing declarator chunks wrap the node.
9063 BoundsAttrFlags Flags;
9065 SourceRange(LA.NameLoc),
9066 /*PointerNestLevel=*/0, Flags))
9067 return false;
9068
9069 // The argument isn't parsed yet, so build the type without a count.
9071 QT, Flags.CountInBytes, Flags.OrNull);
9072 QT = QualType(CATy, 0);
9073 LA.TypeToComplete = CATy;
9074 return true;
9075}
9076
9077static void processTypeAttrs(TypeProcessingState &state, QualType &type,
9078 TypeAttrLocation TAL,
9079 const ParsedAttributesView &attrs,
9080 CUDAFunctionTarget CFT) {
9081
9082 state.setParsedNoDeref(false);
9083 if (attrs.empty())
9084 return;
9085
9086 // Scan through and apply attributes to this type where it makes sense. Some
9087 // attributes (such as __address_space__, __vector_size__, etc) apply to the
9088 // type, but others can be present in the type specifiers even though they
9089 // apply to the decl. Here we apply type attributes and ignore the rest.
9090
9091 // This loop modifies the list pretty frequently, but we still need to make
9092 // sure we visit every element once. Copy the attributes list, and iterate
9093 // over that.
9094 ParsedAttributesView AttrsCopy{attrs};
9095 for (ParsedAttr &attr : AttrsCopy) {
9096
9097 // Skip attributes that were marked to be invalid.
9098 if (attr.isInvalid())
9099 continue;
9100
9101 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) {
9102 // [[gnu::...]] attributes are treated as declaration attributes, so may
9103 // not appertain to a DeclaratorChunk. If we handle them as type
9104 // attributes, accept them in that position and diagnose the GCC
9105 // incompatibility.
9106 if (attr.isGNUScope()) {
9107 assert(attr.isStandardAttributeSyntax());
9108 bool IsTypeAttr = attr.isTypeAttr();
9109 if (TAL == TAL_DeclChunk) {
9110 state.getSema().Diag(attr.getLoc(),
9111 IsTypeAttr
9112 ? diag::warn_gcc_ignores_type_attr
9113 : diag::warn_cxx11_gnu_attribute_on_type)
9114 << attr;
9115 if (!IsTypeAttr)
9116 continue;
9117 }
9118 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
9119 !attr.isTypeAttr()) {
9120 // Otherwise, only consider type processing for a C++11 attribute if
9121 // - it has actually been applied to a type (decl-specifier-seq or
9122 // declarator chunk), or
9123 // - it is a type attribute, irrespective of where it was applied (so
9124 // that we can support the legacy behavior of some type attributes
9125 // that can be applied to the declaration name).
9126 continue;
9127 }
9128 }
9129
9130 if (attr.isTypeAttr() &&
9131 state.getSema().checkCommonAttributeFeatures(type, attr)) {
9132 attr.setInvalid();
9133 continue;
9134 }
9135
9136 // If this is an attribute we can handle, do so now,
9137 // otherwise, add it to the FnAttrs list for rechaining.
9138 switch (attr.getKind()) {
9139 default:
9140 // A [[]] attribute on a declarator chunk must appertain to a type.
9141 if ((attr.isStandardAttributeSyntax() ||
9142 attr.isRegularKeywordAttribute()) &&
9143 TAL == TAL_DeclChunk) {
9144 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
9145 << attr << attr.isRegularKeywordAttribute();
9146 attr.setUsedAsTypeAttr();
9147 }
9148 break;
9149
9151 if (attr.isStandardAttributeSyntax()) {
9152 state.getSema().DiagnoseUnknownAttribute(attr);
9153 // Mark the attribute as invalid so we don't emit the same diagnostic
9154 // multiple times.
9155 attr.setInvalid();
9156 }
9157 break;
9158
9160 break;
9161
9162 case ParsedAttr::AT_BTFTypeTag:
9164 attr.setUsedAsTypeAttr();
9165 break;
9166
9167 case ParsedAttr::AT_MayAlias:
9168 // FIXME: This attribute needs to actually be handled, but if we ignore
9169 // it it breaks large amounts of Linux software.
9170 attr.setUsedAsTypeAttr();
9171 break;
9172 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
9173 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
9174 state.getSema().Diag(attr.getLoc(), diag::warn_deprecated_attribute)
9175 << attr;
9176 [[fallthrough]];
9177 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
9178 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
9179 case ParsedAttr::AT_OpenCLLocalAddressSpace:
9180 case ParsedAttr::AT_OpenCLConstantAddressSpace:
9181 case ParsedAttr::AT_OpenCLGenericAddressSpace:
9182 case ParsedAttr::AT_AddressSpace:
9183 case ParsedAttr::AT_SYCLPrivateAddressSpace:
9184 case ParsedAttr::AT_SYCLGlobalAddressSpace:
9185 case ParsedAttr::AT_SYCLLocalAddressSpace:
9186 case ParsedAttr::AT_SYCLConstantAddressSpace:
9187 case ParsedAttr::AT_SYCLGenericAddressSpace:
9189 attr.setUsedAsTypeAttr();
9190 break;
9191 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
9193 if (state.getDeclarator().getContext() == DeclaratorContext::Prototype) {
9194 if (state.getSema().getLangOpts().getHLSLVersion() <
9196 state.getSema().Diag(attr.getLoc(), diag::warn_hlsl_groupshared_202x);
9197
9198 // Note: we don't check for the usage of HLSLParamModifiers in/out/inout
9199 // here because the check in the AT_HLSLParamModifier case is sufficient
9200 // regardless of the order of groupshared or in/out/inout specified in
9201 // the parameter. And checking there produces a better error message.
9202 }
9203 attr.setUsedAsTypeAttr();
9204 break;
9205 case ParsedAttr::AT_HLSLRowMajor:
9206 case ParsedAttr::AT_HLSLColumnMajor:
9207 if (Attr *A =
9208 state.getSema().HLSL().buildMatrixLayoutTypeAttr(type, attr)) {
9209 MatrixType::LayoutKind Layout =
9210 attr.getKind() == ParsedAttr::AT_HLSLRowMajor
9214 state.getSema().Context.getMatrixTypeWithLayout(type, Layout);
9215 type = state.getAttributedType(A, type, Equivalent);
9216 }
9217 attr.setUsedAsTypeAttr();
9218 break;
9220 if (!handleObjCPointerTypeAttr(state, attr, type))
9222 attr.setUsedAsTypeAttr();
9223 break;
9224 case ParsedAttr::AT_VectorSize:
9225 HandleVectorSizeAttr(type, attr, state.getSema());
9226 attr.setUsedAsTypeAttr();
9227 break;
9228 case ParsedAttr::AT_ExtVectorType:
9229 HandleExtVectorTypeAttr(type, attr, state.getSema());
9230 attr.setUsedAsTypeAttr();
9231 break;
9232 case ParsedAttr::AT_NeonVectorType:
9234 attr.setUsedAsTypeAttr();
9235 break;
9236 case ParsedAttr::AT_NeonPolyVectorType:
9237 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
9239 attr.setUsedAsTypeAttr();
9240 break;
9241 case ParsedAttr::AT_ArmSveVectorBits:
9242 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
9243 attr.setUsedAsTypeAttr();
9244 break;
9245 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
9247 attr.setUsedAsTypeAttr();
9248 break;
9249 }
9250 case ParsedAttr::AT_RISCVRVVVectorBits:
9251 HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema());
9252 attr.setUsedAsTypeAttr();
9253 break;
9254 case ParsedAttr::AT_OpenCLAccess:
9255 HandleOpenCLAccessAttr(type, attr, state.getSema());
9256 attr.setUsedAsTypeAttr();
9257 break;
9258 case ParsedAttr::AT_PointerAuth:
9259 HandlePtrAuthQualifier(state.getSema().Context, type, attr,
9260 state.getSema());
9261 attr.setUsedAsTypeAttr();
9262 break;
9263 case ParsedAttr::AT_LifetimeBound:
9264 if (TAL == TAL_DeclChunk)
9266 break;
9267 case ParsedAttr::AT_LifetimeCaptureBy:
9268 if (TAL == TAL_DeclChunk)
9270 break;
9271 case ParsedAttr::AT_OverflowBehavior:
9273 attr.setUsedAsTypeAttr();
9274 break;
9275
9276 case ParsedAttr::AT_NoDeref: {
9277 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
9278 // See https://github.com/llvm/llvm-project/issues/55790 for details.
9279 // For the time being, we simply emit a warning that the attribute is
9280 // ignored.
9281 if (attr.isStandardAttributeSyntax()) {
9282 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
9283 << attr;
9284 break;
9285 }
9286 ASTContext &Ctx = state.getSema().Context;
9287 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
9288 type, type);
9289 attr.setUsedAsTypeAttr();
9290 state.setParsedNoDeref(true);
9291 break;
9292 }
9293
9294 case ParsedAttr::AT_MatrixType:
9295 HandleMatrixTypeAttr(type, attr, state.getSema());
9296 attr.setUsedAsTypeAttr();
9297 break;
9298
9299 case ParsedAttr::AT_WebAssemblyFuncref: {
9301 attr.setUsedAsTypeAttr();
9302 break;
9303 }
9304
9305 case ParsedAttr::AT_HLSLParamModifier: {
9306 HandleHLSLParamModifierAttr(state, type, attr, state.getSema());
9307 if (attrs.hasAttribute(ParsedAttr::AT_HLSLGroupSharedAddressSpace)) {
9308 state.getSema().Diag(attr.getLoc(), diag::err_hlsl_attr_incompatible)
9309 << attr << "'groupshared'";
9310 attr.setInvalid();
9311 return;
9312 }
9313 attr.setUsedAsTypeAttr();
9314 break;
9315 }
9316
9317 case ParsedAttr::AT_SwiftAttr: {
9318 HandleSwiftAttr(state, TAL, type, attr);
9319 break;
9320 }
9321
9324 attr.setUsedAsTypeAttr();
9325 break;
9326
9327
9329 // Either add nullability here or try to distribute it. We
9330 // don't want to distribute the nullability specifier past any
9331 // dependent type, because that complicates the user model.
9332 if (type->canHaveNullability() || type->isDependentType() ||
9333 type->isArrayType() ||
9335 unsigned endIndex;
9336 if (TAL == TAL_DeclChunk)
9337 endIndex = state.getCurrentChunkIndex();
9338 else
9339 endIndex = state.getDeclarator().getNumTypeObjects();
9340 bool allowOnArrayType =
9341 state.getDeclarator().isPrototypeContext() &&
9342 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
9344 allowOnArrayType)) {
9345 attr.setInvalid();
9346 }
9347
9348 attr.setUsedAsTypeAttr();
9349 }
9350 break;
9351
9352 case ParsedAttr::AT_ObjCKindOf:
9353 // '__kindof' must be part of the decl-specifiers.
9354 switch (TAL) {
9355 case TAL_DeclSpec:
9356 break;
9357
9358 case TAL_DeclChunk:
9359 case TAL_DeclName:
9360 state.getSema().Diag(attr.getLoc(),
9361 diag::err_objc_kindof_wrong_position)
9362 << FixItHint::CreateRemoval(attr.getLoc())
9364 state.getDeclarator().getDeclSpec().getBeginLoc(),
9365 "__kindof ");
9366 break;
9367 }
9368
9369 // Apply it regardless.
9370 if (checkObjCKindOfType(state, type, attr))
9371 attr.setInvalid();
9372 break;
9373
9374 case ParsedAttr::AT_NoThrow:
9375 // Exception Specifications aren't generally supported in C mode throughout
9376 // clang, so revert to attribute-based handling for C.
9377 if (!state.getSema().getLangOpts().CPlusPlus)
9378 break;
9379 [[fallthrough]];
9381
9382 attr.setUsedAsTypeAttr();
9383
9384 // Attributes with standard syntax have strict rules for what they
9385 // appertain to and hence should not use the "distribution" logic below.
9386 if (attr.isStandardAttributeSyntax() ||
9387 attr.isRegularKeywordAttribute()) {
9388 if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
9389 diagnoseBadTypeAttribute(state.getSema(), attr, type);
9390 attr.setInvalid();
9391 }
9392 break;
9393 }
9394
9395 // Never process function type attributes as part of the
9396 // declaration-specifiers.
9397 if (TAL == TAL_DeclSpec)
9399
9400 // Otherwise, handle the possible delays.
9401 else if (!handleFunctionTypeAttr(state, attr, type, CFT))
9403 break;
9404 case ParsedAttr::AT_AcquireHandle: {
9405 if (!type->isFunctionType())
9406 return;
9407
9408 if (attr.getNumArgs() != 1) {
9409 state.getSema().Diag(attr.getLoc(),
9410 diag::err_attribute_wrong_number_arguments)
9411 << attr << 1;
9412 attr.setInvalid();
9413 return;
9414 }
9415
9416 StringRef HandleType;
9417 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
9418 return;
9419 type = state.getAttributedType(
9420 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
9421 type, type);
9422 attr.setUsedAsTypeAttr();
9423 break;
9424 }
9425 case ParsedAttr::AT_AnnotateType: {
9427 attr.setUsedAsTypeAttr();
9428 break;
9429 }
9430 case ParsedAttr::AT_HLSLResourceClass:
9431 case ParsedAttr::AT_HLSLResourceDimension:
9432 case ParsedAttr::AT_HLSLIsROV:
9433 case ParsedAttr::AT_HLSLRawBuffer:
9434 case ParsedAttr::AT_HLSLIsArray:
9435 case ParsedAttr::AT_HLSLIsMultiSampled:
9436 case ParsedAttr::AT_HLSLContainedType: {
9437 // Only collect HLSL resource type attributes that are in
9438 // decl-specifier-seq; do not collect attributes on declarations or those
9439 // that get to slide after declaration name.
9440 if (TAL == TAL_DeclSpec &&
9441 state.getSema().HLSL().handleResourceTypeAttr(type, attr))
9442 attr.setUsedAsTypeAttr();
9443 break;
9444 }
9445 }
9446
9447 // Handle attributes that are defined in a macro. We do not want this to be
9448 // applied to ObjC builtin attributes.
9449 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
9450 !type.getQualifiers().hasObjCLifetime() &&
9451 !type.getQualifiers().hasObjCGCAttr() &&
9452 attr.getKind() != ParsedAttr::AT_ObjCGC &&
9453 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
9454 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
9455 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
9456 state.setExpansionLocForMacroQualifiedType(
9457 cast<MacroQualifiedType>(type.getTypePtr()),
9458 attr.getMacroExpansionLoc());
9459 }
9460 }
9461}
9462
9464 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
9465 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9466 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
9467 auto *Def = Var->getDefinition();
9468 if (!Def) {
9469 SourceLocation PointOfInstantiation = E->getExprLoc();
9470 runWithSufficientStackSpace(PointOfInstantiation, [&] {
9471 InstantiateVariableDefinition(PointOfInstantiation, Var);
9472 });
9473 Def = Var->getDefinition();
9474
9475 // If we don't already have a point of instantiation, and we managed
9476 // to instantiate a definition, this is the point of instantiation.
9477 // Otherwise, we don't request an end-of-TU instantiation, so this is
9478 // not a point of instantiation.
9479 // FIXME: Is this really the right behavior?
9480 if (Var->getPointOfInstantiation().isInvalid() && Def) {
9481 assert(Var->getTemplateSpecializationKind() ==
9483 "explicit instantiation with no point of instantiation");
9484 Var->setTemplateSpecializationKind(
9485 Var->getTemplateSpecializationKind(), PointOfInstantiation);
9486 }
9487 }
9488
9489 // Update the type to the definition's type both here and within the
9490 // expression.
9491 if (Def) {
9492 DRE->setDecl(Def);
9493 QualType T = Def->getType();
9494 DRE->setType(T);
9495 // FIXME: Update the type on all intervening expressions.
9496 E->setType(T);
9497 }
9498
9499 // We still go on to try to complete the type independently, as it
9500 // may also require instantiations or diagnostics if it remains
9501 // incomplete.
9502 }
9503 }
9504 }
9505 if (const auto CastE = dyn_cast<ExplicitCastExpr>(E)) {
9506 QualType DestType = CastE->getTypeAsWritten();
9507 if (const auto *IAT = Context.getAsIncompleteArrayType(DestType)) {
9508 // C++20 [expr.static.cast]p.4: ... If T is array of unknown bound,
9509 // this direct-initialization defines the type of the expression
9510 // as U[1]
9511 QualType ResultType = Context.getConstantArrayType(
9512 IAT->getElementType(),
9513 llvm::APInt(Context.getTypeSize(Context.getSizeType()), 1),
9514 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal,
9515 /*IndexTypeQuals=*/0);
9516 E->setType(ResultType);
9517 }
9518 }
9519}
9520
9522 // Incomplete array types may be completed by the initializer attached to
9523 // their definitions. For static data members of class templates and for
9524 // variable templates, we need to instantiate the definition to get this
9525 // initializer and complete the type.
9526 if (E->getType()->isIncompleteArrayType())
9528
9529 // FIXME: Are there other cases which require instantiating something other
9530 // than the type to complete the type of an expression?
9531
9532 return E->getType();
9533}
9534
9536 TypeDiagnoser &Diagnoser) {
9537 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
9538 Diagnoser);
9539}
9540
9541bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9542 BoundTypeDiagnoser<> Diagnoser(DiagID);
9544}
9545
9547 CompleteTypeKind Kind,
9548 TypeDiagnoser &Diagnoser) {
9549 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
9550 return true;
9551 if (auto *TD = T->getAsTagDecl(); TD && !TD->isCompleteDefinitionRequired()) {
9552 TD->setCompleteDefinitionRequired();
9553 Consumer.HandleTagDeclRequiredDefinition(TD);
9554 }
9555 return false;
9556}
9557
9560 if (!Suggested)
9561 return false;
9562
9563 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9564 // and isolate from other C++ specific checks.
9566 getLangOpts(), D->getASTContext(), Suggested->getASTContext(),
9567 NonEquivalentDecls, StructuralEquivalenceKind::Default,
9568 /*StrictTypeSpelling=*/false, /*Complain=*/true,
9569 /*ErrorOnTagTypeMismatch=*/true);
9570 return Ctx.IsEquivalent(D, Suggested);
9571}
9572
9574 AcceptableKind Kind, bool OnlyNeedComplete) {
9575 // Easy case: if we don't have modules, all declarations are visible.
9576 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9577 return true;
9578
9579 // If this definition was instantiated from a template, map back to the
9580 // pattern from which it was instantiated.
9581 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined())
9582 // We're in the middle of defining it; this definition should be treated
9583 // as visible.
9584 return true;
9585
9586 auto DefinitionIsAcceptable = [&](NamedDecl *D) {
9587 // The (primary) definition might be in a visible module.
9588 if (isAcceptable(D, Kind))
9589 return true;
9590
9591 // A visible module might have a merged definition instead.
9594 if (CodeSynthesisContexts.empty() &&
9595 !getLangOpts().ModulesLocalVisibility) {
9596 // Cache the fact that this definition is implicitly visible because
9597 // there is a visible merged definition.
9599 }
9600 return true;
9601 }
9602
9603 return false;
9604 };
9605 auto IsDefinition = [](NamedDecl *D) {
9606 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
9607 return RD->isThisDeclarationADefinition();
9608 if (auto *ED = dyn_cast<EnumDecl>(D))
9609 return ED->isThisDeclarationADefinition();
9610 if (auto *FD = dyn_cast<FunctionDecl>(D))
9611 return FD->isThisDeclarationADefinition();
9612 if (auto *VD = dyn_cast<VarDecl>(D))
9613 return VD->isThisDeclarationADefinition() == VarDecl::Definition;
9614 llvm_unreachable("unexpected decl type");
9615 };
9616 auto FoundAcceptableDefinition = [&](NamedDecl *D) {
9618 return DefinitionIsAcceptable(D);
9619
9620 // See ASTDeclReader::attachPreviousDeclImpl. Now we still
9621 // may demote definition to declaration for decls in haeder modules,
9622 // so avoid looking at its redeclaration to save time.
9623 // NOTE: If we don't demote definition to declarations for decls
9624 // in header modules, remove the condition.
9626 return DefinitionIsAcceptable(D);
9627
9628 for (auto *RD : D->redecls()) {
9629 auto *ND = cast<NamedDecl>(RD);
9630 if (!IsDefinition(ND))
9631 continue;
9632 if (DefinitionIsAcceptable(ND)) {
9633 *Suggested = ND;
9634 return true;
9635 }
9636 }
9637
9638 return false;
9639 };
9640
9641 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9642 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9643 RD = Pattern;
9644 D = RD->getDefinition();
9645 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
9646 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9647 ED = Pattern;
9648 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9649 // If the enum has a fixed underlying type, it may have been forward
9650 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9651 // the enum and assign it the underlying type of `int`. Since we're only
9652 // looking for a complete type (not a definition), any visible declaration
9653 // of it will do.
9654 *Suggested = nullptr;
9655 for (auto *Redecl : ED->redecls()) {
9656 if (isAcceptable(Redecl, Kind))
9657 return true;
9658 if (Redecl->isThisDeclarationADefinition() ||
9659 (Redecl->isCanonicalDecl() && !*Suggested))
9660 *Suggested = Redecl;
9661 }
9662
9663 return false;
9664 }
9665 D = ED->getDefinition();
9666 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
9667 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9668 FD = Pattern;
9669 D = FD->getDefinition();
9670 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
9671 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9672 VD = Pattern;
9673 D = VD->getDefinition();
9674 }
9675
9676 assert(D && "missing definition for pattern of instantiated definition");
9677
9678 *Suggested = D;
9679
9680 if (FoundAcceptableDefinition(D))
9681 return true;
9682
9683 // The external source may have additional definitions of this entity that are
9684 // visible, so complete the redeclaration chain now and ask again.
9685 if (auto *Source = Context.getExternalSource()) {
9686 Source->CompleteRedeclChain(D);
9687 return FoundAcceptableDefinition(D);
9688 }
9689
9690 return false;
9691}
9692
9693/// Determine whether there is any declaration of \p D that was ever a
9694/// definition (perhaps before module merging) and is currently visible.
9695/// \param D The definition of the entity.
9696/// \param Suggested Filled in with the declaration that should be made visible
9697/// in order to provide a definition of this entity.
9698/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9699/// not defined. This only matters for enums with a fixed underlying
9700/// type, since in all other cases, a type is complete if and only if it
9701/// is defined.
9703 bool OnlyNeedComplete) {
9705 OnlyNeedComplete);
9706}
9707
9708/// Determine whether there is any declaration of \p D that was ever a
9709/// definition (perhaps before module merging) and is currently
9710/// reachable.
9711/// \param D The definition of the entity.
9712/// \param Suggested Filled in with the declaration that should be made
9713/// reachable
9714/// in order to provide a definition of this entity.
9715/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9716/// not defined. This only matters for enums with a fixed underlying
9717/// type, since in all other cases, a type is complete if and only if it
9718/// is defined.
9720 bool OnlyNeedComplete) {
9722 OnlyNeedComplete);
9723}
9724
9725/// Locks in the inheritance model for the given class and all of its bases.
9727 RD = RD->getMostRecentDecl();
9728 if (!RD->hasAttr<MSInheritanceAttr>()) {
9730 bool BestCase = false;
9733 BestCase = true;
9734 IM = RD->calculateInheritanceModel();
9735 break;
9738 break;
9741 break;
9744 break;
9745 }
9746
9749 : RD->getSourceRange();
9750 RD->addAttr(MSInheritanceAttr::CreateImplicit(
9751 S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
9753 }
9754}
9755
9756bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9757 CompleteTypeKind Kind,
9758 TypeDiagnoser *Diagnoser) {
9759 // FIXME: Add this assertion to make sure we always get instantiation points.
9760 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9761 // FIXME: Add this assertion to help us flush out problems with
9762 // checking for dependent types and type-dependent expressions.
9763 //
9764 // assert(!T->isDependentType() &&
9765 // "Can't ask whether a dependent type is complete");
9766
9767 if (const auto *MPTy = dyn_cast<MemberPointerType>(T.getCanonicalType())) {
9768 if (CXXRecordDecl *RD = MPTy->getMostRecentCXXRecordDecl();
9769 RD && !RD->isDependentType()) {
9770 CanQualType T = Context.getCanonicalTagType(RD);
9771 if (getLangOpts().CompleteMemberPointers && !RD->isBeingDefined() &&
9772 RequireCompleteType(Loc, T, Kind, diag::err_memptr_incomplete))
9773 return true;
9774
9775 // We lock in the inheritance model once somebody has asked us to ensure
9776 // that a pointer-to-member type is complete.
9777 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9778 (void)isCompleteType(Loc, T);
9779 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
9780 }
9781 }
9782 }
9783
9784 NamedDecl *Def = nullptr;
9786 bool Incomplete = (T->isIncompleteType(&Def) ||
9788
9789 // Check that any necessary explicit specializations are visible. For an
9790 // enum, we just need the declaration, so don't check this.
9791 if (Def && !isa<EnumDecl>(Def))
9793
9794 // If we have a complete type, we're done.
9795 if (!Incomplete) {
9796 NamedDecl *Suggested = nullptr;
9797 if (Def &&
9798 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
9799 // If the user is going to see an error here, recover by making the
9800 // definition visible.
9801 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9802 if (Diagnoser && Suggested)
9804 /*Recover*/ TreatAsComplete);
9805 return !TreatAsComplete;
9806 }
9807 return false;
9808 }
9809
9810 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
9811 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
9812
9813 // Give the external source a chance to provide a definition of the type.
9814 // This is kept separate from completing the redeclaration chain so that
9815 // external sources such as LLDB can avoid synthesizing a type definition
9816 // unless it's actually needed.
9817 if (Tag || IFace) {
9818 // Avoid diagnosing invalid decls as incomplete.
9819 if (Def->isInvalidDecl())
9820 return true;
9821
9822 // Give the external AST source a chance to complete the type.
9823 if (auto *Source = Context.getExternalSource()) {
9824 if (Tag && Tag->hasExternalLexicalStorage())
9825 Source->CompleteType(Tag);
9826 if (IFace && IFace->hasExternalLexicalStorage())
9827 Source->CompleteType(IFace);
9828 // If the external source completed the type, go through the motions
9829 // again to ensure we're allowed to use the completed type.
9830 if (!T->isIncompleteType())
9831 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9832 }
9833 }
9834
9835 // If we have a class template specialization or a class member of a
9836 // class template specialization, or an array with known size of such,
9837 // try to instantiate it.
9838 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
9839 bool Instantiated = false;
9840 bool Diagnosed = false;
9841 if (RD->isDependentContext()) {
9842 // Don't try to instantiate a dependent class (eg, a member template of
9843 // an instantiated class template specialization).
9844 // FIXME: Can this ever happen?
9845 } else if (auto *ClassTemplateSpec =
9846 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
9847 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9850 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9851 /*Complain=*/Diagnoser, ClassTemplateSpec->hasStrictPackMatch());
9852 });
9853 Instantiated = true;
9854 }
9855 } else {
9856 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9857 if (!RD->isBeingDefined() && Pattern) {
9858 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9859 assert(MSI && "Missing member specialization information?");
9860 // This record was instantiated from a class within a template.
9861 if (MSI->getTemplateSpecializationKind() !=
9864 Diagnosed = InstantiateClass(Loc, RD, Pattern,
9867 /*Complain=*/Diagnoser);
9868 });
9869 Instantiated = true;
9870 }
9871 }
9872 }
9873
9874 if (Instantiated) {
9875 // Instantiate* might have already complained that the template is not
9876 // defined, if we asked it to.
9877 if (Diagnoser && Diagnosed)
9878 return true;
9879 // If we instantiated a definition, check that it's usable, even if
9880 // instantiation produced an error, so that repeated calls to this
9881 // function give consistent answers.
9882 if (!T->isIncompleteType())
9883 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9884 }
9885 }
9886
9887 // FIXME: If we didn't instantiate a definition because of an explicit
9888 // specialization declaration, check that it's visible.
9889
9890 if (!Diagnoser)
9891 return true;
9892
9893 Diagnoser->diagnose(*this, Loc, T);
9894
9895 // If the type was a forward declaration of a class/struct/union
9896 // type, produce a note.
9897 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9898 Diag(Tag->getLocation(), Tag->isBeingDefined()
9899 ? diag::note_type_being_defined
9900 : diag::note_forward_declaration)
9901 << Context.getCanonicalTagType(Tag);
9902
9903 // If the Objective-C class was a forward declaration, produce a note.
9904 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9905 Diag(IFace->getLocation(), diag::note_forward_class);
9906
9907 // If we have external information that we can use to suggest a fix,
9908 // produce a note.
9909 if (ExternalSource)
9910 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9911
9912 return true;
9913}
9914
9916 CompleteTypeKind Kind, unsigned DiagID) {
9917 BoundTypeDiagnoser<> Diagnoser(DiagID);
9918 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9919}
9920
9921/// Get diagnostic %select index for tag kind for
9922/// literal type diagnostic message.
9923/// WARNING: Indexes apply to particular diagnostics only!
9924///
9925/// \returns diagnostic %select index.
9927 switch (Tag) {
9929 return 0;
9931 return 1;
9932 case TagTypeKind::Class:
9933 return 2;
9934 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9935 }
9936}
9937
9939 TypeDiagnoser &Diagnoser) {
9940 assert(!T->isDependentType() && "type should not be dependent");
9941
9942 QualType ElemType = Context.getBaseElementType(T);
9943 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9944 T->isLiteralType(Context))
9945 return false;
9946
9947 Diagnoser.diagnose(*this, Loc, T);
9948
9949 if (T->isVariableArrayType())
9950 return true;
9951
9952 if (!ElemType->isRecordType())
9953 return true;
9954
9955 // A partially-defined class type can't be a literal type, because a literal
9956 // class type must have a trivial destructor (which can't be checked until
9957 // the class definition is complete).
9958 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9959 return true;
9960
9961 const auto *RD = ElemType->castAsCXXRecordDecl();
9962 // [expr.prim.lambda]p3:
9963 // This class type is [not] a literal type.
9964 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9965 Diag(RD->getLocation(), diag::note_non_literal_lambda);
9966 return true;
9967 }
9968
9969 // If the class has virtual base classes, then it's not an aggregate, and
9970 // cannot have any constexpr constructors or a trivial default constructor,
9971 // so is non-literal. This is better to diagnose than the resulting absence
9972 // of constexpr constructors.
9973 if (!getLangOpts().CPlusPlus26 && RD->getNumVBases()) {
9974 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9975 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9976 for (const auto &I : RD->vbases())
9977 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9978 << I.getSourceRange();
9979 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9980 !RD->hasTrivialDefaultConstructor()) {
9981 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9982 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9983 for (const auto &I : RD->bases()) {
9984 if (!I.getType()->isLiteralType(Context)) {
9985 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9986 << RD << I.getType() << I.getSourceRange();
9987 return true;
9988 }
9989 }
9990 for (const auto *I : RD->fields()) {
9991 if (!I->getType()->isLiteralType(Context) ||
9992 I->getType().isVolatileQualified()) {
9993 Diag(I->getLocation(), diag::note_non_literal_field)
9994 << RD << I << I->getType()
9995 << I->getType().isVolatileQualified();
9996 return true;
9997 }
9998 }
9999 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
10000 : !RD->hasTrivialDestructor()) {
10001 // All fields and bases are of literal types, so have trivial or constexpr
10002 // destructors. If this class's destructor is non-trivial / non-constexpr,
10003 // it must be user-declared.
10004 CXXDestructorDecl *Dtor = RD->getDestructor();
10005 assert(Dtor && "class has literal fields and bases but no dtor?");
10006 if (!Dtor)
10007 return true;
10008
10009 if (getLangOpts().CPlusPlus20) {
10010 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
10011 << RD;
10012 } else {
10013 Diag(Dtor->getLocation(), Dtor->isUserProvided()
10014 ? diag::note_non_literal_user_provided_dtor
10015 : diag::note_non_literal_nontrivial_dtor)
10016 << RD;
10017 if (!Dtor->isUserProvided())
10020 /*Diagnose*/ true);
10021 }
10022 }
10023
10024 return true;
10025}
10026
10028 BoundTypeDiagnoser<> Diagnoser(DiagID);
10029 return RequireLiteralType(Loc, T, Diagnoser);
10030}
10031
10033 assert(!E->hasPlaceholderType() && "unexpected placeholder");
10034
10035 if (!getLangOpts().CPlusPlus && E->refersToBitField())
10036 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
10037 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
10038
10039 if (!E->isTypeDependent()) {
10040 QualType T = E->getType();
10041 if (const TagType *TT = T->getAs<TagType>())
10042 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
10043 }
10044 return Context.getTypeOfExprType(E, Kind);
10045}
10046
10047static void
10050 // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl.
10051 auto *CountDecl = cast<DeclRefExpr>(E)->getDecl();
10052 Decls.push_back(TypeCoupledDeclRefInfo(CountDecl, /*IsDref*/ false));
10053}
10054
10056 FieldDecl *FD, Expr *Arg) {
10057 assert(Arg);
10058
10059 // Only the counted_by family exists so far.
10060 auto *CATy = cast<CountAttributedType>(BATy);
10061
10062 auto Reject = [&]() -> bool {
10063 // Guarded so shared declarators (`IP __counted_by(n) a, b;`) only complete
10064 // the node once.
10065 if (!CATy->getCountExpr())
10066 Context.completeCountAttributedType(CATy, Arg, {});
10067 FD->setInvalidDecl();
10068 return false;
10069 };
10070
10071 if (Arg->containsErrors())
10072 return Reject();
10073
10074 if (CheckCountedByAttrOnField(FD, Arg, CATy->isCountInBytes(),
10075 CATy->isOrNull()))
10076 return Reject();
10077
10079 BuildTypeCoupledDecls(Arg, Decls);
10080 // Several declarators can share one node when the attribute was written in
10081 // declaration-specifier position (`IP __counted_by(n) a, b;`), so this runs
10082 // once per field
10083 if (!CATy->getCountExpr())
10084 Context.completeCountAttributedType(CATy, Arg, Decls);
10085
10086 return true;
10087}
10088
10090 Expr *CountExpr,
10091 bool CountInBytes,
10092 bool OrNull) {
10093 assert(WrappedTy->isIncompleteArrayType() || WrappedTy->isPointerType());
10094
10096 BuildTypeCoupledDecls(CountExpr, Decls);
10097 /// When the resulting expression is invalid, we still create the AST using
10098 /// the original count expression for the sake of AST dump.
10099 return Context.getCountAttributedType(WrappedTy, CountExpr, CountInBytes,
10100 OrNull, Decls);
10101}
10102
10103/// getDecltypeForExpr - Given an expr, will return the decltype for
10104/// that expression, according to the rules in C++11
10105/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
10107
10108 Expr *IDExpr = E;
10109 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
10110 IDExpr = ImplCastExpr->getSubExpr();
10111
10112 if (auto *PackExpr = dyn_cast<PackIndexingExpr>(E)) {
10113 if (E->isInstantiationDependent())
10114 IDExpr = PackExpr->getPackIdExpression();
10115 else
10116 IDExpr = PackExpr->getSelectedExpr();
10117 }
10118
10119 if (E->isTypeDependent())
10120 return Context.DependentTy;
10121
10122 // C++11 [dcl.type.simple]p4:
10123 // The type denoted by decltype(e) is defined as follows:
10124
10125 // C++20:
10126 // - if E is an unparenthesized id-expression naming a non-type
10127 // template-parameter (13.2), decltype(E) is the type of the
10128 // template-parameter after performing any necessary type deduction
10129 // Note that this does not pick up the implicit 'const' for a template
10130 // parameter object. This rule makes no difference before C++20 so we apply
10131 // it unconditionally.
10132 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
10133 IDExpr = SNTTPE->getReplacement();
10134
10135 // - if e is an unparenthesized id-expression or an unparenthesized class
10136 // member access (5.2.5), decltype(e) is the type of the entity named
10137 // by e. If there is no such entity, or if e names a set of overloaded
10138 // functions, the program is ill-formed;
10139 //
10140 // We apply the same rules for Objective-C ivar and property references.
10141 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
10142 const ValueDecl *VD = DRE->getDecl();
10143 QualType T = VD->getType();
10144 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
10145 }
10146 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
10147 if (const auto *VD = ME->getMemberDecl())
10148 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
10149 return VD->getType();
10150 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
10151 return IR->getDecl()->getType();
10152 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
10153 if (PR->isExplicitProperty())
10154 return PR->getExplicitProperty()->getType();
10155 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
10156 return PE->getType();
10157 }
10158
10159 // C++11 [expr.lambda.prim]p18:
10160 // Every occurrence of decltype((x)) where x is a possibly
10161 // parenthesized id-expression that names an entity of automatic
10162 // storage duration is treated as if x were transformed into an
10163 // access to a corresponding data member of the closure type that
10164 // would have been declared if x were an odr-use of the denoted
10165 // entity.
10166 if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
10167 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
10168 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
10169 QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
10170 if (!T.isNull())
10171 return Context.getLValueReferenceType(T);
10172 }
10173 }
10174 }
10175
10176 return Context.getReferenceQualifiedType(E);
10177}
10178
10179QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
10180 assert(!E->hasPlaceholderType() && "unexpected placeholder");
10181
10182 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
10183 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
10184 // The expression operand for decltype is in an unevaluated expression
10185 // context, so side effects could result in unintended consequences.
10186 // Exclude instantiation-dependent expressions, because 'decltype' is often
10187 // used to build SFINAE gadgets.
10188 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
10189 }
10190 return Context.getDecltypeType(E, getDecltypeForExpr(E));
10191}
10192
10194 SourceLocation Loc) {
10195 if (!IndexExpr)
10196 return QualType();
10197
10198 // Diagnose unexpanded packs but continue to improve recovery.
10199 if (!Pattern->containsUnexpandedParameterPack())
10200 Diag(Loc, diag::err_expected_name_of_pack) << Pattern;
10201
10202 QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc);
10203
10204 if (!Type.isNull())
10205 DiagCompat(Loc, diag_compat::pack_indexing);
10206 return Type;
10207}
10208
10210 SourceLocation Loc, bool FullySubstituted,
10211 ArrayRef<QualType> Expansions) {
10212
10213 UnsignedOrNone Index = std::nullopt;
10214 if (!IndexExpr->isInstantiationDependent()) {
10215 llvm::APSInt Value;
10217 IndexExpr, Context.getSizeType(), Value, CCEKind::PackIndex);
10218
10219 if (!Res.isUsable() || !Value.isRepresentableByInt64())
10220 return QualType();
10221
10222 IndexExpr = Res.get();
10223 uint64_t V = Value.getZExtValue();
10224 if (FullySubstituted && V >= Expansions.size()) {
10225 Diag(IndexExpr->getBeginLoc(), diag::err_pack_index_out_of_bound)
10226 << V << Pattern << Expansions.size();
10227 return QualType();
10228 }
10229 Index = static_cast<unsigned>(V);
10230 }
10231
10232 return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted,
10233 Expansions, Index);
10234}
10235
10237 SourceLocation Loc) {
10238 assert(BaseType->isEnumeralType());
10239 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
10240
10241 S.DiagnoseUseOfDecl(ED, Loc);
10242
10243 QualType Underlying = ED->getIntegerType();
10244 if (Underlying.isNull()) {
10245 Underlying = ED->getDefinition()->getIntegerType();
10246 assert(!Underlying.isNull());
10247 }
10248
10249 return Underlying;
10250}
10251
10253 SourceLocation Loc) {
10254 if (!BaseType->isEnumeralType()) {
10255 Diag(Loc, diag::err_only_enums_have_underlying_types);
10256 return QualType();
10257 }
10258
10259 // The enum could be incomplete if we're parsing its definition or
10260 // recovering from an error.
10261 NamedDecl *FwdDecl = nullptr;
10262 if (BaseType->isIncompleteType(&FwdDecl)) {
10263 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
10264 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
10265 return QualType();
10266 }
10267
10268 return GetEnumUnderlyingType(*this, BaseType, Loc);
10269}
10270
10272 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
10273 ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
10275 : BaseType;
10276
10277 return Pointer.isNull() ? QualType() : Pointer;
10278}
10279
10281 if (!BaseType->isAnyPointerType())
10282 return BaseType;
10283
10284 return BaseType->getPointeeType();
10285}
10286
10288 QualType Underlying = BaseType.getNonReferenceType();
10289 if (Underlying->isArrayType())
10290 return Context.getDecayedType(Underlying);
10291
10292 if (Underlying->isFunctionType())
10293 return BuiltinAddPointer(BaseType, Loc);
10294
10295 SplitQualType Split = Underlying.getSplitUnqualifiedType();
10296 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
10297 // in the same group of qualifiers as 'const' and 'volatile', we're extending
10298 // '__decay(T)' so that it removes all qualifiers.
10299 Split.Quals.removeCVRQualifiers();
10300 return Context.getQualifiedType(Split);
10301}
10302
10304 SourceLocation Loc) {
10305 assert(LangOpts.CPlusPlus);
10307 BaseType.isReferenceable()
10308 ? BuildReferenceType(BaseType,
10309 UKind == UnaryTransformType::AddLvalueReference,
10310 Loc, DeclarationName())
10311 : BaseType;
10312 return Reference.isNull() ? QualType() : Reference;
10313}
10314
10316 SourceLocation Loc) {
10317 if (UKind == UnaryTransformType::RemoveAllExtents)
10318 return Context.getBaseElementType(BaseType);
10319
10320 if (const auto *AT = Context.getAsArrayType(BaseType))
10321 return AT->getElementType();
10322
10323 return BaseType;
10324}
10325
10327 SourceLocation Loc) {
10328 assert(LangOpts.CPlusPlus);
10329 QualType T = BaseType.getNonReferenceType();
10330 if (UKind == UTTKind::RemoveCVRef &&
10331 (T.isConstQualified() || T.isVolatileQualified())) {
10332 Qualifiers Quals;
10333 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
10334 Quals.removeConst();
10335 Quals.removeVolatile();
10336 T = Context.getQualifiedType(Unqual, Quals);
10337 }
10338 return T;
10339}
10340
10342 SourceLocation Loc) {
10343 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
10344 BaseType->isFunctionType())
10345 return BaseType;
10346
10347 Qualifiers Quals;
10348 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
10349
10350 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
10351 Quals.removeConst();
10352 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
10353 Quals.removeVolatile();
10354 if (UKind == UTTKind::RemoveRestrict)
10355 Quals.removeRestrict();
10356
10357 return Context.getQualifiedType(Unqual, Quals);
10358}
10359
10361 bool IsMakeSigned,
10362 SourceLocation Loc) {
10363 if (BaseType->isEnumeralType()) {
10364 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
10365 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
10366 unsigned int Bits = BitInt->getNumBits();
10367 if (Bits > 1)
10368 return S.Context.getBitIntType(!IsMakeSigned, Bits);
10369
10370 S.Diag(Loc, diag::err_make_signed_integral_only)
10371 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
10372 return QualType();
10373 }
10374 if (Underlying->isBooleanType()) {
10375 S.Diag(Loc, diag::err_make_signed_integral_only)
10376 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
10377 << Underlying;
10378 return QualType();
10379 }
10380 }
10381
10382 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
10383 std::array<CanQualType *, 6> AllSignedIntegers = {
10386 ArrayRef<CanQualType *> AvailableSignedIntegers(
10387 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
10388 std::array<CanQualType *, 6> AllUnsignedIntegers = {
10392 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
10393 AllUnsignedIntegers.size() -
10394 Int128Unsupported);
10395 ArrayRef<CanQualType *> *Consider =
10396 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
10397
10398 uint64_t BaseSize = S.Context.getTypeSize(BaseType);
10399 auto *Result =
10400 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
10401 return BaseSize == S.Context.getTypeSize(T->getTypePtr());
10402 });
10403
10404 assert(Result != Consider->end());
10405 return QualType((*Result)->getTypePtr(), 0);
10406}
10407
10409 SourceLocation Loc) {
10410 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
10411 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
10412 BaseType->isBooleanType() ||
10413 (BaseType->isBitIntType() &&
10414 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
10415 Diag(Loc, diag::err_make_signed_integral_only)
10416 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
10417 return QualType();
10418 }
10419
10420 bool IsNonIntIntegral =
10421 BaseType->isChar16Type() || BaseType->isChar32Type() ||
10422 BaseType->isWideCharType() || BaseType->isEnumeralType();
10423
10424 QualType Underlying =
10425 IsNonIntIntegral
10426 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
10427 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
10428 : Context.getCorrespondingUnsignedType(BaseType);
10429 if (Underlying.isNull())
10430 return Underlying;
10431 return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
10432}
10433
10435 SourceLocation Loc) {
10436 if (BaseType->isDependentType())
10437 return Context.getUnaryTransformType(BaseType, BaseType, UKind);
10439 switch (UKind) {
10440 case UnaryTransformType::EnumUnderlyingType: {
10441 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
10442 break;
10443 }
10444 case UnaryTransformType::AddPointer: {
10445 Result = BuiltinAddPointer(BaseType, Loc);
10446 break;
10447 }
10448 case UnaryTransformType::RemovePointer: {
10449 Result = BuiltinRemovePointer(BaseType, Loc);
10450 break;
10451 }
10452 case UnaryTransformType::Decay: {
10453 Result = BuiltinDecay(BaseType, Loc);
10454 break;
10455 }
10456 case UnaryTransformType::AddLvalueReference:
10457 case UnaryTransformType::AddRvalueReference: {
10458 Result = BuiltinAddReference(BaseType, UKind, Loc);
10459 break;
10460 }
10461 case UnaryTransformType::RemoveAllExtents:
10462 case UnaryTransformType::RemoveExtent: {
10463 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
10464 break;
10465 }
10466 case UnaryTransformType::RemoveCVRef:
10467 case UnaryTransformType::RemoveReference: {
10468 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
10469 break;
10470 }
10471 case UnaryTransformType::RemoveConst:
10472 case UnaryTransformType::RemoveCV:
10473 case UnaryTransformType::RemoveRestrict:
10474 case UnaryTransformType::RemoveVolatile: {
10475 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
10476 break;
10477 }
10478 case UnaryTransformType::MakeSigned:
10479 case UnaryTransformType::MakeUnsigned: {
10480 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
10481 break;
10482 }
10483 }
10484
10485 return !Result.isNull()
10486 ? Context.getUnaryTransformType(BaseType, Result, UKind)
10487 : Result;
10488}
10489
10491 if (!T->isDependentType() && !isa<AutoType>(T)) {
10492 // FIXME: It isn't entirely clear whether incomplete atomic types
10493 // are allowed or not; for simplicity, ban them for the moment.
10494 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
10495 return QualType();
10496
10497 int DisallowedKind = -1;
10498 if (T->isArrayType())
10499 DisallowedKind = 1;
10500 else if (T->isFunctionType())
10501 DisallowedKind = 2;
10502 else if (T->isReferenceType())
10503 DisallowedKind = 3;
10504 else if (T->isAtomicType())
10505 DisallowedKind = 4;
10506 else if (T.hasQualifiers())
10507 DisallowedKind = 5;
10508 else if (T->isSizelessType())
10509 DisallowedKind = 6;
10510 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus)
10511 // Some other non-trivially-copyable type (probably a C++ class)
10512 DisallowedKind = 7;
10513 else if (T->isBitIntType())
10514 DisallowedKind = 8;
10515 else if (getLangOpts().C23 && T->isUndeducedAutoType())
10516 // _Atomic auto is prohibited in C23
10517 DisallowedKind = 9;
10518 else if (T->isOverflowBehaviorType())
10519 // Overflow behavior types do not compose with _Atomic
10520 DisallowedKind = 10;
10521
10522 if (DisallowedKind != -1) {
10523 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
10524 return QualType();
10525 }
10526
10527 // FIXME: Do we need any handling for ARC here?
10528 }
10529
10530 // Build the pointer type.
10531 return Context.getAtomicType(T);
10532}
Defines the clang::ASTContext interface.
#define V(N, I)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
static StringRef getTriple(const Command &Job)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
llvm::json::Array Array
Defines the clang::Preprocessor interface.
static QualType getUnderlyingType(const SubRegion *R)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S, VectorKind VecKind)
HandleNeonVectorTypeAttr - The "neon_vector_type" and "neon_polyvector_type" attributes are used to c...
static constexpr uint64_t MaxVectorSizeInBits
static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType)
static bool checkOpenCLPipePacketType(Sema &S, QualType T, SourceLocation Loc)
static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S)
static void distributeObjCPointerTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType type)
Given that an objc_gc attribute was written somewhere on a declaration other than on the declarator i...
Definition SemaType.cpp:510
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:768
#define MS_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:172
#define CALLING_CONV_ATTRS_CASELIST
Definition SemaType.cpp:125
static void emitNullabilityConsistencyWarning(Sema &S, SimplePointerKind PointerKind, SourceLocation PointerLoc, SourceLocation PointerEndLoc)
static void fixItNullability(Sema &S, DiagBuilderT &Diag, SourceLocation PointerLoc, NullabilityKind Nullability)
Creates a fix-it to insert a C-style nullability keyword at pointerLoc, taking into account whitespac...
static ExprResult checkArraySize(Sema &S, Expr *&ArraySize, llvm::APSInt &SizeVal, unsigned VLADiag, bool VLAIsError)
Check whether the specified array bound can be evaluated using the relevant language rules.
static Attr * createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, NullabilityKind NK)
static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
HandleVectorSizeAttribute - this attribute is only applicable to integral and float scalars,...
static void inferARCWriteback(TypeProcessingState &state, QualType &declSpecType)
Given that this is the declaration of a parameter under ARC, attempt to infer attributes and such for...
static TypeSourceInfo * GetTypeSourceInfoForDeclarator(TypeProcessingState &State, QualType T, TypeSourceInfo *ReturnTypeInfo)
Create and instantiate a TypeSourceInfo with type source information.
static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, const Expr *AddrSpace, SourceLocation AttrLoc)
Build an AddressSpace index from a constant expression and diagnose any errors related to invalid add...
static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr, TypeProcessingState &State)
static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, Qualifiers::ObjCLifetime ownership, unsigned chunkIndex)
static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
handleObjCGCTypeAttr - Process the attribute((objc_gc)) type attribute on the specified type.
static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk)
static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
Process the OpenCL-like ext_vector_type attribute when it occurs on a type.
static void HandleHLSLParamModifierAttr(TypeProcessingState &State, QualType &CurType, const ParsedAttr &Attr, Sema &S)
static void HandleLifetimeBoundAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &Attr)
static bool handleArmStateAttribute(Sema &S, FunctionProtoType::ExtProtoInfo &EPI, ParsedAttr &Attr, FunctionType::ArmStateValue State)
static bool handleArmAgnosticAttribute(Sema &S, FunctionProtoType::ExtProtoInfo &EPI, ParsedAttr &Attr)
static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType, CUDAFunctionTarget CFT)
A function type attribute was written in the decl spec.
Definition SemaType.cpp:678
static bool handleObjCPointerTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
Definition SemaType.cpp:425
static constexpr uint64_t MaxVectorElements
static QualType inferARCLifetimeForPointee(Sema &S, QualType type, SourceLocation loc, bool isReference)
Given that we're building a pointer or reference to the given.
static bool handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState, ParsedAttr &PAttr, QualType &QT, FunctionTypeUnwrapper &Unwrapped)
static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType, bool IsMakeSigned, SourceLocation Loc)
static bool CheckNullabilityTypeSpecifier(Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT, NullabilityKind Nullability, SourceLocation NullabilityLoc, bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting)
#define OBJC_POINTER_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:120
static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, QualType type)
diagnoseBadTypeAttribute - Diagnoses a type attribute which doesn't apply to the given type.
Definition SemaType.cpp:80
static PointerDeclaratorKind classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, PointerWrappingDeclaratorKind &wrappingKind)
Classify the given declarator, whose type-specified is type, based on what kind of pointer it refers ...
static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr, llvm::APSInt &Result)
static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL, QualType &QT, ParsedAttr &PAttr)
static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
static bool shouldHaveNullability(QualType T)
static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &Attr)
static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, DeclaratorChunk &DeclType, QualType RT)
Produce an appropriate diagnostic for an ambiguity between a function declarator and a C++ direct-ini...
static void distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType)
Distribute an objc_gc type attribute that was written on the declarator.
Definition SemaType.cpp:566
static FileID getNullabilityCompletenessCheckFileID(Sema &S, SourceLocation loc)
static void HandleOverflowBehaviorAttr(QualType &Type, const ParsedAttr &Attr, TypeProcessingState &State)
static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, Sema &S)
HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is used to create fixed-length v...
#define FUNCTION_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:149
static void HandleLifetimeCaptureByAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &PA)
static bool distributeNullabilityTypeAttr(TypeProcessingState &state, QualType type, ParsedAttr &attr)
Distribute a nullability type attribute that cannot be applied to the type specifier to a pointer,...
static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, QualType &declSpecType, CUDAFunctionTarget CFT)
Given that there are attributes written on the declarator or declaration itself, try to distribute an...
Definition SemaType.cpp:727
static void fillHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL, TypeProcessingState &State)
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:627
static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type.
static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State, QualType &QT, ParsedAttr &PAttr)
static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex)
Returns true if any of the declarator chunks before endIndex include a level of indirection: array,...
static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
Handle OpenCL Access Qualifier Attribute.
static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind)
Map a nullability attribute kind to a nullability kind.
static bool distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, ParsedAttr &attr, ParsedAttributesView &attrList, QualType &declSpecType, CUDAFunctionTarget CFT)
Try to distribute a function type attribute to the innermost function chunk or type.
Definition SemaType.cpp:658
#define NULLABILITY_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:179
static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, TypeSourceInfo *&ReturnTypeInfo)
static void checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, SourceLocation pointerLoc, SourceLocation pointerEndLoc=SourceLocation())
Complains about missing nullability if the file containing pointerLoc has other uses of nullability (...
static void transferARCOwnership(TypeProcessingState &state, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership)
Used for transferring ownership in casts resulting in l-values.
static std::string getPrintableNameForEntity(DeclarationName Entity)
static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy)
static QualType rebuildAttributedTypeWithoutNullability(ASTContext &Ctx, QualType Type)
Rebuild an attributed type without the nullability attribute on it.
static DeclaratorChunk * maybeMovePastReturnType(Declarator &declarator, unsigned i, bool onlyBlockPointers)
Given the index of a declarator chunk, check whether that chunk directly specifies the return type of...
Definition SemaType.cpp:442
static OpenCLAccessAttr::Spelling getImageAccess(const ParsedAttributesView &Attrs)
Definition SemaType.cpp:882
static void fillMatrixTypeLoc(MatrixTypeLoc MTL, const ParsedAttributesView &Attrs)
static UnaryTransformType::UTTKind TSTToUnaryTransformType(DeclSpec::TST SwitchTST)
Definition SemaType.cpp:890
static void HandleRISCVRVVVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, Sema &S)
HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is used to create fixed-leng...
static void HandleAddressSpaceTypeAttribute(QualType &Type, const ParsedAttr &Attr, TypeProcessingState &State)
HandleAddressSpaceTypeAttribute - Process an address_space attribute on the specified type.
static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, QualifiedFunctionKind QFK)
Check whether the type T is a qualified function type, and if it is, diagnose that it cannot be conta...
static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, QualType Result)
Return true if this is omitted block return type.
Definition SemaType.cpp:852
static void HandlePtrAuthQualifier(ASTContext &Ctx, QualType &T, const ParsedAttr &Attr, Sema &S)
Handle the __ptrauth qualifier.
static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld, LangAS ASNew, SourceLocation AttrLoc)
static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T)
Produce an appropriate diagnostic for a declarator with top-level parentheses.
static QualType ConvertDeclSpecToType(TypeProcessingState &state)
Convert the specified declspec to the appropriate type object.
Definition SemaType.cpp:907
static std::pair< QualType, TypeSourceInfo * > InventTemplateParameter(TypeProcessingState &state, QualType T, TypeSourceInfo *TrailingTSI, AutoType *Auto, InventedTemplateParameterInfo &Info)
static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType, CUDAFunctionTarget CFT)
A function type attribute was written on the declarator or declaration.
Definition SemaType.cpp:698
static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, unsigned &TypeQuals, QualType TypeSoFar, unsigned RemoveTQs, unsigned DiagID)
Definition SemaType.cpp:824
static CallingConv getCCForDeclaratorChunk(Sema &S, Declarator &D, const ParsedAttributesView &AttrList, const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex)
Helper for figuring out the default CC for a function declarator type.
static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for literal type diagnostic message.
static void recordNullabilitySeen(Sema &S, SourceLocation loc)
Marks that a nullability feature has been used in the file containing loc.
static bool CheckBitIntElementType(Sema &S, SourceLocation AttrLoc, const BitIntType *BIT, bool ForMatrixType=false)
static void checkExtParameterInfos(Sema &S, ArrayRef< QualType > paramTypes, const FunctionProtoType::ExtProtoInfo &EPI, llvm::function_ref< SourceLocation(unsigned)> getParamLoc)
Check the extended parameter information.
static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type, CUDAFunctionTarget CFT)
Process an individual function attribute.
static void transferARCOwnershipToDeclSpec(Sema &S, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership)
static void BuildTypeCoupledDecls(Expr *E, llvm::SmallVectorImpl< TypeCoupledDeclRefInfo > &Decls)
static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD)
Locks in the inheritance model for the given class and all of its bases.
static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, ParsedAttr &attr)
Check the application of the Objective-C '__kindof' qualifier to the given type.
static bool hasNullabilityAttr(const ParsedAttributesView &attrs)
Check whether there is a nullability attribute of any kind in the given attribute list.
static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
handleObjCOwnershipTypeAttr - Process an objc_ownership attribute on the specified type.
static void moveAttrFromListToList(ParsedAttr &attr, ParsedAttributesView &fromList, ParsedAttributesView &toList)
Definition SemaType.cpp:391
static void HandleAnnotateTypeAttr(TypeProcessingState &State, QualType &CurType, const ParsedAttr &PA)
static void fillAttributedTypeLoc(AttributedTypeLoc TL, TypeProcessingState &State)
TypeAttrLocation
The location of a type attribute.
Definition SemaType.cpp:399
@ TAL_DeclChunk
The attribute is part of a DeclaratorChunk.
Definition SemaType.cpp:403
@ TAL_DeclSpec
The attribute is in the decl-specifier-seq.
Definition SemaType.cpp:401
@ TAL_DeclName
The attribute is immediately after the declaration's name.
Definition SemaType.cpp:405
static bool isOmittedBlockReturnType(const Declarator &D)
isOmittedBlockReturnType - Return true if this declarator is missing a return type because this is a ...
Definition SemaType.cpp:63
static TypeSourceInfo * GetFullTypeForDeclarator(TypeProcessingState &state, QualType declSpecType, TypeSourceInfo *TInfo)
TypeDiagSelector
Definition SemaType.cpp:55
@ TDS_ObjCObjOrBlock
Definition SemaType.cpp:58
@ TDS_Function
Definition SemaType.cpp:56
@ TDS_Pointer
Definition SemaType.cpp:57
static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType, SourceLocation Loc)
static void fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, ArrayRef< const ParsedAttributesView * > AttrLists)
static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk)
static AttrT * createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL)
static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, Declarator &D, unsigned FunctionChunkIndex)
static void processTypeAttrs(TypeProcessingState &state, QualType &type, TypeAttrLocation TAL, const ParsedAttributesView &attrs, CUDAFunctionTarget CFT=CUDAFunctionTarget::HostDevice)
static bool checkMutualExclusion(TypeProcessingState &state, const FunctionProtoType::ExtProtoInfo &EPI, ParsedAttr &Attr, AttributeCommonInfo::Kind OtherKind)
static Attr * getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr)
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__DEVICE__ int max(int __a, int __b)
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
TranslationUnitDecl * getTranslationUnitDecl() const
CanQualType LongTy
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
CanQualType Int128Ty
QualType getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateName TypeConstraintConcept=TemplateName(), ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:852
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 BoolTy
CanQualType UnsignedLongTy
CountAttributedType * getIncompleteCountAttributedType(QualType WrappedTy, bool CountInBytes, bool OrNull) const
Return a CountAttributedType whose count expression has not been parsed yet, for use by a late-parsed...
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
CanQualType UnsignedLongLongTy
CanQualType UnsignedShortTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
CanQualType ShortTy
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
DiagnosticsEngine & getDiagnostics() const
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:971
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getPointerAuthType(QualType Ty, PointerAuthQualifier PointerAuth)
Return a type with the given __ptrauth qualifier.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
void setLBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1814
void setRBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1822
void setSizeExpr(Expr *Size)
Definition TypeLoc.h:1834
TypeLoc getValueLoc() const
Definition TypeLoc.h:2692
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2704
void setParensRange(SourceRange Range)
Definition TypeLoc.h:2728
Attr - This represents one attribute.
Definition Attr.h:47
attr::Kind getKind() const
Definition Attr.h:93
const char * getSpelling() const
void setImplicit(bool I)
Definition Attr.h:107
Combines information about the source-code form of an attribute, including its syntax and spelling.
bool isContextSensitiveKeywordAttribute() const
SourceLocation getLoc() const
const IdentifierInfo * getAttrName() const
ParsedAttr * create(IdentifierInfo *attrName, SourceRange attrRange, AttributeScopeInfo scope, ArgsUnion *args, unsigned numArgs, ParsedAttr::Form form, SourceLocation ellipsisLoc=SourceLocation())
Definition ParsedAttr.h:756
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
bool hasExplicitTemplateArgs() const
Definition TypeLoc.h:2476
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2442
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2492
TemplateName getNamedConcept() const
Definition TypeLoc.h:2466
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2485
void setConceptReference(ConceptReference *CR)
Definition TypeLoc.h:2436
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2460
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition TypeLoc.h:2503
unsigned getNumArgs() const
Definition TypeLoc.h:2499
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2472
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2430
TypeLoc getWrappedLoc() const
Definition TypeLoc.h:1060
Comparison function object.
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8436
unsigned getNumBits() const
Definition TypeBase.h:8448
void setCaretLoc(SourceLocation Loc)
Definition TypeLoc.h:1563
Pointer to a block type.
Definition TypeBase.h:3653
[BoundsSafety] Represents a parent type class for CountAttributedType and similar sugar types that wi...
Definition TypeBase.h:3457
TypeSpecifierWidth getWrittenWidthSpec() const
Definition TypeLoc.h:641
bool needsExtraLocalData() const
Definition TypeLoc.h:606
void setBuiltinLoc(SourceLocation Loc)
Definition TypeLoc.h:583
WrittenBuiltinSpecs & getWrittenBuiltinSpecs()
Definition TypeLoc.h:599
TypeSpecifierSign getWrittenSignSpec() const
Definition TypeLoc.h:625
void expandBuiltinRange(SourceRange Range)
Definition TypeLoc.h:587
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
Kind getKind() const
Definition TypeBase.h:3299
Represents a C++ destructor within a class.
Definition DeclCXX.h:2915
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:540
bool hasUserProvidedDefaultConstructor() const
Whether this class has a user-provided default constructor per C++11.
Definition DeclCXX.h:792
bool hasDefinition() const
Definition DeclCXX.h:562
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:1196
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:189
SourceRange getRange() const
Definition DeclSpec.h:83
SourceLocation getBeginLoc() const
Definition DeclSpec.h:87
bool isSet() const
Deprecated.
Definition DeclSpec.h:202
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:98
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:187
Represents a canonical, potentially-qualified type.
SourceLocation getBegin() const
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateName NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
TypeLoc getNextTypeLoc() const
Definition TypeLoc.h:429
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:336
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:376
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3509
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2108
bool isRecord() const
Definition DeclBase.h:2208
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2710
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2163
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
Captures information about "declaration specifiers".
Definition DeclSpec.h:279
const WrittenBuiltinSpecs & getWrittenBuiltinSpecs() const
Definition DeclSpec.h:967
bool isTypeSpecPipe() const
Definition DeclSpec.h:594
static const TST TST_typeof_unqualType
Definition DeclSpec.h:341
SourceLocation getTypeSpecSignLoc() const
Definition DeclSpec.h:632
bool hasAutoTypeSpec() const
Definition DeclSpec.h:646
static const TST TST_typename
Definition DeclSpec.h:338
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:627
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:764
static const TST TST_char8
Definition DeclSpec.h:314
static const TST TST_BFloat16
Definition DeclSpec.h:321
TST getTypeSpecType() const
Definition DeclSpec.h:588
SCS getStorageClassSpec() const
Definition DeclSpec.h:552
SourceLocation getOverflowBehaviorLoc() const
Definition DeclSpec.h:690
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:626
bool isTypeSpecSat() const
Definition DeclSpec.h:595
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:625
static const TST TST_auto_type
Definition DeclSpec.h:351
static const TST TST_interface
Definition DeclSpec.h:336
static const TST TST_double
Definition DeclSpec.h:323
static const TST TST_typeofExpr
Definition DeclSpec.h:340
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:668
TemplateIdAnnotation * getRepAsTemplateId() const
Definition DeclSpec.h:617
static const TST TST_union
Definition DeclSpec.h:334
static const TST TST_typename_pack_indexing
Definition DeclSpec.h:345
static const TST TST_char
Definition DeclSpec.h:312
static const TST TST_bool
Definition DeclSpec.h:329
static const TST TST_char16
Definition DeclSpec.h:315
static const TST TST_unknown_anytype
Definition DeclSpec.h:352
TSC getTypeSpecComplex() const
Definition DeclSpec.h:584
static const TST TST_int
Definition DeclSpec.h:317
ParsedType getRepAsType() const
Definition DeclSpec.h:598
static const TST TST_accum
Definition DeclSpec.h:325
static const TST TST_half
Definition DeclSpec.h:320
ParsedAttributes & getAttributes()
Definition DeclSpec.h:946
bool isTypeAltiVecPixel() const
Definition DeclSpec.h:590
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:697
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:669
static const TST TST_ibm128
Definition DeclSpec.h:328
Expr * getRepAsExpr() const
Definition DeclSpec.h:606
static const TST TST_enum
Definition DeclSpec.h:333
AttributePool & getAttributePool() const
Definition DeclSpec.h:919
bool isWrapSpecified() const
Definition DeclSpec.h:681
static const TST TST_float128
Definition DeclSpec.h:327
static const TST TST_decltype
Definition DeclSpec.h:343
SourceRange getTypeSpecWidthRange() const
Definition DeclSpec.h:630
SourceLocation getTypeSpecTypeNameLoc() const
Definition DeclSpec.h:637
SourceLocation getTypeSpecWidthLoc() const
Definition DeclSpec.h:629
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:670
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:342
static const TST TST_class
Definition DeclSpec.h:337
TypeSpecifierType TST
Definition DeclSpec.h:309
bool isOverflowBehaviorSpecified() const
Definition DeclSpec.h:687
bool hasTagDefinition() const
Definition DeclSpec.cpp:435
static const TST TST_decimal64
Definition DeclSpec.h:331
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition DeclSpec.cpp:444
bool isTypeAltiVecBool() const
Definition DeclSpec.h:591
bool isConstrainedAuto() const
Definition DeclSpec.h:596
static const TST TST_wchar
Definition DeclSpec.h:313
SourceLocation getTypeSpecComplexLoc() const
Definition DeclSpec.h:631
static const TST TST_void
Definition DeclSpec.h:311
bool isTypeAltiVecVector() const
Definition DeclSpec.h:589
static const TST TST_bitint
Definition DeclSpec.h:319
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:534
static const TST TST_float
Definition DeclSpec.h:322
static const TST TST_atomic
Definition DeclSpec.h:353
bool isTrapSpecified() const
Definition DeclSpec.h:684
static const TST TST_fract
Definition DeclSpec.h:326
Decl * getRepAsDecl() const
Definition DeclSpec.h:602
static const TST TST_float16
Definition DeclSpec.h:324
static bool isTransformTypeTrait(TST T)
Definition DeclSpec.h:523
static const TST TST_unspecified
Definition DeclSpec.h:310
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:672
TypeSpecifierSign getTypeSpecSign() const
Definition DeclSpec.h:585
CXXScopeSpec & getTypeSpecScope()
Definition DeclSpec.h:622
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:633
OverflowBehaviorState getOverflowBehaviorState() const
Definition DeclSpec.h:678
static const TST TST_decltype_auto
Definition DeclSpec.h:344
static const TST TST_error
Definition DeclSpec.h:363
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:429
static const TST TST_decimal32
Definition DeclSpec.h:330
TypeSpecifierWidth getTypeSpecWidth() const
Definition DeclSpec.h:581
static const TST TST_char32
Definition DeclSpec.h:316
static const TST TST_decimal128
Definition DeclSpec.h:332
bool isTypeSpecOwned() const
Definition DeclSpec.h:592
SourceLocation getTypeSpecSatLoc() const
Definition DeclSpec.h:635
SourceRange getTypeofParensRange() const
Definition DeclSpec.h:643
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:673
static const TST TST_int128
Definition DeclSpec.h:318
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:671
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:894
static const TST TST_typeofType
Definition DeclSpec.h:339
static const TST TST_auto
Definition DeclSpec.h:350
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:905
static const TST TST_struct
Definition DeclSpec.h:335
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:855
bool isInvalidDecl() const
Definition DeclBase.h:597
SourceLocation getLocation() const
Definition DeclBase.h:448
void setImplicit(bool I=true)
Definition DeclBase.h:603
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1067
bool hasAttr() const
Definition DeclBase.h:586
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:436
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:883
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:1996
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2559
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2501
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2146
const DeclaratorChunk * getInnermostNonParenChunk() const
Return the innermost (closest to the declarator) chunk of this declarator that is not a parens chunk,...
Definition DeclSpec.h:2527
void AddInnermostTypeInfo(const DeclaratorChunk &TI)
Add a new innermost chunk to this declarator.
Definition DeclSpec.h:2492
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2613
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2849
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2786
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2436
bool hasTrailingReturnType() const
Determine whether a trailing return type was written (at any level) within this declarator.
Definition DeclSpec.h:2711
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2183
bool isExpressionContext() const
Determine whether this declaration appears in a context where an expression could appear.
Definition DeclSpec.h:2655
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2514
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2821
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2497
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2789
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2834
DeclaratorContext getContext() const
Definition DeclSpec.h:2171
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2182
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2165
bool isFirstDeclarator() const
Definition DeclSpec.h:2829
SourceLocation getCommaLoc() const
Definition DeclSpec.h:2830
AttributePool & getAttributePool() const
Definition DeclSpec.h:2155
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2161
bool hasEllipsis() const
Definition DeclSpec.h:2833
ParsedType getTrailingReturnType() const
Get the trailing return type appearing (at any level) within this declarator.
Definition DeclSpec.h:2720
bool isInvalidType() const
Definition DeclSpec.h:2822
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:400
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2181
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2857
bool isPrototypeContext() const
Definition DeclSpec.h:2173
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:391
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2153
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2590
void setEllipsisLoc(SourceLocation EL)
Definition DeclSpec.h:2835
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2430
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2322
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2319
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2008
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2029
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4159
void copy(DependentNameTypeLoc Loc)
Definition TypeLoc.h:2643
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2127
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2099
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:992
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:761
Wrap a function effect's condition expression in another struct so that FunctionProtoType's TrailingO...
Definition TypeBase.h:5268
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation NameLoc)
Definition TypeLoc.h:744
Represents an enum.
Definition Decl.h:4162
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4335
EnumDecl * getDefinition() const
Definition Decl.h:4274
This represents one expression.
Definition Expr.h:114
void setType(QualType t)
Definition Expr.h:147
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isPRValue() const
Definition Expr.h:287
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:3728
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:225
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:481
QualType getType() const
Definition Expr.h:146
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:528
Represents a member of a struct/union/class.
Definition Decl.h:3311
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:79
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:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
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:103
A SourceLocation and its associated SourceManager.
unsigned getSpellingLineNumber(bool *Invalid=nullptr) const
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5484
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:6006
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5516
Represents an abstract function effect, using just an enumeration describing its kind.
Definition TypeBase.h:5161
Kind
Identifies the particular effect.
Definition TypeBase.h:5164
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5348
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
Qualifiers getMethodQuals() const
Definition TypeBase.h:5974
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5952
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5837
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5833
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition TypeBase.h:5982
unsigned getNumParams() const
Definition TypeLoc.h:1747
void setLocalRangeBegin(SourceLocation L)
Definition TypeLoc.h:1695
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1711
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1754
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1719
void setLocalRangeEnd(SourceLocation L)
Definition TypeLoc.h:1703
void setExceptionSpecRange(SourceRange R)
Definition TypeLoc.h:1733
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4855
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4967
CallingConv getCC() const
Definition TypeBase.h:4914
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4783
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
ExtInfo getExtInfo() const
Definition TypeBase.h:5100
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3847
AArch64SMETypeAttributes
The AArch64 SME ACLE (Arm C/C++ Language Extensions) define a number of function type attributes that...
Definition TypeBase.h:5020
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:5053
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:5049
CallingConv getCallConv() const
Definition TypeBase.h:5099
QualType getReturnType() const
Definition TypeBase.h:5084
bool getHasRegParm() const
Definition TypeBase.h:5086
Type source information for HLSL attributed resource type.
Definition TypeLoc.h:1113
void setContainedTypeSourceInfo(TypeSourceInfo *TSI) const
Definition TypeLoc.h:1120
void setSourceRange(const SourceRange &R)
Definition TypeLoc.h:1124
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
A simple pair of identifier info and location.
void setIdentifierInfo(IdentifierInfo *Ident)
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ElaboratedTypeKeyword getKeyword() const
Definition TypeBase.h:6224
void setAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1645
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3715
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
bool isImplicitIntAllowed() const
Returns true if implicit int is supported at all.
bool allowArrayReturnTypes() const
bool isTargetDevice() const
True when compiling for an offloading target device.
bool isImplicitIntRequired() const
Returns true if implicit int is part of the language requirements.
bool isSYCL() const
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Holds a QualType and a TypeSourceInfo* that came out of a declarator parsing.
Definition LocInfoType.h:28
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
Represents the results of name lookup.
Definition Lookup.h:147
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1404
void setExpansionLoc(SourceLocation Loc)
Definition TypeLoc.h:1414
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6426
void setAttrRowOperand(Expr *e)
Definition TypeLoc.h:2162
void setAttrColumnOperand(Expr *e)
Definition TypeLoc.h:2168
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2177
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2156
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4593
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:1590
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3783
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5845
QualType getPointeeType() const
Definition TypeBase.h:3769
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:869
This represents a decl that may have a name.
Definition Decl.h:276
bool isModulePrivate() const
Whether this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:657
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NamespaceAndPrefix getAsNamespaceAndPrefix() const
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1313
void setNameEndLoc(SourceLocation Loc)
Definition TypeLoc.h:1325
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8163
Wraps an ObjCPointerType with source location information.
Definition TypeLoc.h:1617
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1623
Represents a pointer to an Objective C object.
Definition TypeBase.h:8219
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8256
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(QualType P)
Definition Ownership.h:61
OpenCL supported extensions and optional core features.
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
bool isSupported(llvm::StringRef Ext, const LangOptions &LO) const
TypeLoc getWrappedLoc() const
Definition TypeLoc.h:1084
A parameter attribute which changes the argument-passing ABI rule for the parameter.
Definition Attr.h:261
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1446
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1442
Represents a parameter to a function.
Definition Decl.h:1832
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:631
void setUsedAsTypeAttr(bool Used=true)
Definition ParsedAttr.h:360
bool checkAtMostNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at most as many args as Num.
void addAtEnd(ParsedAttr *newAttr)
Definition ParsedAttr.h:848
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:918
void remove(ParsedAttr *ToBeRemoved)
Definition ParsedAttr.h:853
void takeOneFrom(ParsedAttributes &Other, ParsedAttr *PA)
Definition ParsedAttr.h:983
TypeLoc getValueLoc() const
Definition TypeLoc.h:2751
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2756
PipeType - OpenCL20.
Definition TypeBase.h:8407
Pointer-authentication qualifiers.
Definition TypeBase.h:153
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:240
@ MaxKey
The maximum supported pointer-authentication key.
Definition TypeBase.h:230
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1550
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
SourceLocation getPragmaAssumeNonNullLoc() const
The location of the currently-active #pragma clang assume_nonnull begin.
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8667
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1312
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
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:8763
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1090
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8599
SplitQualType getSplitUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8679
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8699
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8624
UnqualTypeLoc getUnqualifiedLoc() const
Definition TypeLoc.h:304
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
void addAddressSpace(LangAS space)
Definition TypeBase.h:598
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
void removeObjCLifetime()
Definition TypeBase.h:552
void addCVRUQualifiers(unsigned mask)
Definition TypeBase.h:507
bool hasRestrict() const
Definition TypeBase.h:478
void removeRestrict()
Definition TypeBase.h:480
static Qualifiers fromCVRMask(unsigned CVR)
Definition TypeBase.h:436
bool empty() const
Definition TypeBase.h:648
void setUnaligned(bool flag)
Definition TypeBase.h:513
void removeVolatile()
Definition TypeBase.h:470
std::string getAsString() const
@ MaxAddressSpace
The maximum supported address space number.
Definition TypeBase.h:374
void addObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:553
void setAmpAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1659
QualType getPointeeType() const
Definition TypeBase.h:3700
bool isSpelledAsLValue() const
Definition TypeBase.h:3691
bool isFunctionDeclarationScope() const
isFunctionDeclarationScope - Return true if this scope is a function prototype scope.
Definition Scope.h:479
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:212
QualType ProcessResourceTypeAttributes(QualType Wrapped)
QualType getInoutParameterType(QualType Ty)
bool isCFError(RecordDecl *D)
IdentifierInfo * getNSErrorIdent()
Retrieve the identifier "NSError".
bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type)
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1423
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7880
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:862
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
QualType BuildParenType(QualType T)
Build a paren type including T.
bool ActOnLateParsedTypeAttrArgument(BoundsAttributedType *BATy, FieldDecl *FD, Expr *Arg)
Supply the parsed argument of a late-parsed bounds attribute to the type built for it by ProcessLateP...
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs (unless they are value dependent ...
Definition SemaAttr.cpp:546
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13849
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1164
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8406
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9507
UnaryTransformType::UTTKind UTTKind
Definition Sema.h:15711
QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc)
BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression is uninstantiated.
bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind, unsigned &IntVal)
QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc)
SemaOpenMP & OpenMP()
Definition Sema.h:1558
std::optional< FunctionEffectMode > ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName)
Try to parse the conditional expression attached to an effect attribute (e.g.
SemaCUDA & CUDA()
Definition Sema.h:1498
@ AcceptSizeless
Relax the normal rules for complete types so that they include sizeless built-in types.
Definition Sema.h:15391
class clang::Sema::DelayedDiagnostics DelayedDiagnostics
QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc)
Build an ext-vector type.
bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS)
Check whether the given variable declaration has a size that fits within the address space it is decl...
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def)
ASTContext & Context
Definition Sema.h:1331
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:229
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateName NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
SemaObjC & ObjC()
Definition Sema.h:1543
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:934
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.
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD=nullptr, CUDAFunctionTarget CFT=CUDAFunctionTarget::InvalidTarget)
Check validaty of calling convention attribute attr.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull)
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc)
Build a bit-precise integer type.
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1798
QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
bool CheckFunctionReturnType(QualType T, SourceLocation Loc)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14730
const LangOptions & getLangOpts() const
Definition Sema.h:927
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc)
bool ProcessLateParsedTypeAttr(LateParsedTypeAttrInfo &LA, QualType &QT)
Validate the late-parsed type attribute LA and wrap QT in a CountAttributedType with no count yet,...
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
Preprocessor & PP
Definition Sema.h:1330
QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
const LangOptions & LangOpts
Definition Sema.h:1329
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2739
SemaHLSL & HLSL()
Definition Sema.h:1508
IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, unsigned Index)
Invent a new identifier for parameters of abbreviated templates.
Definition Sema.cpp:140
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition Sema.h:1864
bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes, bool OrNull)
Check if applying the specified attribute variant from the "counted by" family of attributes to Field...
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6648
void completeExprArrayBound(Expr *E)
bool hasExplicitCallingConv(QualType T)
bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value)
Checks a regparm attribute, returning true if it is ill-formed and otherwise setting numParams to the...
FileNullabilityMap NullabilityMap
A mapping that describes the nullability we've seen in each header file.
Definition Sema.h:15366
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1366
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
bool checkArrayTooLarge(QualType ElementType, const llvm::APSInt &NumElements, SourceLocation Loc, SourceRange Range=SourceRange())
Diagnose an array of NumElements elements of type ElementType that is too large.
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:2476
QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS, CXXRecordDecl *Cls, SourceLocation Loc, DeclarationName Entity)
Build a member pointer type T Class::*.
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:649
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1471
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:1553
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
IdentifierInfo * getNullabilityKeyword(NullabilityKind nullability)
Retrieve the keyword associated.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8343
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
bool ValidateBoundsAttrTypeForTypePosition(QualType Ty, AttributeCommonInfo::Kind AttrKind, SourceLocation AttrLoc, SourceRange AttrRange, unsigned PointerNestLevel, BoundsAttrFlags &Flags)
Check a counted_by-family attribute in type position and initialize Flags from AttrKind.
bool isAcceptable(const NamedDecl *D, AcceptableKind Kind)
Determine whether a declaration is acceptable (visible/reachable).
Definition Sema.h:15823
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14219
SourceManager & getSourceManager() const
Definition Sema.h:932
QualType BuiltinAddReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
bool hasVisibleMergedDefinition(const NamedDecl *Def)
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
@ NTCUK_Destruct
Definition Sema.h:4261
@ NTCUK_Copy
Definition Sema.h:4262
QualType BuildAtomicType(QualType T, SourceLocation Loc)
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX, const FunctionEffectWithCondition &EC, SourceLocation NewAttrLoc)
Warn and return true if adding a function effect to a set would create a conflict.
TypeSourceInfo * ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
TypeResult ActOnTypeName(Declarator &D)
bool isSFINAEContext() const
Definition Sema.h:13940
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15765
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration,...
QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a pointer type.
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc)
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1609
ASTConsumer & Consumer
Definition Sema.h:1332
bool CheckImplicitNullabilityTypeSpecifier(QualType &Type, NullabilityKind Nullability, SourceLocation DiagLoc, bool AllowArrayTypes, bool OverrideExisting)
Check whether a nullability type specifier can be added to the given type through some means not writ...
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
bool CheckDistantExceptionSpec(QualType T)
CheckDistantExceptionSpec - Check if the given type is a pointer or pointer to member to a function w...
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind, SourceLocation Loc)
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind, SourceLocation Loc)
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind, SourceLocation Loc)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:1334
DiagnosticsEngine & Diags
Definition Sema.h:1333
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:928
QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc)
QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity)
Build an array type.
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc)
QualType BuildReadPipeType(QualType T, SourceLocation Loc)
Build a Read-only Pipe type.
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition Sema.h:1859
llvm::BumpPtrAllocator BumpAlloc
Definition Sema.h:1276
QualType BuildWritePipeType(QualType T, SourceLocation Loc)
Build a Write-only Pipe type.
QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:643
QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc)
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2280
bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, AcceptableKind Kind, bool OnlyNeedComplete=false)
QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind, SourceLocation Loc)
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a block pointer type.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Information about a FileID, basically just the logical file that it represents and include stack info...
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
SourceLocation getIncludeLoc() const
This is a discriminated union of FileInfo and ExpansionInfo.
const FileInfo & getFile() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3868
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:3999
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3969
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4988
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:816
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:824
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
Exposes information about the current target.
Definition TargetInfo.h:228
virtual bool hasBitIntType() const
Determine whether the _BitInt type is supported on this target.
Definition TargetInfo.h:697
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts, ArmStreamingKind Mode, llvm::StringMap< bool > *FeatureMap=nullptr) const
Returns target-specific min and max values VScale_Range.
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition TargetInfo.h:497
virtual bool allowHalfArgsAndReturns() const
Whether half args and returns are supported.
Definition TargetInfo.h:710
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:686
virtual bool hasFloat16Type() const
Determine whether the _Float16 type is supported on this target.
Definition TargetInfo.h:716
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:728
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:713
virtual size_t getMaxBitIntWidth() const
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition TargetInfo.h:719
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
@ Template
A single template declaration.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:1953
void copy(TemplateSpecializationTypeLoc Loc)
Definition TypeLoc.h:1956
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition TypeBase.h:3425
const Type * getTypeForDecl() const
Definition Decl.h:3689
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition TypeLoc.h:349
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:171
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:217
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition TypeLoc.h:165
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:892
void * getOpaqueData() const
Get the pointer where source information is stored.
Definition TypeLoc.h:143
void copy(TypeLoc other)
Copies the other type loc into this one.
Definition TypeLoc.cpp:169
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition TypeLoc.h:211
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
void setUnmodifiedTInfo(TypeSourceInfo *TI) const
Definition TypeLoc.h:2296
A container of type source information.
Definition TypeBase.h:8549
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8560
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2549
bool isBlockPointerType() const
Definition TypeBase.h:8835
bool isVoidType() const
Definition TypeBase.h:9200
bool isBooleanType() const
Definition TypeBase.h:9341
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2897
bool isIncompleteArrayType() const
Definition TypeBase.h:8922
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2299
bool isUndeducedAutoType() const
Definition TypeBase.h:9011
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:8914
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isPointerType() const
Definition TypeBase.h:8815
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
NestedNameSpecifier getPrefix() const
If this type represents a qualified-id, this returns its nested name specifier.
Definition Type.cpp:2099
bool isSizelessBuiltinType() const
Definition Type.cpp:2751
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2829
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:595
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool canHaveNullability(bool ResultIfUnknown=true) const
Determine whether the given type can have a nullability specifier applied to it, i....
Definition Type.cpp:5338
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2866
bool isImageType() const
Definition TypeBase.h:9079
bool isPipeType() const
Definition TypeBase.h:9086
bool isBitIntType() const
Definition TypeBase.h:9090
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8938
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool isChar16Type() const
Definition Type.cpp:2341
bool isHalfType() const
Definition TypeBase.h:9208
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2469
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2779
bool isMemberPointerType() const
Definition TypeBase.h:8896
bool isAtomicType() const
Definition TypeBase.h:9007
bool isObjCObjectType() const
Definition TypeBase.h:8998
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9347
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
bool isFunctionType() const
Definition TypeBase.h:8811
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2879
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2533
bool isAnyPointerType() const
Definition TypeBase.h:8823
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isSamplerT() const
Definition TypeBase.h:9059
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:786
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition Type.cpp:5578
bool isRecordType() const
Definition TypeBase.h:8942
bool isObjCRetainableType() const
Definition Type.cpp:5609
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5325
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3818
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3713
void setParensRange(SourceRange range)
Definition TypeLoc.h:2255
void setTypeofLoc(SourceLocation Loc)
Definition TypeLoc.h:2231
void setParensRange(SourceRange Range)
Definition TypeLoc.h:2399
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2375
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition TypeLoc.h:2387
Wrapper of type source information for a type with no direct qualifiers.
Definition TypeLoc.h:274
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:283
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1146
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1319
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1192
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3437
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1326
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2076
Represents a GCC generic vector type.
Definition TypeBase.h:4398
VectorKind getVectorKind() const
Definition TypeBase.h:4418
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
Defines the clang::TargetInfo interface.
const internal::VariadicDynCastAllOfMatcher< Decl, TypedefDecl > typedefDecl
Matches typedef declarations.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Decl, RecordDecl > recordDecl
Matches class, struct, and union declarations.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_auto_type
Definition Specifiers.h:95
@ TST_auto
Definition Specifiers.h:93
@ TST_unspecified
Definition Specifiers.h:57
@ TST_typename
Definition Specifiers.h:85
@ TST_decltype_auto
Definition Specifiers.h:94
VectorKind getRVVFixedLengthDataVectorKind(int LMulLog2)
Inverse of getRVVFixedLengthDataLMulLog2().
Definition TypeBase.h:4330
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:216
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus26
@ CPlusPlus17
@ ExpectedParameterOrImplicitObjectParameter
@ ExpectedFunctionWithProtoType
@ GNUAutoType
__auto_type (GNU extension)
Definition TypeBase.h:1846
@ DecltypeAuto
decltype(auto)
Definition TypeBase.h:1843
llvm::StringRef getParameterABISpelling(ParameterABI kind)
FunctionEffectMode
Used with attributes/effects with a boolean condition, e.g. nonblocking.
Definition Sema.h:452
LLVM_READONLY bool isAsciiIdentifierContinue(unsigned char c)
Definition CharInfo.h:61
QualType pointeeType(QualType T)
CUDAFunctionTarget
Definition Cuda.h:65
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:350
@ Nullable
Values of this type can be null.
Definition Specifiers.h:354
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:359
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:352
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1801
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1804
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
llvm::PointerUnion< Expr *, IdentifierLoc * > ArgsUnion
A union of the various pointer types that can be passed to an ParsedAttr as an argument.
Definition ParsedAttr.h:103
@ Success
Annotation was successful.
Definition Parser.h:65
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
VectorKind getRVVFixedLengthMaskVectorKind(unsigned RatioLog2, unsigned SubByteLanes)
Inverse of getRVVFixedLengthMaskRatioLog2() and getRVVFixedLengthMaskSubByteLanes().
Definition TypeBase.h:4382
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:1106
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1104
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1102
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1098
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1096
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1094
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1088
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1100
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1090
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1092
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:919
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
@ AANT_ArgumentIntegerConstant
@ AANT_ArgumentString
DeclaratorContext
Definition DeclSpec.h:1946
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
llvm::StringRef getNullabilitySpelling(NullabilityKind kind, bool isContextSensitive=false)
Retrieve the spelling of the given nullability kind.
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3817
@ SwiftAsyncContext
This parameter (which must have pointer type) uses the special Swift asynchronous context-pointer ABI...
Definition Specifiers.h:403
@ SwiftErrorResult
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
Definition Specifiers.h:393
@ Ordinary
This parameter uses ordinary ABI rules for its type.
Definition Specifiers.h:384
@ SwiftIndirectResult
This parameter (which must have pointer type) is a Swift indirect result parameter.
Definition Specifiers.h:388
@ SwiftContext
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment.
Definition Specifiers.h:398
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:322
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
static bool isBlockPointer(Expr *Arg)
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6171
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6176
@ Struct
The "struct" keyword.
Definition TypeBase.h:6173
@ Class
The "class" keyword.
Definition TypeBase.h:6182
@ Union
The "union" keyword.
Definition TypeBase.h:6179
@ Enum
The "enum" keyword.
Definition TypeBase.h:6185
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition CharInfo.h:108
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:555
LangAS
Defines the address space values used by the address space qualifier of QualType.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
@ Deduced
The normal deduced case.
Definition TypeBase.h:1818
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1813
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition Specifiers.h:414
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:640
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:383
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
@ CC_Swift
Definition Specifiers.h:296
@ CC_DeviceKernel
Definition Specifiers.h:295
@ CC_SwiftAsync
Definition Specifiers.h:297
@ CC_X86StdCall
Definition Specifiers.h:284
@ CC_X86FastCall
Definition Specifiers.h:285
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4243
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4252
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4237
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4240
@ Neon
is ARM Neon vector
Definition TypeBase.h:4246
@ Generic
not a target-specific vector type
Definition TypeBase.h:4234
@ NeonPoly
is ARM Neon polynomial vector
Definition TypeBase.h:4249
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4255
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:837
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:844
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:6146
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2250
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
@ Implicit
An implicit conversion.
Definition Sema.h:433
OptionalUnsigned< NullabilityKind > NullabilityKindOrNone
Definition Specifiers.h:366
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:1404
unsigned TypeQuals
The type qualifiers for the array: const/volatile/restrict/__unaligned/_Atomic.
Definition DeclSpec.h:1396
unsigned hasStatic
True if this dimension included the 'static' keyword.
Definition DeclSpec.h:1400
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition DeclSpec.h:1409
unsigned TypeQuals
For now, sema will catch these as invalid.
Definition DeclSpec.h:1693
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition DeclSpec.h:1456
SourceLocation getTrailingReturnTypeLoc() const
Get the trailing-return-type location for this function declarator.
Definition DeclSpec.h:1683
SourceLocation getLParenLoc() const
Definition DeclSpec.h:1598
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition DeclSpec.h:1674
TypeAndRange * Exceptions
Pointer to a new[]'d array of TypeAndRange objects that contain the types in the function's dynamic e...
Definition DeclSpec.h:1528
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1516
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition DeclSpec.h:1677
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1465
SourceLocation getExceptionSpecLocBeg() const
Definition DeclSpec.h:1604
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1519
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1617
SourceLocation getRParenLoc() const
Definition DeclSpec.h:1602
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:1600
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1491
unsigned getNumExceptions() const
Get the number of dynamic exception specifications.
Definition DeclSpec.h:1660
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1649
unsigned isAmbiguous
Can this declaration be a constructor-style initializer?
Definition DeclSpec.h:1460
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1450
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1642
SourceRange getExceptionSpecRange() const
Definition DeclSpec.h:1612
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition DeclSpec.h:1655
Expr * NoexceptExpr
Pointer to the expression in the noexcept-specifier of this function, if it has one.
Definition DeclSpec.h:1532
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
Definition DeclSpec.h:1702
SourceLocation StarLoc
Location of the '*' token.
Definition DeclSpec.h:1704
const IdentifierInfo * Ident
Definition DeclSpec.h:1422
SourceLocation OverflowBehaviorLoc
The location of an __ob_wrap or __ob_trap qualifier, if any.
Definition DeclSpec.h:1372
SourceLocation RestrictQualLoc
The location of the restrict-qualifier, if any.
Definition DeclSpec.h:1363
SourceLocation ConstQualLoc
The location of the const-qualifier, if any.
Definition DeclSpec.h:1357
SourceLocation VolatileQualLoc
The location of the volatile-qualifier, if any.
Definition DeclSpec.h:1360
SourceLocation UnalignedQualLoc
The location of the __unaligned-qualifier, if any.
Definition DeclSpec.h:1369
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/unaligned/atomic.
Definition DeclSpec.h:1354
SourceLocation AtomicQualLoc
The location of the _Atomic-qualifier, if any.
Definition DeclSpec.h:1366
unsigned OverflowBehaviorIsWrap
Whether the overflow behavior qualifier is wrap (true) or trap (false).
Definition DeclSpec.h:1377
bool LValueRef
True if this is an lvalue reference, false if it's an rvalue reference.
Definition DeclSpec.h:1387
bool HasRestrict
The type qualifier: restrict. [GNU] C++ extension.
Definition DeclSpec.h:1385
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1330
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1751
SourceLocation EndLoc
EndLoc - If valid, the place where this chunck ends.
Definition DeclSpec.h:1340
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:1728
BlockPointerTypeInfo Cls
Definition DeclSpec.h:1731
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1732
ArrayTypeInfo Arr
Definition DeclSpec.h:1729
SourceLocation Loc
Loc - The place where this type was defined.
Definition DeclSpec.h:1338
FunctionTypeInfo Fun
Definition DeclSpec.h:1730
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
PointerTypeInfo Ptr
Definition DeclSpec.h:1727
Describes whether we've seen any nullability information for the given file.
Definition Sema.h:246
SourceLocation PointerEndLoc
The end location for the first pointer declarator in the file.
Definition Sema.h:253
SourceLocation PointerLoc
The first pointer declarator (of any pointer kind) in the file that does not have a corresponding nul...
Definition Sema.h:249
bool SawTypeNullability
Whether we saw any type nullability annotations in the given file.
Definition Sema.h:259
uint8_t PointerKind
Which kind of pointer declarator we saw.
Definition Sema.h:256
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition TypeBase.h:5285
Holds information about the various types of exception specification.
Definition TypeBase.h:5605
Extra information about a function prototype.
Definition TypeBase.h:5633
FunctionTypeExtraAttributeInfo ExtraAttributeInfo
Definition TypeBase.h:5641
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5638
void setArmSMEAttribute(AArch64SMETypeAttributes Kind, bool Enable=true)
Definition TypeBase.h:5687
StringRef CFISalt
A CFI "salt" that differentiates functions with the same prototype.
Definition TypeBase.h:5010
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition DeclSpec.h:3004
unsigned AutoTemplateParameterDepth
If this is a generic lambda or abbreviated function template, use this as the depth of each 'auto' pa...
Definition DeclSpec.h:2995
static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
Definition Type.cpp:3481
The part of a late-parsed type attribute that Sema reads and fills in during type construction.
Definition DeclSpec.h:256
BoundsAttributedType * TypeToComplete
The type built for this attribute during type construction, still missing the argument that hasn't be...
Definition DeclSpec.h:269
Describes how types, statements, expressions, and declarations should be printed.
Abstract class used to diagnose incomplete types.
Definition Sema.h:8420
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:871
SplitQualType getSingleStepDesugaredType() const
Definition TypeBase.h:8571
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:873
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:876
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.