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
5983// FIXME: Also handle attributes on the decl-specifier, declarator and
5984// declaration. Matrix type locations need the same handling.
5986 const ParsedAttributesView &Attrs) {
5987 auto Kind = isa<ExtVectorType>(VTL.getTypePtr())
5988 ? ParsedAttr::AT_ExtVectorType
5989 : ParsedAttr::AT_VectorSize;
5990 for (const ParsedAttr &AL : Attrs) {
5991 if (AL.getKind() == Kind && !AL.isInvalid() && AL.getNumArgs() == 1) {
5992 VTL.setAttrNameLoc(AL.getLoc());
5993 VTL.setSizeExpr(AL.getArgAsExpr(0));
5994 return;
5995 }
5996 }
5997
5998 // The attribute may be on the declarator rather than this chunk, or the
5999 // vector may use a target-specific attribute. Keep the default locations
6000 // when no matching attribute is present.
6001}
6002
6003static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
6004 SourceLocation Loc;
6005 switch (Chunk.Kind) {
6010 llvm_unreachable("cannot be _Atomic qualified");
6011
6013 Loc = Chunk.Ptr.AtomicQualLoc;
6014 break;
6015
6019 // FIXME: Provide a source location for the _Atomic keyword.
6020 break;
6021 }
6022
6023 ATL.setKWLoc(Loc);
6025}
6026
6027namespace {
6028 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
6029 Sema &SemaRef;
6030 ASTContext &Context;
6031 TypeProcessingState &State;
6032 const DeclSpec &DS;
6033
6034 public:
6035 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
6036 const DeclSpec &DS)
6037 : SemaRef(S), Context(Context), State(State), DS(DS) {}
6038
6039 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6040 Visit(TL.getModifiedLoc());
6041 fillAttributedTypeLoc(TL, State);
6042 }
6043 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6044 Visit(TL.getWrappedLoc());
6045 }
6046 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
6047 Visit(TL.getWrappedLoc());
6048 }
6049 void VisitHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL) {
6050 Visit(TL.getWrappedLoc());
6052 }
6053 void VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {}
6054 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6055 Visit(TL.getInnerLoc());
6056 TL.setExpansionLoc(
6057 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6058 }
6059 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6060 Visit(TL.getUnqualifiedLoc());
6061 }
6062 // Allow to fill pointee's type locations, e.g.,
6063 // int __attr * __attr * __attr *p;
6064 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
6065 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6066 if (DS.getTypeSpecType() == TST_typename) {
6067 TypeSourceInfo *TInfo = nullptr;
6069 if (TInfo) {
6070 TL.copy(TInfo->getTypeLoc().castAs<TypedefTypeLoc>());
6071 return;
6072 }
6073 }
6074 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6075 ? DS.getTypeSpecTypeLoc()
6076 : SourceLocation(),
6079 }
6080 void VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6081 if (DS.getTypeSpecType() == TST_typename) {
6082 TypeSourceInfo *TInfo = nullptr;
6084 if (TInfo) {
6085 TL.copy(TInfo->getTypeLoc().castAs<UnresolvedUsingTypeLoc>());
6086 return;
6087 }
6088 }
6089 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6090 ? DS.getTypeSpecTypeLoc()
6091 : SourceLocation(),
6094 }
6095 void VisitUsingTypeLoc(UsingTypeLoc TL) {
6096 if (DS.getTypeSpecType() == TST_typename) {
6097 TypeSourceInfo *TInfo = nullptr;
6099 if (TInfo) {
6100 TL.copy(TInfo->getTypeLoc().castAs<UsingTypeLoc>());
6101 return;
6102 }
6103 }
6104 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6105 ? DS.getTypeSpecTypeLoc()
6106 : SourceLocation(),
6109 }
6110 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6112 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6113 // addition field. What we have is good enough for display of location
6114 // of 'fixit' on interface name.
6115 TL.setNameEndLoc(DS.getEndLoc());
6116 }
6117 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6118 TypeSourceInfo *RepTInfo = nullptr;
6119 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6120 TL.copy(RepTInfo->getTypeLoc());
6121 }
6122 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6123 TypeSourceInfo *RepTInfo = nullptr;
6124 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6125 TL.copy(RepTInfo->getTypeLoc());
6126 }
6127 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6128 TypeSourceInfo *TInfo = nullptr;
6130
6131 // If we got no declarator info from previous Sema routines,
6132 // just fill with the typespec loc.
6133 if (!TInfo) {
6134 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
6135 return;
6136 }
6137
6138 TypeLoc OldTL = TInfo->getTypeLoc();
6139 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6140 assert(TL.getRAngleLoc() ==
6141 OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6142 }
6143 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6148 }
6149 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6154 assert(DS.getRepAsType());
6155 TypeSourceInfo *TInfo = nullptr;
6157 TL.setUnmodifiedTInfo(TInfo);
6158 }
6159 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6163 }
6164 void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6166 TypeSourceInfo *TInfo = nullptr;
6168 TL.copy(TInfo->getTypeLoc());
6169 }
6170 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6171 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6174 assert(DS.getRepAsType());
6175 TypeSourceInfo *TInfo = nullptr;
6177 TL.setUnderlyingTInfo(TInfo);
6178 }
6179 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6180 // By default, use the source location of the type specifier.
6182 if (TL.needsExtraLocalData()) {
6183 // Set info for the written builtin specifiers.
6185 // Try to have a meaningful source location.
6186 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6188 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6190 }
6191 }
6192 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6193 assert(DS.getTypeSpecType() == TST_typename);
6194 TypeSourceInfo *TInfo = nullptr;
6196 assert(TInfo);
6197 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6198 }
6199 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6200 assert(DS.getTypeSpecType() == TST_auto ||
6207 if (!DS.isConstrainedAuto())
6208 return;
6209 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6210 if (!TemplateId)
6211 return;
6212
6213 NestedNameSpecifierLoc NNS =
6214 (DS.getTypeSpecScope().isNotEmpty()
6216 : NestedNameSpecifierLoc());
6217 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6218 TemplateId->RAngleLoc);
6219 if (TemplateId->NumArgs > 0) {
6220 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6221 TemplateId->NumArgs);
6222 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6223 }
6224 DeclarationNameInfo DNI = Context.getNameForTemplate(
6225 TL.getTypePtr()->getTypeConstraintConcept(),
6226 TemplateId->TemplateNameLoc);
6227
6228 NamedDecl *FoundDecl;
6229 if (auto TN = TemplateId->Template.get();
6230 UsingShadowDecl *USD = TN.getAsUsingShadowDecl())
6231 FoundDecl = cast<NamedDecl>(USD);
6232 else
6233 FoundDecl = cast_if_present<NamedDecl>(TN.getAsTemplateDecl());
6234
6235 auto *CR = ConceptReference::Create(
6236 Context, NNS, TemplateId->TemplateKWLoc, DNI, FoundDecl,
6237 /*NamedDecl=*/TL.getTypePtr()->getTypeConstraintConcept(),
6238 ASTTemplateArgumentListInfo::Create(Context, TemplateArgsInfo));
6239 TL.setConceptReference(CR);
6240 }
6241 void VisitDeducedTemplateSpecializationTypeLoc(
6242 DeducedTemplateSpecializationTypeLoc TL) {
6243 assert(DS.getTypeSpecType() == TST_typename);
6244 TypeSourceInfo *TInfo = nullptr;
6246 assert(TInfo);
6247 TL.copy(
6248 TInfo->getTypeLoc().castAs<DeducedTemplateSpecializationTypeLoc>());
6249 }
6250 void VisitTagTypeLoc(TagTypeLoc TL) {
6251 if (DS.getTypeSpecType() == TST_typename) {
6252 TypeSourceInfo *TInfo = nullptr;
6254 if (TInfo) {
6255 TL.copy(TInfo->getTypeLoc().castAs<TagTypeLoc>());
6256 return;
6257 }
6258 }
6259 TL.setElaboratedKeywordLoc(TL.getTypePtr()->getKeyword() !=
6260 ElaboratedTypeKeyword::None
6261 ? DS.getTypeSpecTypeLoc()
6262 : SourceLocation());
6265 }
6266 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6267 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6268 // or an _Atomic qualifier.
6272
6273 TypeSourceInfo *TInfo = nullptr;
6275 assert(TInfo);
6277 } else {
6278 TL.setKWLoc(DS.getAtomicSpecLoc());
6279 // No parens, to indicate this was spelled as an _Atomic qualifier.
6280 TL.setParensRange(SourceRange());
6281 Visit(TL.getValueLoc());
6282 }
6283 }
6284
6285 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6287
6288 TypeSourceInfo *TInfo = nullptr;
6291 }
6292
6293 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6295 }
6296
6297 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6299 }
6300
6301 void VisitTypeLoc(TypeLoc TL) {
6302 // FIXME: add other typespec types and change this to an assert.
6303 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6304 }
6305 };
6306
6307 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6308 ASTContext &Context;
6309 TypeProcessingState &State;
6310 const DeclaratorChunk &Chunk;
6311
6312 public:
6313 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6314 const DeclaratorChunk &Chunk)
6315 : Context(Context), State(State), Chunk(Chunk) {}
6316
6317 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6318 llvm_unreachable("qualified type locs not expected here!");
6319 }
6320 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6321 llvm_unreachable("decayed type locs not expected here!");
6322 }
6323 void VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6324 llvm_unreachable("array parameter type locs not expected here!");
6325 }
6326
6327 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6328 fillAttributedTypeLoc(TL, State);
6329 }
6330 void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
6331 // nothing
6332 }
6333 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6334 // nothing
6335 }
6336 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
6337 // nothing
6338 }
6339 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6340 // nothing
6341 }
6342 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6343 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6344 TL.setCaretLoc(Chunk.Loc);
6345 }
6346 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6347 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6348 TL.setStarLoc(Chunk.Loc);
6349 }
6350 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6351 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6352 TL.setStarLoc(Chunk.Loc);
6353 }
6354 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6355 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6356 TL.setStarLoc(Chunk.Mem.StarLoc);
6357 TL.setQualifierLoc(Chunk.Mem.Scope().getWithLocInContext(Context));
6358 }
6359 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6360 assert(Chunk.Kind == DeclaratorChunk::Reference);
6361 // 'Amp' is misleading: this might have been originally
6362 /// spelled with AmpAmp.
6363 TL.setAmpLoc(Chunk.Loc);
6364 }
6365 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6366 assert(Chunk.Kind == DeclaratorChunk::Reference);
6367 assert(!Chunk.Ref.LValueRef);
6368 TL.setAmpAmpLoc(Chunk.Loc);
6369 }
6370 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6371 assert(Chunk.Kind == DeclaratorChunk::Array);
6372 TL.setLBracketLoc(Chunk.Loc);
6373 TL.setRBracketLoc(Chunk.EndLoc);
6374 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6375 }
6376 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6377 assert(Chunk.Kind == DeclaratorChunk::Function);
6378 TL.setLocalRangeBegin(Chunk.Loc);
6379 TL.setLocalRangeEnd(Chunk.EndLoc);
6380
6381 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6382 TL.setLParenLoc(FTI.getLParenLoc());
6383 TL.setRParenLoc(FTI.getRParenLoc());
6384 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6385 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6386 TL.setParam(tpi++, Param);
6387 }
6389 }
6390 void VisitParenTypeLoc(ParenTypeLoc TL) {
6391 assert(Chunk.Kind == DeclaratorChunk::Paren);
6392 TL.setLParenLoc(Chunk.Loc);
6393 TL.setRParenLoc(Chunk.EndLoc);
6394 }
6395 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6396 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6397 TL.setKWLoc(Chunk.Loc);
6398 }
6399 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6400 TL.setNameLoc(Chunk.Loc);
6401 }
6402 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6403 TL.setExpansionLoc(Chunk.Loc);
6404 }
6405 void VisitVectorTypeLoc(VectorTypeLoc TL) {
6406 TL.initializeLocal(Context, Chunk.Loc);
6407 fillVectorTypeLoc(TL, Chunk.getAttrs());
6408 }
6409 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6410 TL.initializeLocal(Context, Chunk.Loc);
6411 }
6412 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6413 fillAtomicQualLoc(TL, Chunk);
6414 }
6415 void
6416 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6417 TL.initializeLocal(Context, Chunk.Loc);
6418 }
6419 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6420 fillMatrixTypeLoc(TL, Chunk.getAttrs());
6421 }
6422
6423 void VisitTypeLoc(TypeLoc TL) {
6424 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6425 }
6426 };
6427} // end anonymous namespace
6428
6432 for (const ParsedAttributesView *Attrs : AttrLists) {
6433 for (const ParsedAttr &AL : *Attrs) {
6434 // Skip invalid or malformed attributes; they did not produce a type.
6435 if (AL.getKind() != ParsedAttr::AT_AddressSpace || AL.isInvalid() ||
6436 AL.getNumArgs() != 1 || !AL.isArgExpr(0))
6437 continue;
6438 DASTL.setAttrNameLoc(AL.getLoc());
6439 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6441 return;
6442 }
6443 }
6444
6445 llvm_unreachable(
6446 "no address_space attribute found at the expected location!");
6447}
6448
6449/// Create and instantiate a TypeSourceInfo with type source information.
6450///
6451/// \param T QualType referring to the type as written in source code.
6452///
6453/// \param ReturnTypeInfo For declarators whose return type does not show
6454/// up in the normal place in the declaration specifiers (such as a C++
6455/// conversion function), this pointer will refer to a type source information
6456/// for that return type.
6457static TypeSourceInfo *
6458GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6459 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6460 Sema &S = State.getSema();
6461 Declarator &D = State.getDeclarator();
6462
6464 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6465
6466 // Handle parameter packs whose type is a pack expansion.
6468 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6469 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6470 }
6471
6472 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6473 // Microsoft property fields can have multiple sizeless array chunks
6474 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6475 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6477 continue;
6478
6479 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6480 // declarator chunk.
6481 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6483 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6484 }
6485
6486 bool HasDesugaredTypeLoc = true;
6487 while (HasDesugaredTypeLoc) {
6488 switch (CurrTL.getTypeLocClass()) {
6489 case TypeLoc::MacroQualified: {
6490 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6491 TL.setExpansionLoc(
6492 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6493 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6494 break;
6495 }
6496
6497 case TypeLoc::Attributed: {
6498 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6499 fillAttributedTypeLoc(TL, State);
6500 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6501 break;
6502 }
6503
6504 case TypeLoc::Adjusted:
6505 case TypeLoc::BTFTagAttributed: {
6506 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6507 break;
6508 }
6509
6510 case TypeLoc::DependentAddressSpace: {
6511 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6512 // An attribute written after the declarator-id appertains to the
6513 // declared entity, not to a chunk, so every attribute list of the
6514 // declarator has to be searched.
6516 &D.getAttributes(),
6519 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6520 break;
6521 }
6522
6523 default:
6524 HasDesugaredTypeLoc = false;
6525 break;
6526 }
6527 }
6528
6529 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6530 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6531 }
6532
6533 // If we have different source information for the return type, use
6534 // that. This really only applies to C++ conversion functions.
6535 if (ReturnTypeInfo) {
6536 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6537 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6538 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6539 } else {
6540 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6541 }
6542
6543 return TInfo;
6544}
6545
6546/// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6548 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6549 // and Sema during declaration parsing. Try deallocating/caching them when
6550 // it's appropriate, instead of allocating them and keeping them around.
6551 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(sizeof(LocInfoType),
6552 alignof(LocInfoType));
6553 new (LocT) LocInfoType(T, TInfo);
6554 assert(LocT->getTypeClass() != T->getTypeClass() &&
6555 "LocInfoType's TypeClass conflicts with an existing Type class");
6556 return ParsedType::make(QualType(LocT, 0));
6557}
6558
6560 const PrintingPolicy &Policy) const {
6561 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6562 " was used directly instead of getting the QualType through"
6563 " GetTypeFromParser");
6564}
6565
6567 // C99 6.7.6: Type names have no identifier. This is already validated by
6568 // the parser.
6569 assert(D.getIdentifier() == nullptr &&
6570 "Type name should have no identifier!");
6571
6573 QualType T = TInfo->getType();
6574 if (D.isInvalidType())
6575 return true;
6576
6577 // Make sure there are no unused decl attributes on the declarator.
6578 // We don't want to do this for ObjC parameters because we're going
6579 // to apply them to the actual parameter declaration.
6580 // Likewise, we don't want to do this for alias declarations, because
6581 // we are actually going to build a declaration from this eventually.
6586
6587 if (getLangOpts().CPlusPlus) {
6588 // Check that there are no default arguments (C++ only).
6590 }
6591
6592 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
6593 const AutoType *AT = TL.getTypePtr();
6594 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
6595 }
6596 return CreateParsedType(T, TInfo);
6597}
6598
6599//===----------------------------------------------------------------------===//
6600// Type Attribute Processing
6601//===----------------------------------------------------------------------===//
6602
6603/// Build an AddressSpace index from a constant expression and diagnose any
6604/// errors related to invalid address_spaces. Returns true on successfully
6605/// building an AddressSpace index.
6606static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6607 const Expr *AddrSpace,
6608 SourceLocation AttrLoc) {
6609 if (!AddrSpace->isValueDependent()) {
6610 std::optional<llvm::APSInt> OptAddrSpace =
6611 AddrSpace->getIntegerConstantExpr(S.Context);
6612 if (!OptAddrSpace) {
6613 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6614 << "'address_space'" << AANT_ArgumentIntegerConstant
6615 << AddrSpace->getSourceRange();
6616 return false;
6617 }
6618 llvm::APSInt &addrSpace = *OptAddrSpace;
6619
6620 // Bounds checking.
6621 if (addrSpace.isSigned()) {
6622 if (addrSpace.isNegative()) {
6623 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6624 << AddrSpace->getSourceRange();
6625 return false;
6626 }
6627 addrSpace.setIsSigned(false);
6628 }
6629
6630 llvm::APSInt max(addrSpace.getBitWidth());
6631 max =
6633
6634 if (addrSpace > max) {
6635 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6636 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6637 return false;
6638 }
6639
6640 ASIdx =
6641 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6642 return true;
6643 }
6644
6645 // Default value for DependentAddressSpaceTypes
6646 ASIdx = LangAS::Default;
6647 return true;
6648}
6649
6651 SourceLocation AttrLoc) {
6652 if (!AddrSpace->isValueDependent()) {
6653 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6654 AttrLoc))
6655 return QualType();
6656
6657 return Context.getAddrSpaceQualType(T, ASIdx);
6658 }
6659
6660 // A check with similar intentions as checking if a type already has an
6661 // address space except for on a dependent types, basically if the
6662 // current type is already a DependentAddressSpaceType then its already
6663 // lined up to have another address space on it and we can't have
6664 // multiple address spaces on the one pointer indirection
6665 if (T->getAs<DependentAddressSpaceType>()) {
6666 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6667 return QualType();
6668 }
6669
6670 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6671}
6672
6674 SourceLocation AttrLoc) {
6675 LangAS ASIdx;
6676 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6677 return QualType();
6678 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6679}
6680
6682 TypeProcessingState &State) {
6683 Sema &S = State.getSema();
6684
6685 // Ensure the argument is a string.
6686 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6687 if (!StrLiteral) {
6688 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6690 Attr.setInvalid();
6691 return;
6692 }
6693
6694 ASTContext &Ctx = S.Context;
6695 StringRef BTFTypeTag = StrLiteral->getString();
6696 Type = State.getBTFTagAttributedType(
6697 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6698}
6699
6700/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6701/// specified type. The attribute contains 1 argument, the id of the address
6702/// space for the type.
6704 const ParsedAttr &Attr,
6705 TypeProcessingState &State) {
6706 Sema &S = State.getSema();
6707
6708 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6709 // qualified by an address-space qualifier."
6710 if (Type->isFunctionType()) {
6711 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6712 Attr.setInvalid();
6713 return;
6714 }
6715
6716 LangAS ASIdx;
6717 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6718
6719 // Check the attribute arguments.
6720 if (Attr.getNumArgs() != 1) {
6721 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6722 << 1;
6723 Attr.setInvalid();
6724 return;
6725 }
6726
6727 Expr *ASArgExpr = Attr.getArgAsExpr(0);
6728 LangAS ASIdx;
6729 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6730 Attr.setInvalid();
6731 return;
6732 }
6733
6734 ASTContext &Ctx = S.Context;
6735 auto *ASAttr =
6736 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6737
6738 // If the expression is not value dependent (not templated), then we can
6739 // apply the address space qualifiers just to the equivalent type.
6740 // Otherwise, we make an AttributedType with the modified and equivalent
6741 // type the same, and wrap it in a DependentAddressSpaceType. When this
6742 // dependent type is resolved, the qualifier is added to the equivalent type
6743 // later.
6744 QualType T;
6745 if (!ASArgExpr->isValueDependent()) {
6746 QualType EquivType =
6747 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6748 if (EquivType.isNull()) {
6749 Attr.setInvalid();
6750 return;
6751 }
6752 T = State.getAttributedType(ASAttr, Type, EquivType);
6753 } else {
6754 T = State.getAttributedType(ASAttr, Type, Type);
6755 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6756 }
6757
6758 if (!T.isNull())
6759 Type = T;
6760 else
6761 Attr.setInvalid();
6762 } else {
6763 // The keyword-based type attributes imply which address space to use.
6764 // The SYCL address space attributes are available in both SYCL host and
6765 // device compilation.
6766 ASIdx =
6767 S.getLangOpts().isSYCL() ? Attr.asSYCLLangAS() : Attr.asOpenCLLangAS();
6768 if (S.getLangOpts().HLSL)
6769 ASIdx = Attr.asHLSLLangAS();
6770
6771 if (ASIdx == LangAS::Default)
6772 llvm_unreachable("Invalid address space");
6773
6774 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6775 Attr.getLoc())) {
6776 Attr.setInvalid();
6777 return;
6778 }
6779
6781 }
6782}
6783
6785 TypeProcessingState &State) {
6786 Sema &S = State.getSema();
6787
6788 // Check for -fexperimental-overflow-behavior-types
6789 if (!S.getLangOpts().OverflowBehaviorTypes) {
6790 S.Diag(Attr.getLoc(), diag::warn_overflow_behavior_attribute_disabled)
6791 << Attr << 1;
6792 Attr.setInvalid();
6793 return;
6794 }
6795
6796 // Check the number of attribute arguments.
6797 if (Attr.getNumArgs() != 1) {
6798 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6799 << Attr << 1;
6800 Attr.setInvalid();
6801 return;
6802 }
6803
6804 // Verify we aren't dealing with an atomic type
6805 if (Type->isAtomicType()) {
6806 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_atomic_type)
6807 << Attr << Type.getAsString() << 0; // 0 for attribute
6808 Attr.setInvalid();
6809 return;
6810 }
6811
6812 // Check that the underlying type is an integer type
6813 if (!Type->isIntegerType()) {
6814 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_non_integer_type)
6815 << Attr << Type.getAsString() << 0; // 0 for attribute
6816 Attr.setInvalid();
6817 return;
6818 }
6819
6820 StringRef KindName = "";
6821 IdentifierInfo *Ident = nullptr;
6822
6823 if (Attr.isArgIdent(0)) {
6824 Ident = Attr.getArgAsIdent(0)->getIdentifierInfo();
6825 KindName = Ident->getName();
6826 }
6827
6828 // Support identifier or string argument types. Failure to provide one of
6829 // these two types results in a diagnostic that hints towards using string
6830 // arguments (either "wrap" or "trap") as this is the most common use
6831 // pattern.
6832 if (!Ident) {
6833 auto *Str = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6834 if (Str)
6835 KindName = Str->getString();
6836 else {
6837 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6839 Attr.setInvalid();
6840 return;
6841 }
6842 }
6843
6844 OverflowBehaviorType::OverflowBehaviorKind Kind;
6845 if (KindName == "wrap") {
6846 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
6847 } else if (KindName == "trap") {
6848 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
6849 } else {
6850 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_unknown_ident)
6851 << KindName << Attr;
6852 Attr.setInvalid();
6853 return;
6854 }
6855
6856 // Check for mixed specifier/attribute usage
6857 const DeclSpec &DS = State.getDeclarator().getDeclSpec();
6858 if (DS.isWrapSpecified() || DS.isTrapSpecified()) {
6859 // We have both specifier and attribute on the same type. If
6860 // OverflowBehaviorKinds are the same we can just warn.
6861 OverflowBehaviorType::OverflowBehaviorKind SpecifierKind =
6862 DS.isWrapSpecified() ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
6863 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
6864
6865 if (SpecifierKind != Kind) {
6866 StringRef SpecifierName = DS.isWrapSpecified() ? "wrap" : "trap";
6867 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors)
6868 << 1 << SpecifierName << KindName;
6869 Attr.setInvalid();
6870 return;
6871 }
6872 S.Diag(Attr.getLoc(), diag::warn_redundant_overflow_behaviors_mixed)
6873 << KindName;
6874 Attr.setInvalid();
6875 return;
6876 }
6877
6878 // Check for conflicting overflow behavior attributes
6879 if (const auto *ExistingOBT = Type->getAs<OverflowBehaviorType>()) {
6880 OverflowBehaviorType::OverflowBehaviorKind ExistingKind =
6881 ExistingOBT->getBehaviorKind();
6882 if (ExistingKind != Kind) {
6883 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors) << 0;
6884 if (Kind == OverflowBehaviorType::OverflowBehaviorKind::Trap) {
6885 Type = State.getOverflowBehaviorType(Kind,
6886 ExistingOBT->getUnderlyingType());
6887 }
6888 return;
6889 }
6890 } else {
6891 Type = State.getOverflowBehaviorType(Kind, Type);
6892 }
6893}
6894
6895/// handleObjCOwnershipTypeAttr - Process an objc_ownership
6896/// attribute on the specified type.
6897///
6898/// Returns 'true' if the attribute was handled.
6899static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6901 bool NonObjCPointer = false;
6902
6903 if (!type->isDependentType() && !type->isUndeducedType()) {
6904 if (const PointerType *ptr = type->getAs<PointerType>()) {
6905 QualType pointee = ptr->getPointeeType();
6906 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6907 return false;
6908 // It is important not to lose the source info that there was an attribute
6909 // applied to non-objc pointer. We will create an attributed type but
6910 // its type will be the same as the original type.
6911 NonObjCPointer = true;
6912 } else if (!type->isObjCRetainableType()) {
6913 return false;
6914 }
6915
6916 // Don't accept an ownership attribute in the declspec if it would
6917 // just be the return type of a block pointer.
6918 if (state.isProcessingDeclSpec()) {
6919 Declarator &D = state.getDeclarator();
6921 /*onlyBlockPointers=*/true))
6922 return false;
6923 }
6924 }
6925
6926 Sema &S = state.getSema();
6927 SourceLocation AttrLoc = attr.getLoc();
6928 if (AttrLoc.isMacroID())
6929 AttrLoc =
6931
6932 if (!attr.isArgIdent(0)) {
6933 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6935 attr.setInvalid();
6936 return true;
6937 }
6938
6939 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
6940 Qualifiers::ObjCLifetime lifetime;
6941 if (II->isStr("none"))
6943 else if (II->isStr("strong"))
6944 lifetime = Qualifiers::OCL_Strong;
6945 else if (II->isStr("weak"))
6946 lifetime = Qualifiers::OCL_Weak;
6947 else if (II->isStr("autoreleasing"))
6949 else {
6950 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6951 attr.setInvalid();
6952 return true;
6953 }
6954
6955 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6956 // outside of ARC mode.
6957 if (!S.getLangOpts().ObjCAutoRefCount &&
6958 lifetime != Qualifiers::OCL_Weak &&
6959 lifetime != Qualifiers::OCL_ExplicitNone) {
6960 return true;
6961 }
6962
6963 SplitQualType underlyingType = type.split();
6964
6965 // Check for redundant/conflicting ownership qualifiers.
6966 if (Qualifiers::ObjCLifetime previousLifetime
6967 = type.getQualifiers().getObjCLifetime()) {
6968 // If it's written directly, that's an error.
6970 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6971 << type;
6972 return true;
6973 }
6974
6975 // Otherwise, if the qualifiers actually conflict, pull sugar off
6976 // and remove the ObjCLifetime qualifiers.
6977 if (previousLifetime != lifetime) {
6978 // It's possible to have multiple local ObjCLifetime qualifiers. We
6979 // can't stop after we reach a type that is directly qualified.
6980 const Type *prevTy = nullptr;
6981 while (!prevTy || prevTy != underlyingType.Ty) {
6982 prevTy = underlyingType.Ty;
6983 underlyingType = underlyingType.getSingleStepDesugaredType();
6984 }
6985 underlyingType.Quals.removeObjCLifetime();
6986 }
6987 }
6988
6989 underlyingType.Quals.addObjCLifetime(lifetime);
6990
6991 if (NonObjCPointer) {
6992 StringRef name = attr.getAttrName()->getName();
6993 switch (lifetime) {
6996 break;
6997 case Qualifiers::OCL_Strong: name = "__strong"; break;
6998 case Qualifiers::OCL_Weak: name = "__weak"; break;
6999 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
7000 }
7001 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
7003 }
7004
7005 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
7006 // because having both 'T' and '__unsafe_unretained T' exist in the type
7007 // system causes unfortunate widespread consistency problems. (For example,
7008 // they're not considered compatible types, and we mangle them identicially
7009 // as template arguments.) These problems are all individually fixable,
7010 // but it's easier to just not add the qualifier and instead sniff it out
7011 // in specific places using isObjCInertUnsafeUnretainedType().
7012 //
7013 // Doing this does means we miss some trivial consistency checks that
7014 // would've triggered in ARC, but that's better than trying to solve all
7015 // the coexistence problems with __unsafe_unretained.
7016 if (!S.getLangOpts().ObjCAutoRefCount &&
7017 lifetime == Qualifiers::OCL_ExplicitNone) {
7018 type = state.getAttributedType(
7020 type, type);
7021 return true;
7022 }
7023
7024 QualType origType = type;
7025 if (!NonObjCPointer)
7026 type = S.Context.getQualifiedType(underlyingType);
7027
7028 // If we have a valid source location for the attribute, use an
7029 // AttributedType instead.
7030 if (AttrLoc.isValid()) {
7031 type = state.getAttributedType(::new (S.Context)
7032 ObjCOwnershipAttr(S.Context, attr, II),
7033 origType, type);
7034 }
7035
7036 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
7037 unsigned diagnostic, QualType type) {
7042 diagnostic, type, /*ignored*/ 0));
7043 } else {
7044 S.Diag(loc, diagnostic);
7045 }
7046 };
7047
7048 // Sometimes, __weak isn't allowed.
7049 if (lifetime == Qualifiers::OCL_Weak &&
7050 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
7051
7052 // Use a specialized diagnostic if the runtime just doesn't support them.
7053 unsigned diagnostic =
7054 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
7055 : diag::err_arc_weak_no_runtime);
7056
7057 // In any case, delay the diagnostic until we know what we're parsing.
7058 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
7059
7060 attr.setInvalid();
7061 return true;
7062 }
7063
7064 // Forbid __weak for class objects marked as
7065 // objc_arc_weak_reference_unavailable
7066 if (lifetime == Qualifiers::OCL_Weak) {
7067 if (const ObjCObjectPointerType *ObjT =
7068 type->getAs<ObjCObjectPointerType>()) {
7069 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
7070 if (Class->isArcWeakrefUnavailable()) {
7071 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
7072 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
7073 diag::note_class_declared);
7074 }
7075 }
7076 }
7077 }
7078
7079 return true;
7080}
7081
7082/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
7083/// attribute on the specified type. Returns true to indicate that
7084/// the attribute was handled, false to indicate that the type does
7085/// not permit the attribute.
7086static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7087 QualType &type) {
7088 Sema &S = state.getSema();
7089
7090 // Delay if this isn't some kind of pointer.
7091 if (!type->isPointerType() &&
7092 !type->isObjCObjectPointerType() &&
7093 !type->isBlockPointerType())
7094 return false;
7095
7096 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7097 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
7098 attr.setInvalid();
7099 return true;
7100 }
7101
7102 // Check the attribute arguments.
7103 if (!attr.isArgIdent(0)) {
7104 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
7106 attr.setInvalid();
7107 return true;
7108 }
7109 Qualifiers::GC GCAttr;
7110 if (attr.getNumArgs() > 1) {
7111 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
7112 << 1;
7113 attr.setInvalid();
7114 return true;
7115 }
7116
7117 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
7118 if (II->isStr("weak"))
7119 GCAttr = Qualifiers::Weak;
7120 else if (II->isStr("strong"))
7121 GCAttr = Qualifiers::Strong;
7122 else {
7123 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
7124 << attr << II;
7125 attr.setInvalid();
7126 return true;
7127 }
7128
7129 QualType origType = type;
7130 type = S.Context.getObjCGCQualType(origType, GCAttr);
7131
7132 // Make an attributed type to preserve the source information.
7133 if (attr.getLoc().isValid())
7134 type = state.getAttributedType(
7135 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
7136
7137 return true;
7138}
7139
7140namespace {
7141 /// A helper class to unwrap a type down to a function for the
7142 /// purposes of applying attributes there.
7143 ///
7144 /// Use:
7145 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
7146 /// if (unwrapped.isFunctionType()) {
7147 /// const FunctionType *fn = unwrapped.get();
7148 /// // change fn somehow
7149 /// T = unwrapped.wrap(fn);
7150 /// }
7151 struct FunctionTypeUnwrapper {
7152 enum WrapKind {
7153 Desugar,
7154 Attributed,
7155 Parens,
7156 Array,
7157 Pointer,
7158 BlockPointer,
7159 Reference,
7160 MemberPointer,
7161 MacroQualified,
7162 };
7163
7164 QualType Original;
7165 const FunctionType *Fn;
7166 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7167
7168 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7169 while (true) {
7170 const Type *Ty = T.getTypePtr();
7171 if (isa<FunctionType>(Ty)) {
7172 Fn = cast<FunctionType>(Ty);
7173 return;
7174 } else if (isa<ParenType>(Ty)) {
7175 T = cast<ParenType>(Ty)->getInnerType();
7176 Stack.push_back(Parens);
7177 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
7179 T = cast<ArrayType>(Ty)->getElementType();
7180 Stack.push_back(Array);
7181 } else if (isa<PointerType>(Ty)) {
7182 T = cast<PointerType>(Ty)->getPointeeType();
7183 Stack.push_back(Pointer);
7184 } else if (isa<BlockPointerType>(Ty)) {
7185 T = cast<BlockPointerType>(Ty)->getPointeeType();
7186 Stack.push_back(BlockPointer);
7187 } else if (isa<MemberPointerType>(Ty)) {
7188 T = cast<MemberPointerType>(Ty)->getPointeeType();
7189 Stack.push_back(MemberPointer);
7190 } else if (isa<ReferenceType>(Ty)) {
7191 T = cast<ReferenceType>(Ty)->getPointeeType();
7192 Stack.push_back(Reference);
7193 } else if (isa<AttributedType>(Ty)) {
7194 T = cast<AttributedType>(Ty)->getEquivalentType();
7195 Stack.push_back(Attributed);
7196 } else if (isa<MacroQualifiedType>(Ty)) {
7197 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
7198 Stack.push_back(MacroQualified);
7199 } else {
7200 const Type *DTy = Ty->getUnqualifiedDesugaredType();
7201 if (Ty == DTy) {
7202 Fn = nullptr;
7203 return;
7204 }
7205
7206 T = QualType(DTy, 0);
7207 Stack.push_back(Desugar);
7208 }
7209 }
7210 }
7211
7212 bool isFunctionType() const { return (Fn != nullptr); }
7213 const FunctionType *get() const { return Fn; }
7214
7215 QualType wrap(Sema &S, const FunctionType *New) {
7216 // If T wasn't modified from the unwrapped type, do nothing.
7217 if (New == get()) return Original;
7218
7219 Fn = New;
7220 return wrap(S.Context, Original, 0);
7221 }
7222
7223 private:
7224 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7225 if (I == Stack.size())
7226 return C.getQualifiedType(Fn, Old.getQualifiers());
7227
7228 // Build up the inner type, applying the qualifiers from the old
7229 // type to the new type.
7230 SplitQualType SplitOld = Old.split();
7231
7232 // As a special case, tail-recurse if there are no qualifiers.
7233 if (SplitOld.Quals.empty())
7234 return wrap(C, SplitOld.Ty, I);
7235 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
7236 }
7237
7238 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7239 if (I == Stack.size()) return QualType(Fn, 0);
7240
7241 switch (static_cast<WrapKind>(Stack[I++])) {
7242 case Desugar:
7243 // This is the point at which we potentially lose source
7244 // information.
7245 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
7246
7247 case Attributed:
7248 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7249
7250 case Parens: {
7251 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7252 return C.getParenType(New);
7253 }
7254
7255 case MacroQualified:
7256 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7257
7258 case Array: {
7259 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7260 QualType New = wrap(C, CAT->getElementType(), I);
7261 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7262 CAT->getSizeModifier(),
7263 CAT->getIndexTypeCVRQualifiers());
7264 }
7265
7266 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7267 QualType New = wrap(C, VAT->getElementType(), I);
7268 return C.getVariableArrayType(New, VAT->getSizeExpr(),
7269 VAT->getSizeModifier(),
7270 VAT->getIndexTypeCVRQualifiers());
7271 }
7272
7273 const auto *IAT = cast<IncompleteArrayType>(Old);
7274 QualType New = wrap(C, IAT->getElementType(), I);
7275 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7276 IAT->getIndexTypeCVRQualifiers());
7277 }
7278
7279 case Pointer: {
7280 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7281 return C.getPointerType(New);
7282 }
7283
7284 case BlockPointer: {
7285 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7286 return C.getBlockPointerType(New);
7287 }
7288
7289 case MemberPointer: {
7290 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7291 QualType New = wrap(C, OldMPT->getPointeeType(), I);
7292 return C.getMemberPointerType(New, OldMPT->getQualifier(),
7293 OldMPT->getMostRecentCXXRecordDecl());
7294 }
7295
7296 case Reference: {
7297 const ReferenceType *OldRef = cast<ReferenceType>(Old);
7298 QualType New = wrap(C, OldRef->getPointeeType(), I);
7299 if (isa<LValueReferenceType>(OldRef))
7300 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7301 else
7302 return C.getRValueReferenceType(New);
7303 }
7304 }
7305
7306 llvm_unreachable("unknown wrapping kind");
7307 }
7308 };
7309} // end anonymous namespace
7310
7311static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7312 ParsedAttr &PAttr, QualType &Type) {
7313 Sema &S = State.getSema();
7314
7315 Attr *A;
7316 switch (PAttr.getKind()) {
7317 default: llvm_unreachable("Unknown attribute kind");
7318 case ParsedAttr::AT_Ptr32:
7320 break;
7321 case ParsedAttr::AT_Ptr64:
7323 break;
7324 case ParsedAttr::AT_SPtr:
7325 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7326 break;
7327 case ParsedAttr::AT_UPtr:
7328 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7329 break;
7330 }
7331
7332 std::bitset<attr::LastAttr> Attrs;
7333 QualType Desugared = Type;
7334 for (;;) {
7335 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7336 Desugared = TT->desugar();
7337 continue;
7338 }
7339 const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7340 if (!AT)
7341 break;
7342 Attrs[AT->getAttrKind()] = true;
7343 Desugared = AT->getModifiedType();
7344 }
7345
7346 // You cannot specify duplicate type attributes, so if the attribute has
7347 // already been applied, flag it.
7348 attr::Kind NewAttrKind = A->getKind();
7349 if (Attrs[NewAttrKind]) {
7350 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7351 return true;
7352 }
7353 Attrs[NewAttrKind] = true;
7354
7355 // You cannot have both __sptr and __uptr on the same type, nor can you
7356 // have __ptr32 and __ptr64.
7357 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7358 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7359 << "'__ptr32'"
7360 << "'__ptr64'" << /*isRegularKeyword=*/0;
7361 return true;
7362 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7363 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7364 << "'__sptr'"
7365 << "'__uptr'" << /*isRegularKeyword=*/0;
7366 return true;
7367 }
7368
7369 // Check the raw (i.e., desugared) Canonical type to see if it
7370 // is a pointer type.
7371 if (!isa<PointerType>(Desugared)) {
7372 // Pointer type qualifiers can only operate on pointer types, but not
7373 // pointer-to-member types.
7375 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7376 else
7377 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7378 return true;
7379 }
7380
7381 // Add address space to type based on its attributes.
7382 LangAS ASIdx = LangAS::Default;
7383 uint64_t PtrWidth =
7385 if (PtrWidth == 32) {
7386 if (Attrs[attr::Ptr64])
7387 ASIdx = LangAS::ptr64;
7388 else if (Attrs[attr::UPtr])
7389 ASIdx = LangAS::ptr32_uptr;
7390 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7391 if (S.Context.getTargetInfo().getTriple().isOSzOS() || Attrs[attr::UPtr])
7392 ASIdx = LangAS::ptr32_uptr;
7393 else
7394 ASIdx = LangAS::ptr32_sptr;
7395 }
7396
7397 QualType Pointee = Type->getPointeeType();
7398 if (ASIdx != LangAS::Default)
7399 Pointee = S.Context.getAddrSpaceQualType(
7400 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7401
7403 S.Context.getPointerType(Pointee), Type.getQualifiers());
7404 Type = State.getAttributedType(A, Type, Equivalent);
7405 return false;
7406}
7407
7408static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7409 QualType &QT, ParsedAttr &PAttr) {
7410 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7411
7412 Sema &S = State.getSema();
7414
7415 std::bitset<attr::LastAttr> Attrs;
7416 attr::Kind NewAttrKind = A->getKind();
7417 const auto *AT = dyn_cast<AttributedType>(QT);
7418 while (AT) {
7419 Attrs[AT->getAttrKind()] = true;
7420 AT = dyn_cast<AttributedType>(AT->getModifiedType());
7421 }
7422
7423 // You cannot specify duplicate type attributes, so if the attribute has
7424 // already been applied, flag it.
7425 if (Attrs[NewAttrKind]) {
7426 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7427 return true;
7428 }
7429
7430 // Check that the type is a function pointer type.
7431 QualType Desugared = QT.getDesugaredType(S.Context);
7432 const auto *Ptr = dyn_cast<PointerType>(Desugared);
7433 if (!Ptr || !Ptr->getPointeeType()->isFunctionType()) {
7434 S.Diag(PAttr.getLoc(), diag::err_attribute_webassembly_funcref);
7435 return true;
7436 }
7437
7438 // Add address space to type based on its attributes.
7440 QualType Pointee = QT->getPointeeType();
7441 Pointee = S.Context.getAddrSpaceQualType(
7442 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7443
7445 S.Context.getPointerType(Pointee), QT.getQualifiers());
7446 QT = State.getAttributedType(A, QT, Equivalent);
7447 return false;
7448}
7449
7450static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL,
7451 QualType &QT, ParsedAttr &PAttr) {
7452 if (TAL == TAL_DeclName)
7453 return;
7454
7455 Sema &S = State.getSema();
7456 auto &D = State.getDeclarator();
7457
7458 // If the attribute appears in declaration specifiers
7459 // it should be handled as a declaration attribute,
7460 // unless it's associated with a type or a function
7461 // prototype (i.e. appears on a parameter or result type).
7462 if (State.isProcessingDeclSpec()) {
7463 if (!(D.isPrototypeContext() ||
7464 D.getContext() == DeclaratorContext::TypeName))
7465 return;
7466
7467 if (auto *chunk = D.getInnermostNonParenChunk()) {
7468 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7469 const_cast<DeclaratorChunk *>(chunk)->getAttrs());
7470 return;
7471 }
7472 }
7473
7474 StringRef Str;
7475 if (!S.checkStringLiteralArgumentAttr(PAttr, 0, Str)) {
7476 PAttr.setInvalid();
7477 return;
7478 }
7479
7480 // If the attribute as attached to a paren move it closer to
7481 // the declarator. This can happen in block declarations when
7482 // an attribute is placed before `^` i.e. `(__attribute__((...)) ^)`.
7483 //
7484 // Note that it's actually invalid to use GNU style attributes
7485 // in a block but such cases are currently handled gracefully
7486 // but the parser and behavior should be consistent between
7487 // cases when attribute appears before/after block's result
7488 // type and inside (^).
7489 if (TAL == TAL_DeclChunk) {
7490 auto chunkIdx = State.getCurrentChunkIndex();
7491 if (chunkIdx >= 1 &&
7492 D.getTypeObject(chunkIdx).Kind == DeclaratorChunk::Paren) {
7493 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7494 D.getTypeObject(chunkIdx - 1).getAttrs());
7495 return;
7496 }
7497 }
7498
7499 auto *A = ::new (S.Context) SwiftAttrAttr(S.Context, PAttr, Str);
7500 QT = State.getAttributedType(A, QT, QT);
7501 PAttr.setUsedAsTypeAttr();
7502}
7503
7504/// Rebuild an attributed type without the nullability attribute on it.
7506 QualType Type) {
7507 auto Attributed = dyn_cast<AttributedType>(Type.getTypePtr());
7508 if (!Attributed)
7509 return Type;
7510
7511 // Skip the nullability attribute; we're done.
7512 if (Attributed->getImmediateNullability())
7513 return Attributed->getModifiedType();
7514
7515 // Build the modified type.
7517 Ctx, Attributed->getModifiedType());
7518 assert(Modified.getTypePtr() != Attributed->getModifiedType().getTypePtr());
7519 return Ctx.getAttributedType(Attributed->getAttrKind(), Modified,
7520 Attributed->getEquivalentType(),
7521 Attributed->getAttr());
7522}
7523
7524/// Map a nullability attribute kind to a nullability kind.
7526 switch (kind) {
7527 case ParsedAttr::AT_TypeNonNull:
7529
7530 case ParsedAttr::AT_TypeNullable:
7532
7533 case ParsedAttr::AT_TypeNullableResult:
7535
7536 case ParsedAttr::AT_TypeNullUnspecified:
7538
7539 default:
7540 llvm_unreachable("not a nullability attribute kind");
7541 }
7542}
7543
7545 Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT,
7546 NullabilityKind Nullability, SourceLocation NullabilityLoc,
7547 bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting) {
7548 bool Implicit = (State == nullptr);
7549 if (!Implicit)
7550 recordNullabilitySeen(S, NullabilityLoc);
7551
7552 // Check for existing nullability attributes on the type.
7553 QualType Desugared = QT;
7554 while (auto *Attributed = dyn_cast<AttributedType>(Desugared.getTypePtr())) {
7555 // Check whether there is already a null
7556 if (auto ExistingNullability = Attributed->getImmediateNullability()) {
7557 // Duplicated nullability.
7558 if (Nullability == *ExistingNullability) {
7559 if (Implicit)
7560 break;
7561
7562 S.Diag(NullabilityLoc, diag::warn_nullability_duplicate)
7563 << DiagNullabilityKind(Nullability, IsContextSensitive)
7564 << FixItHint::CreateRemoval(NullabilityLoc);
7565
7566 break;
7567 }
7568
7569 if (!OverrideExisting) {
7570 // Conflicting nullability.
7571 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7572 << DiagNullabilityKind(Nullability, IsContextSensitive)
7573 << DiagNullabilityKind(*ExistingNullability, false);
7574 return true;
7575 }
7576
7577 // Rebuild the attributed type, dropping the existing nullability.
7579 }
7580
7581 Desugared = Attributed->getModifiedType();
7582 }
7583
7584 // If there is already a different nullability specifier, complain.
7585 // This (unlike the code above) looks through typedefs that might
7586 // have nullability specifiers on them, which means we cannot
7587 // provide a useful Fix-It.
7588 if (auto ExistingNullability = Desugared->getNullability()) {
7589 if (Nullability != *ExistingNullability && !Implicit) {
7590 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7591 << DiagNullabilityKind(Nullability, IsContextSensitive)
7592 << DiagNullabilityKind(*ExistingNullability, false);
7593
7594 // Try to find the typedef with the existing nullability specifier.
7595 if (auto TT = Desugared->getAs<TypedefType>()) {
7596 TypedefNameDecl *typedefDecl = TT->getDecl();
7597 QualType underlyingType = typedefDecl->getUnderlyingType();
7598 if (auto typedefNullability =
7599 AttributedType::stripOuterNullability(underlyingType)) {
7600 if (*typedefNullability == *ExistingNullability) {
7601 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7602 << DiagNullabilityKind(*ExistingNullability, false);
7603 }
7604 }
7605 }
7606
7607 return true;
7608 }
7609 }
7610
7611 // If this definitely isn't a pointer type, reject the specifier.
7612 if (!Desugared->canHaveNullability() &&
7613 !(AllowOnArrayType && Desugared->isArrayType())) {
7614 if (!Implicit)
7615 S.Diag(NullabilityLoc, diag::err_nullability_nonpointer)
7616 << DiagNullabilityKind(Nullability, IsContextSensitive) << QT;
7617
7618 return true;
7619 }
7620
7621 // For the context-sensitive keywords/Objective-C property
7622 // attributes, require that the type be a single-level pointer.
7623 if (IsContextSensitive) {
7624 // Make sure that the pointee isn't itself a pointer type.
7625 const Type *pointeeType = nullptr;
7626 if (Desugared->isArrayType())
7628 else if (Desugared->isAnyPointerType())
7629 pointeeType = Desugared->getPointeeType().getTypePtr();
7630
7631 if (pointeeType && (pointeeType->isAnyPointerType() ||
7632 pointeeType->isObjCObjectPointerType() ||
7633 pointeeType->isMemberPointerType())) {
7634 S.Diag(NullabilityLoc, diag::err_nullability_cs_multilevel)
7635 << DiagNullabilityKind(Nullability, true) << QT;
7636 S.Diag(NullabilityLoc, diag::note_nullability_type_specifier)
7637 << DiagNullabilityKind(Nullability, false) << QT
7638 << FixItHint::CreateReplacement(NullabilityLoc,
7639 getNullabilitySpelling(Nullability));
7640 return true;
7641 }
7642 }
7643
7644 // Form the attributed type.
7645 if (State) {
7646 assert(PAttr);
7647 Attr *A = createNullabilityAttr(S.Context, *PAttr, Nullability);
7648 QT = State->getAttributedType(A, QT, QT);
7649 } else {
7650 QT = S.Context.getAttributedType(Nullability, QT, QT);
7651 }
7652 return false;
7653}
7654
7655static bool CheckNullabilityTypeSpecifier(TypeProcessingState &State,
7657 bool AllowOnArrayType) {
7659 SourceLocation NullabilityLoc = Attr.getLoc();
7660 bool IsContextSensitive = Attr.isContextSensitiveKeywordAttribute();
7661
7662 return CheckNullabilityTypeSpecifier(State.getSema(), &State, &Attr, Type,
7663 Nullability, NullabilityLoc,
7664 IsContextSensitive, AllowOnArrayType,
7665 /*overrideExisting*/ false);
7666}
7667
7669 NullabilityKind Nullability,
7670 SourceLocation DiagLoc,
7671 bool AllowArrayTypes,
7672 bool OverrideExisting) {
7674 *this, nullptr, nullptr, Type, Nullability, DiagLoc,
7675 /*isContextSensitive*/ false, AllowArrayTypes, OverrideExisting);
7676}
7677
7679 QualType T = VD->getType();
7680
7681 // Check that the variable's type can fit in the specified address space. This
7682 // is determined by how far a pointer in that address space can reach.
7683 llvm::APInt MaxSizeForAddrSpace =
7684 llvm::APInt::getMaxValue(Context.getTargetInfo().getPointerWidth(AS));
7685 std::optional<CharUnits> TSizeInChars = Context.getTypeSizeInCharsIfKnown(T);
7686 if (TSizeInChars && static_cast<uint64_t>(TSizeInChars->getQuantity()) >
7687 MaxSizeForAddrSpace.getZExtValue()) {
7688 Diag(VD->getLocation(), diag::err_type_too_large_for_address_space)
7689 << T << MaxSizeForAddrSpace;
7690 return false;
7691 }
7692
7693 return true;
7694}
7695
7696/// Check the application of the Objective-C '__kindof' qualifier to
7697/// the given type.
7698static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7699 ParsedAttr &attr) {
7700 Sema &S = state.getSema();
7701
7703 // Build the attributed type to record where __kindof occurred.
7704 type = state.getAttributedType(
7706 return false;
7707 }
7708
7709 // Find out if it's an Objective-C object or object pointer type;
7710 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7711 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7712 : type->getAs<ObjCObjectType>();
7713
7714 // If not, we can't apply __kindof.
7715 if (!objType) {
7716 // FIXME: Handle dependent types that aren't yet object types.
7717 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7718 << type;
7719 return true;
7720 }
7721
7722 // Rebuild the "equivalent" type, which pushes __kindof down into
7723 // the object type.
7724 // There is no need to apply kindof on an unqualified id type.
7725 QualType equivType = S.Context.getObjCObjectType(
7726 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7727 objType->getProtocols(),
7728 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7729
7730 // If we started with an object pointer type, rebuild it.
7731 if (ptrType) {
7732 equivType = S.Context.getObjCObjectPointerType(equivType);
7733 if (auto nullability = type->getNullability()) {
7734 // We create a nullability attribute from the __kindof attribute.
7735 // Make sure that will make sense.
7736 assert(attr.getAttributeSpellingListIndex() == 0 &&
7737 "multiple spellings for __kindof?");
7738 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7739 A->setImplicit(true);
7740 equivType = state.getAttributedType(A, equivType, equivType);
7741 }
7742 }
7743
7744 // Build the attributed type to record where __kindof occurred.
7745 type = state.getAttributedType(
7747 return false;
7748}
7749
7750/// Distribute a nullability type attribute that cannot be applied to
7751/// the type specifier to a pointer, block pointer, or member pointer
7752/// declarator, complaining if necessary.
7753///
7754/// \returns true if the nullability annotation was distributed, false
7755/// otherwise.
7756static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7758 Declarator &declarator = state.getDeclarator();
7759
7760 /// Attempt to move the attribute to the specified chunk.
7761 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7762 // If there is already a nullability attribute there, don't add
7763 // one.
7764 if (hasNullabilityAttr(chunk.getAttrs()))
7765 return false;
7766
7767 // Complain about the nullability qualifier being in the wrong
7768 // place.
7769 enum {
7770 PK_Pointer,
7771 PK_BlockPointer,
7772 PK_MemberPointer,
7773 PK_FunctionPointer,
7774 PK_MemberFunctionPointer,
7775 } pointerKind
7776 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7777 : PK_Pointer)
7778 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7779 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7780
7781 auto diag = state.getSema().Diag(attr.getLoc(),
7782 diag::warn_nullability_declspec)
7784 attr.isContextSensitiveKeywordAttribute())
7785 << type
7786 << static_cast<unsigned>(pointerKind);
7787
7788 // FIXME: MemberPointer chunks don't carry the location of the *.
7789 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7792 state.getSema().getPreprocessor().getLocForEndOfToken(
7793 chunk.Loc),
7794 " " + attr.getAttrName()->getName().str() + " ");
7795 }
7796
7797 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7798 chunk.getAttrs());
7799 return true;
7800 };
7801
7802 // Move it to the outermost pointer, member pointer, or block
7803 // pointer declarator.
7804 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7805 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7806 switch (chunk.Kind) {
7810 return moveToChunk(chunk, false);
7811
7814 continue;
7815
7817 // Try to move past the return type to a function/block/member
7818 // function pointer.
7820 declarator, i,
7821 /*onlyBlockPointers=*/false)) {
7822 return moveToChunk(*dest, true);
7823 }
7824
7825 return false;
7826
7827 // Don't walk through these.
7830 return false;
7831 }
7832 }
7833
7834 return false;
7835}
7836
7838 assert(!Attr.isInvalid());
7839 switch (Attr.getKind()) {
7840 default:
7841 llvm_unreachable("not a calling convention attribute");
7842 case ParsedAttr::AT_CDecl:
7843 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7844 case ParsedAttr::AT_FastCall:
7846 case ParsedAttr::AT_StdCall:
7848 case ParsedAttr::AT_ThisCall:
7850 case ParsedAttr::AT_RegCall:
7852 case ParsedAttr::AT_Pascal:
7854 case ParsedAttr::AT_SwiftCall:
7856 case ParsedAttr::AT_SwiftAsyncCall:
7858 case ParsedAttr::AT_VectorCall:
7860 case ParsedAttr::AT_AArch64VectorPcs:
7862 case ParsedAttr::AT_AArch64SVEPcs:
7864 case ParsedAttr::AT_ArmStreaming:
7866 case ParsedAttr::AT_Pcs: {
7867 // The attribute may have had a fixit applied where we treated an
7868 // identifier as a string literal. The contents of the string are valid,
7869 // but the form may not be.
7870 StringRef Str;
7871 if (Attr.isArgExpr(0))
7872 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7873 else
7874 Str = Attr.getArgAsIdent(0)->getIdentifierInfo()->getName();
7875 PcsAttr::PCSType Type;
7876 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7877 llvm_unreachable("already validated the attribute");
7878 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7879 }
7880 case ParsedAttr::AT_IntelOclBicc:
7882 case ParsedAttr::AT_MSABI:
7883 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7884 case ParsedAttr::AT_SysVABI:
7886 case ParsedAttr::AT_PreserveMost:
7888 case ParsedAttr::AT_PreserveAll:
7890 case ParsedAttr::AT_M68kRTD:
7892 case ParsedAttr::AT_PreserveNone:
7894 case ParsedAttr::AT_RISCVVectorCC:
7896 case ParsedAttr::AT_RISCVVLSCC: {
7897 // If the riscv_abi_vlen doesn't have any argument, we set set it to default
7898 // value 128.
7899 unsigned ABIVLen = 128;
7900 if (Attr.getNumArgs()) {
7901 std::optional<llvm::APSInt> MaybeABIVLen =
7902 Attr.getArgAsExpr(0)->getIntegerConstantExpr(Ctx);
7903 if (!MaybeABIVLen)
7904 llvm_unreachable("Invalid RISC-V ABI VLEN");
7905 ABIVLen = MaybeABIVLen->getZExtValue();
7906 }
7907
7908 return ::new (Ctx) RISCVVLSCCAttr(Ctx, Attr, ABIVLen);
7909 }
7910 }
7911 llvm_unreachable("unexpected attribute kind!");
7912}
7913
7914std::optional<FunctionEffectMode>
7915Sema::ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName) {
7916 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent())
7918
7919 std::optional<llvm::APSInt> ConditionValue =
7921 if (!ConditionValue) {
7922 // FIXME: err_attribute_argument_type doesn't quote the attribute
7923 // name but needs to; users are inconsistent.
7924 Diag(CondExpr->getExprLoc(), diag::err_attribute_argument_type)
7925 << AttributeName << AANT_ArgumentIntegerConstant
7926 << CondExpr->getSourceRange();
7927 return std::nullopt;
7928 }
7929 return !ConditionValue->isZero() ? FunctionEffectMode::True
7931}
7932
7933static bool
7934handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState,
7935 ParsedAttr &PAttr, QualType &QT,
7936 FunctionTypeUnwrapper &Unwrapped) {
7937 // Delay if this is not a function type.
7938 if (!Unwrapped.isFunctionType())
7939 return false;
7940
7941 Sema &S = TPState.getSema();
7942
7943 // Require FunctionProtoType.
7944 auto *FPT = Unwrapped.get()->getAs<FunctionProtoType>();
7945 if (FPT == nullptr) {
7946 S.Diag(PAttr.getLoc(), diag::err_func_with_effects_no_prototype)
7947 << PAttr.getAttrName()->getName();
7948 return true;
7949 }
7950
7951 // Parse the new attribute.
7952 // non/blocking or non/allocating? Or conditional (computed)?
7953 bool IsNonBlocking = PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7954 PAttr.getKind() == ParsedAttr::AT_Blocking;
7955
7957 Expr *CondExpr = nullptr; // only valid if dependent
7958
7959 if (PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7960 PAttr.getKind() == ParsedAttr::AT_NonAllocating) {
7961 if (!PAttr.checkAtMostNumArgs(S, 1)) {
7962 PAttr.setInvalid();
7963 return true;
7964 }
7965
7966 // Parse the condition, if any.
7967 if (PAttr.getNumArgs() == 1) {
7968 CondExpr = PAttr.getArgAsExpr(0);
7969 std::optional<FunctionEffectMode> MaybeMode =
7970 S.ActOnEffectExpression(CondExpr, PAttr.getAttrName()->getName());
7971 if (!MaybeMode) {
7972 PAttr.setInvalid();
7973 return true;
7974 }
7975 NewMode = *MaybeMode;
7976 if (NewMode != FunctionEffectMode::Dependent)
7977 CondExpr = nullptr;
7978 } else {
7979 NewMode = FunctionEffectMode::True;
7980 }
7981 } else {
7982 // This is the `blocking` or `allocating` attribute.
7983 if (S.CheckAttrNoArgs(PAttr)) {
7984 // The attribute has been marked invalid.
7985 return true;
7986 }
7987 NewMode = FunctionEffectMode::False;
7988 }
7989
7990 const FunctionEffect::Kind FEKind =
7991 (NewMode == FunctionEffectMode::False)
7992 ? (IsNonBlocking ? FunctionEffect::Kind::Blocking
7994 : (IsNonBlocking ? FunctionEffect::Kind::NonBlocking
7996 const FunctionEffectWithCondition NewEC{FunctionEffect(FEKind),
7997 EffectConditionExpr(CondExpr)};
7998
7999 if (S.diagnoseConflictingFunctionEffect(FPT->getFunctionEffects(), NewEC,
8000 PAttr.getLoc())) {
8001 PAttr.setInvalid();
8002 return true;
8003 }
8004
8005 // Add the effect to the FunctionProtoType.
8006 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8009 [[maybe_unused]] bool Success = FX.insert(NewEC, Errs);
8010 assert(Success && "effect conflicts should have been diagnosed above");
8012
8013 QualType NewType = S.Context.getFunctionType(FPT->getReturnType(),
8014 FPT->getParamTypes(), EPI);
8015 QT = Unwrapped.wrap(S, NewType->getAs<FunctionType>());
8016 return true;
8017}
8018
8019static bool checkMutualExclusion(TypeProcessingState &state,
8022 AttributeCommonInfo::Kind OtherKind) {
8023 auto OtherAttr = llvm::find_if(
8024 state.getCurrentAttributes(),
8025 [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
8026 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid())
8027 return false;
8028
8029 Sema &S = state.getSema();
8030 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
8031 << *OtherAttr << Attr
8032 << (OtherAttr->isRegularKeywordAttribute() ||
8034 S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute);
8035 Attr.setInvalid();
8036 return true;
8037}
8038
8041 ParsedAttr &Attr) {
8042 if (!Attr.getNumArgs()) {
8043 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
8044 Attr.setInvalid();
8045 return true;
8046 }
8047
8048 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
8049 StringRef StateName;
8050 SourceLocation LiteralLoc;
8051 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
8052 return true;
8053
8054 if (StateName != "sme_za_state") {
8055 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
8056 Attr.setInvalid();
8057 return true;
8058 }
8059
8060 if (EPI.AArch64SMEAttributes &
8062 S.Diag(Attr.getLoc(), diag::err_conflicting_attributes_arm_agnostic);
8063 Attr.setInvalid();
8064 return true;
8065 }
8066
8068 }
8069
8070 return false;
8071}
8072
8077 if (!Attr.getNumArgs()) {
8078 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
8079 Attr.setInvalid();
8080 return true;
8081 }
8082
8083 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
8084 StringRef StateName;
8085 SourceLocation LiteralLoc;
8086 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
8087 return true;
8088
8089 unsigned Shift;
8090 FunctionType::ArmStateValue ExistingState;
8091 if (StateName == "za") {
8094 } else if (StateName == "zt0") {
8097 } else {
8098 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
8099 Attr.setInvalid();
8100 return true;
8101 }
8102
8104 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_agnostic);
8105 Attr.setInvalid();
8106 return true;
8107 }
8108
8109 // __arm_in(S), __arm_out(S), __arm_inout(S) and __arm_preserves(S)
8110 // are all mutually exclusive for the same S, so check if there are
8111 // conflicting attributes.
8112 if (ExistingState != FunctionType::ARM_None && ExistingState != State) {
8113 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_state)
8114 << StateName;
8115 Attr.setInvalid();
8116 return true;
8117 }
8118
8120 (FunctionType::AArch64SMETypeAttributes)((State << Shift)));
8121 }
8122 return false;
8123}
8124
8125/// Process an individual function attribute. Returns true to
8126/// indicate that the attribute was handled, false if it wasn't.
8127static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
8129 Sema &S = state.getSema();
8130
8131 FunctionTypeUnwrapper unwrapped(S, type);
8132
8133 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
8134 if (S.CheckAttrNoArgs(attr))
8135 return true;
8136
8137 // Delay if this is not a function type.
8138 if (!unwrapped.isFunctionType())
8139 return false;
8140
8141 // Otherwise we can process right away.
8142 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
8143 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8144 return true;
8145 }
8146
8147 if (attr.getKind() == ParsedAttr::AT_CFIUncheckedCallee) {
8148 // Delay if this is not a prototyped function type.
8149 if (!unwrapped.isFunctionType())
8150 return false;
8151
8152 if (!unwrapped.get()->isFunctionProtoType()) {
8153 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
8154 << attr << attr.isRegularKeywordAttribute()
8156 attr.setInvalid();
8157 return true;
8158 }
8159
8160 const auto *FPT = unwrapped.get()->getAs<FunctionProtoType>();
8162 FPT->getReturnType(), FPT->getParamTypes(),
8163 FPT->getExtProtoInfo().withCFIUncheckedCallee(true));
8164 type = unwrapped.wrap(S, cast<FunctionType>(type.getTypePtr()));
8165 return true;
8166 }
8167
8168 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
8169 // Delay if this is not a function type.
8170 if (!unwrapped.isFunctionType())
8171 return false;
8172
8173 // Ignore if we don't have CMSE enabled.
8174 if (!S.getLangOpts().Cmse) {
8175 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
8176 attr.setInvalid();
8177 return true;
8178 }
8179
8180 // Otherwise we can process right away.
8182 unwrapped.get()->getExtInfo().withCmseNSCall(true);
8183 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8184 return true;
8185 }
8186
8187 // ns_returns_retained is not always a type attribute, but if we got
8188 // here, we're treating it as one right now.
8189 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
8190 if (attr.getNumArgs()) return true;
8191
8192 // Delay if this is not a function type.
8193 if (!unwrapped.isFunctionType())
8194 return false;
8195
8196 // Check whether the return type is reasonable.
8198 attr.getLoc(), unwrapped.get()->getReturnType()))
8199 return true;
8200
8201 // Only actually change the underlying type in ARC builds.
8202 QualType origType = type;
8203 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
8205 = unwrapped.get()->getExtInfo().withProducesResult(true);
8206 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8207 }
8208 type = state.getAttributedType(
8210 origType, type);
8211 return true;
8212 }
8213
8214 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
8216 return true;
8217
8218 // Delay if this is not a function type.
8219 if (!unwrapped.isFunctionType())
8220 return false;
8221
8223 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
8224 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8225 return true;
8226 }
8227
8228 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
8229 if (!S.getLangOpts().CFProtectionBranch) {
8230 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
8231 attr.setInvalid();
8232 return true;
8233 }
8234
8236 return true;
8237
8238 // If this is not a function type, warning will be asserted by subject
8239 // check.
8240 if (!unwrapped.isFunctionType())
8241 return true;
8242
8244 unwrapped.get()->getExtInfo().withNoCfCheck(true);
8245 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8246 return true;
8247 }
8248
8249 if (attr.getKind() == ParsedAttr::AT_Regparm) {
8250 unsigned value;
8251 if (S.CheckRegparmAttr(attr, value))
8252 return true;
8253
8254 // Delay if this is not a function type.
8255 if (!unwrapped.isFunctionType())
8256 return false;
8257
8258 // Diagnose regparm with fastcall.
8259 const FunctionType *fn = unwrapped.get();
8260 CallingConv CC = fn->getCallConv();
8261 if (CC == CC_X86FastCall) {
8262 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8263 << FunctionType::getNameForCallConv(CC) << "regparm"
8264 << attr.isRegularKeywordAttribute();
8265 attr.setInvalid();
8266 return true;
8267 }
8268
8270 unwrapped.get()->getExtInfo().withRegParm(value);
8271 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8272 return true;
8273 }
8274
8275 if (attr.getKind() == ParsedAttr::AT_CFISalt) {
8276 if (attr.getNumArgs() != 1)
8277 return true;
8278
8279 StringRef Argument;
8280 if (!S.checkStringLiteralArgumentAttr(attr, 0, Argument))
8281 return true;
8282
8283 // Delay if this is not a function type.
8284 if (!unwrapped.isFunctionType())
8285 return false;
8286
8287 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8288 if (!FnTy) {
8289 S.Diag(attr.getLoc(), diag::err_attribute_wrong_decl_type)
8290 << attr << attr.isRegularKeywordAttribute()
8292 attr.setInvalid();
8293 return true;
8294 }
8295
8296 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8297 EPI.ExtraAttributeInfo.CFISalt = Argument;
8298
8299 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8300 FnTy->getParamTypes(), EPI);
8301 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8302 return true;
8303 }
8304
8305 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8306 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible ||
8307 attr.getKind() == ParsedAttr::AT_ArmPreserves ||
8308 attr.getKind() == ParsedAttr::AT_ArmIn ||
8309 attr.getKind() == ParsedAttr::AT_ArmOut ||
8310 attr.getKind() == ParsedAttr::AT_ArmInOut ||
8311 attr.getKind() == ParsedAttr::AT_ArmAgnostic) {
8312 if (S.CheckAttrTarget(attr))
8313 return true;
8314
8315 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8316 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible)
8317 if (S.CheckAttrNoArgs(attr))
8318 return true;
8319
8320 if (!unwrapped.isFunctionType())
8321 return false;
8322
8323 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8324 if (!FnTy) {
8325 // SME ACLE attributes are not supported on K&R-style unprototyped C
8326 // functions.
8327 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
8328 << attr << attr.isRegularKeywordAttribute()
8330 attr.setInvalid();
8331 return false;
8332 }
8333
8334 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8335 switch (attr.getKind()) {
8336 case ParsedAttr::AT_ArmStreaming:
8337 if (checkMutualExclusion(state, EPI, attr,
8338 ParsedAttr::AT_ArmStreamingCompatible))
8339 return true;
8341 break;
8342 case ParsedAttr::AT_ArmStreamingCompatible:
8343 if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming))
8344 return true;
8346 break;
8347 case ParsedAttr::AT_ArmPreserves:
8349 return true;
8350 break;
8351 case ParsedAttr::AT_ArmIn:
8353 return true;
8354 break;
8355 case ParsedAttr::AT_ArmOut:
8357 return true;
8358 break;
8359 case ParsedAttr::AT_ArmInOut:
8361 return true;
8362 break;
8363 case ParsedAttr::AT_ArmAgnostic:
8364 if (handleArmAgnosticAttribute(S, EPI, attr))
8365 return true;
8366 break;
8367 default:
8368 llvm_unreachable("Unsupported attribute");
8369 }
8370
8371 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8372 FnTy->getParamTypes(), EPI);
8373 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8374 return true;
8375 }
8376
8377 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
8378 // Delay if this is not a function type.
8379 if (!unwrapped.isFunctionType())
8380 return false;
8381
8382 if (S.CheckAttrNoArgs(attr)) {
8383 attr.setInvalid();
8384 return true;
8385 }
8386
8387 // Otherwise we can process right away.
8388 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
8389
8390 // MSVC ignores nothrow if it is in conflict with an explicit exception
8391 // specification.
8392 if (Proto->hasExceptionSpec()) {
8393 switch (Proto->getExceptionSpecType()) {
8394 case EST_None:
8395 llvm_unreachable("This doesn't have an exception spec!");
8396
8397 case EST_DynamicNone:
8398 case EST_BasicNoexcept:
8399 case EST_NoexceptTrue:
8400 case EST_NoThrow:
8401 // Exception spec doesn't conflict with nothrow, so don't warn.
8402 [[fallthrough]];
8403 case EST_Unparsed:
8404 case EST_Uninstantiated:
8406 case EST_Unevaluated:
8407 // We don't have enough information to properly determine if there is a
8408 // conflict, so suppress the warning.
8409 break;
8410 case EST_Dynamic:
8411 case EST_MSAny:
8412 case EST_NoexceptFalse:
8413 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
8414 break;
8415 }
8416 return true;
8417 }
8418
8419 type = unwrapped.wrap(
8420 S, S.Context
8422 QualType{Proto, 0},
8424 ->getAs<FunctionType>());
8425 return true;
8426 }
8427
8428 if (attr.getKind() == ParsedAttr::AT_NonBlocking ||
8429 attr.getKind() == ParsedAttr::AT_NonAllocating ||
8430 attr.getKind() == ParsedAttr::AT_Blocking ||
8431 attr.getKind() == ParsedAttr::AT_Allocating) {
8432 return handleNonBlockingNonAllocatingTypeAttr(state, attr, type, unwrapped);
8433 }
8434
8435 // Delay if the type didn't work out to a function.
8436 if (!unwrapped.isFunctionType()) return false;
8437
8438 // Otherwise, a calling convention.
8439 CallingConv CC;
8440 if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/nullptr, CFT))
8441 return true;
8442
8443 const FunctionType *fn = unwrapped.get();
8444 CallingConv CCOld = fn->getCallConv();
8445 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
8446
8447 if (CCOld != CC) {
8448 // Error out on when there's already an attribute on the type
8449 // and the CCs don't match.
8451 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8454 << attr.isRegularKeywordAttribute();
8455 attr.setInvalid();
8456 return true;
8457 }
8458 }
8459
8460 // Diagnose use of variadic functions with calling conventions that
8461 // don't support them (e.g. because they're callee-cleanup).
8462 // We delay warning about this on unprototyped function declarations
8463 // until after redeclaration checking, just in case we pick up a
8464 // prototype that way. And apparently we also "delay" warning about
8465 // unprototyped function types in general, despite not necessarily having
8466 // much ability to diagnose it later.
8467 if (!supportsVariadicCall(CC)) {
8468 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
8469 if (FnP && FnP->isVariadic()) {
8470 // stdcall and fastcall are ignored with a warning for GCC and MS
8471 // compatibility.
8472 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
8473 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
8476
8477 attr.setInvalid();
8478 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
8480 }
8481 }
8482
8483 // Also diagnose fastcall with regparm.
8484 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
8485 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8487 << attr.isRegularKeywordAttribute();
8488 attr.setInvalid();
8489 return true;
8490 }
8491
8492 // Modify the CC from the wrapped function type, wrap it all back, and then
8493 // wrap the whole thing in an AttributedType as written. The modified type
8494 // might have a different CC if we ignored the attribute.
8496 if (CCOld == CC) {
8497 Equivalent = type;
8498 } else {
8499 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
8500 Equivalent =
8501 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8502 }
8503 type = state.getAttributedType(CCAttr, type, Equivalent);
8504 return true;
8505}
8506
8508 const AttributedType *AT;
8509
8510 // Stop if we'd be stripping off a typedef sugar node to reach the
8511 // AttributedType.
8512 while ((AT = T->getAs<AttributedType>()) &&
8513 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
8514 if (AT->isCallingConv())
8515 return true;
8516 T = AT->getModifiedType();
8517 }
8518 return false;
8519}
8520
8521void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
8522 bool IsCtorOrDtor, SourceLocation Loc) {
8523 FunctionTypeUnwrapper Unwrapped(*this, T);
8524 const FunctionType *FT = Unwrapped.get();
8525 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
8526 cast<FunctionProtoType>(FT)->isVariadic());
8527 CallingConv CurCC = FT->getCallConv();
8528 CallingConv ToCC =
8529 Context.getDefaultCallingConvention(IsVariadic, HasThisPointer);
8530
8531 if (CurCC == ToCC)
8532 return;
8533
8534 // MS compiler ignores explicit calling convention attributes on structors. We
8535 // should do the same.
8536 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
8537 // Issue a warning on ignored calling convention -- except of __stdcall.
8538 // Again, this is what MS compiler does.
8539 if (CurCC != CC_X86StdCall)
8540 Diag(Loc, diag::warn_cconv_unsupported)
8543 // Default adjustment.
8544 } else {
8545 // Only adjust types with the default convention. For example, on Windows
8546 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8547 // __thiscall type to __cdecl for static methods.
8548 CallingConv DefaultCC =
8549 Context.getDefaultCallingConvention(IsVariadic, !HasThisPointer);
8550
8551 if (CurCC != DefaultCC)
8552 return;
8553
8555 return;
8556 }
8557
8558 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
8559 QualType Wrapped = Unwrapped.wrap(*this, FT);
8560 T = Context.getAdjustedType(T, Wrapped);
8561}
8562
8563/// HandleVectorSizeAttribute - this attribute is only applicable to integral
8564/// and float scalars, although arrays, pointers, and function return values are
8565/// allowed in conjunction with this construct. Aggregates with this attribute
8566/// are invalid, even if they are of the same size as a corresponding scalar.
8567/// The raw attribute should contain precisely 1 argument, the vector size for
8568/// the variable, measured in bytes. If curType and rawAttr are well formed,
8569/// this routine will return a new vector type.
8570static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8571 Sema &S) {
8572 // Check the attribute arguments.
8573 if (Attr.getNumArgs() != 1) {
8574 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8575 << 1;
8576 Attr.setInvalid();
8577 return;
8578 }
8579
8580 Expr *SizeExpr = Attr.getArgAsExpr(0);
8581 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
8582 if (!T.isNull())
8583 CurType = T;
8584 else
8585 Attr.setInvalid();
8586}
8587
8588/// Process the OpenCL-like ext_vector_type attribute when it occurs on
8589/// a type.
8591 Sema &S) {
8592 Expr *SizeExpr = Attr.getArgAsExpr(0);
8593 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
8594 if (!T.isNull())
8595 CurType = T;
8596}
8597
8598static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) {
8599 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8600 if (!BTy)
8601 return false;
8602
8603 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8604
8605 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8606 // now.
8607 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8608 Triple.getArch() == llvm::Triple::aarch64_32 ||
8609 Triple.getArch() == llvm::Triple::aarch64_be;
8610 if (VecKind == VectorKind::NeonPoly) {
8611 if (IsPolyUnsigned) {
8612 // AArch64 polynomial vectors are unsigned.
8613 return BTy->getKind() == BuiltinType::UChar ||
8614 BTy->getKind() == BuiltinType::UShort ||
8615 BTy->getKind() == BuiltinType::ULong ||
8616 BTy->getKind() == BuiltinType::ULongLong;
8617 } else {
8618 // AArch32 polynomial vectors are signed.
8619 return BTy->getKind() == BuiltinType::SChar ||
8620 BTy->getKind() == BuiltinType::Short ||
8621 BTy->getKind() == BuiltinType::LongLong;
8622 }
8623 }
8624
8625 // Non-polynomial vector types: the usual suspects are allowed, as well as
8626 // float64_t on AArch64.
8627 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8628 BTy->getKind() == BuiltinType::Double)
8629 return true;
8630
8631 return BTy->getKind() == BuiltinType::SChar ||
8632 BTy->getKind() == BuiltinType::UChar ||
8633 BTy->getKind() == BuiltinType::Short ||
8634 BTy->getKind() == BuiltinType::UShort ||
8635 BTy->getKind() == BuiltinType::Int ||
8636 BTy->getKind() == BuiltinType::UInt ||
8637 BTy->getKind() == BuiltinType::Long ||
8638 BTy->getKind() == BuiltinType::ULong ||
8639 BTy->getKind() == BuiltinType::LongLong ||
8640 BTy->getKind() == BuiltinType::ULongLong ||
8641 BTy->getKind() == BuiltinType::Float ||
8642 BTy->getKind() == BuiltinType::Half ||
8643 BTy->getKind() == BuiltinType::BFloat16 ||
8644 BTy->getKind() == BuiltinType::MFloat8;
8645}
8646
8648 llvm::APSInt &Result) {
8649 const auto *AttrExpr = Attr.getArgAsExpr(0);
8650 if (!AttrExpr->isTypeDependent()) {
8651 if (std::optional<llvm::APSInt> Res =
8652 AttrExpr->getIntegerConstantExpr(S.Context)) {
8653 Result = *Res;
8654 return true;
8655 }
8656 }
8657 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8658 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8659 Attr.setInvalid();
8660 return false;
8661}
8662
8663/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8664/// "neon_polyvector_type" attributes are used to create vector types that
8665/// are mangled according to ARM's ABI. Otherwise, these types are identical
8666/// to those created with the "vector_size" attribute. Unlike "vector_size"
8667/// the argument to these Neon attributes is the number of vector elements,
8668/// not the vector size in bytes. The vector width and element type must
8669/// match one of the standard Neon vector types.
8671 Sema &S, VectorKind VecKind) {
8672 bool IsTargetOffloading = S.getLangOpts().isTargetDevice();
8673
8674 // Target must have NEON (or MVE, whose vectors are similar enough
8675 // not to need a separate attribute)
8676 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8677 VecKind == VectorKind::Neon &&
8678 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8679 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8680 << Attr << "'mve'";
8681 Attr.setInvalid();
8682 return;
8683 }
8684 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8685 VecKind == VectorKind::NeonPoly &&
8686 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8687 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8688 << Attr << "'mve'";
8689 Attr.setInvalid();
8690 return;
8691 }
8692
8693 // The number of elements must be an ICE.
8694 llvm::APSInt numEltsInt(32);
8695 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8696 return;
8697
8698 // Only certain element types are supported for Neon vectors.
8699 if (!isPermittedNeonBaseType(CurType, VecKind, S) && !IsTargetOffloading) {
8700 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8701 Attr.setInvalid();
8702 return;
8703 }
8704
8705 // The total size of the vector must be 64 or 128 bits.
8706 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8707 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8708 unsigned vecSize = typeSize * numElts;
8709 if (vecSize != 64 && vecSize != 128) {
8710 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8711 Attr.setInvalid();
8712 return;
8713 }
8714
8715 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8716}
8717
8718/// Handle the __ptrauth qualifier.
8720 const ParsedAttr &Attr, Sema &S) {
8721
8722 assert((Attr.getNumArgs() > 0 && Attr.getNumArgs() <= 3) &&
8723 "__ptrauth qualifier takes between 1 and 3 arguments");
8724 Expr *KeyArg = Attr.getArgAsExpr(0);
8725 Expr *IsAddressDiscriminatedArg =
8726 Attr.getNumArgs() >= 2 ? Attr.getArgAsExpr(1) : nullptr;
8727 Expr *ExtraDiscriminatorArg =
8728 Attr.getNumArgs() >= 3 ? Attr.getArgAsExpr(2) : nullptr;
8729
8730 unsigned Key;
8731 if (S.checkConstantPointerAuthKey(KeyArg, Key)) {
8732 Attr.setInvalid();
8733 return;
8734 }
8735 assert(Key <= PointerAuthQualifier::MaxKey && "ptrauth key is out of range");
8736
8737 bool IsInvalid = false;
8738 unsigned IsAddressDiscriminated, ExtraDiscriminator;
8739 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(IsAddressDiscriminatedArg,
8741 IsAddressDiscriminated);
8742 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(
8743 ExtraDiscriminatorArg, PointerAuthDiscArgKind::Extra, ExtraDiscriminator);
8744
8745 if (IsInvalid) {
8746 Attr.setInvalid();
8747 return;
8748 }
8749
8750 if (!T->isSignableType(Ctx) && !T->isDependentType()) {
8751 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_invalid_target) << T;
8752 Attr.setInvalid();
8753 return;
8754 }
8755
8756 if (T.getPointerAuth()) {
8757 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_redundant) << T;
8758 Attr.setInvalid();
8759 return;
8760 }
8761
8762 if (!S.getLangOpts().PointerAuthIntrinsics) {
8763 S.Diag(Attr.getLoc(), diag::err_ptrauth_disabled) << Attr.getRange();
8764 Attr.setInvalid();
8765 return;
8766 }
8767
8768 assert((!IsAddressDiscriminatedArg || IsAddressDiscriminated <= 1) &&
8769 "address discriminator arg should be either 0 or 1");
8771 Key, IsAddressDiscriminated, ExtraDiscriminator,
8772 PointerAuthenticationMode::SignAndAuth, /*IsIsaPointer=*/false,
8773 /*AuthenticatesNullValues=*/false);
8774 T = S.Context.getPointerAuthType(T, Qual);
8775}
8776
8777/// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8778/// used to create fixed-length versions of sizeless SVE types defined by
8779/// the ACLE, such as svint32_t and svbool_t.
8781 Sema &S) {
8782 // Target must have SVE.
8783 if (!S.Context.getTargetInfo().hasFeature("sve")) {
8784 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8785 Attr.setInvalid();
8786 return;
8787 }
8788
8789 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8790 // if <bits>+ syntax is used.
8791 if (!S.getLangOpts().VScaleMin ||
8792 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8793 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8794 << Attr;
8795 Attr.setInvalid();
8796 return;
8797 }
8798
8799 // The vector size must be an integer constant expression.
8800 llvm::APSInt SveVectorSizeInBits(32);
8801 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8802 return;
8803
8804 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8805
8806 // The attribute vector size must match -msve-vector-bits.
8807 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8808 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8809 << VecSize << S.getLangOpts().VScaleMin * 128;
8810 Attr.setInvalid();
8811 return;
8812 }
8813
8814 // Attribute can only be attached to a single SVE vector or predicate type.
8815 if (!CurType->isSveVLSBuiltinType()) {
8816 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8817 << Attr << CurType;
8818 Attr.setInvalid();
8819 return;
8820 }
8821
8822 const auto *BT = CurType->castAs<BuiltinType>();
8823
8824 QualType EltType = CurType->getSveEltType(S.Context);
8825 unsigned TypeSize = S.Context.getTypeSize(EltType);
8827 if (BT->getKind() == BuiltinType::SveBool) {
8828 // Predicates are represented as i8.
8829 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8831 } else
8832 VecSize /= TypeSize;
8833 CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8834}
8835
8836static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8837 QualType &CurType,
8838 ParsedAttr &Attr) {
8839 const VectorType *VT = dyn_cast<VectorType>(CurType);
8840 if (!VT || VT->getVectorKind() != VectorKind::Neon) {
8841 State.getSema().Diag(Attr.getLoc(),
8842 diag::err_attribute_arm_mve_polymorphism);
8843 Attr.setInvalid();
8844 return;
8845 }
8846
8847 CurType =
8848 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8849 State.getSema().Context, Attr),
8850 CurType, CurType);
8851}
8852
8853/// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8854/// used to create fixed-length versions of sizeless RVV types such as
8855/// vint8m1_t_t.
8857 ParsedAttr &Attr, Sema &S) {
8858 // Target must have vector extension.
8859 if (!S.Context.getTargetInfo().hasFeature("zve32x")) {
8860 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8861 << Attr << "'zve32x'";
8862 Attr.setInvalid();
8863 return;
8864 }
8865
8866 auto VScale = S.Context.getTargetInfo().getVScaleRange(
8868 if (!VScale || !VScale->first || VScale->first != VScale->second) {
8869 S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported)
8870 << Attr;
8871 Attr.setInvalid();
8872 return;
8873 }
8874
8875 // The vector size must be an integer constant expression.
8876 llvm::APSInt RVVVectorSizeInBits(32);
8877 if (!verifyValidIntegerConstantExpr(S, Attr, RVVVectorSizeInBits))
8878 return;
8879
8880 // Attribute can only be attached to a single RVV vector type.
8881 if (!CurType->isRVVVLSBuiltinType()) {
8882 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type)
8883 << Attr << CurType;
8884 Attr.setInvalid();
8885 return;
8886 }
8887
8888 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8889
8892 unsigned MinElts = Info.EC.getKnownMinValue();
8893
8894 VectorKind VecKind;
8895 unsigned ExpectedSize = VScale->first * MinElts;
8896 QualType EltType = CurType->getRVVEltType(S.Context);
8897 unsigned EltSize = S.Context.getTypeSize(EltType);
8898 unsigned NumElts;
8899 if (Info.ElementType == S.Context.BoolTy) {
8900 // A mask is stored in bytes. One with fewer than 8 lanes takes a single
8901 // byte, and its lane count is recorded in the vector kind.
8902 NumElts = VecSize / S.Context.getCharWidth();
8903 unsigned SubByteLanes = 0;
8904 if (!NumElts) {
8905 NumElts = 1;
8906 if (VecSize == 1 || VecSize == 2 || VecSize == 4)
8907 SubByteLanes = VecSize;
8908 }
8909 // Record the ratio of the vbool<R>_t type in the vector kind, so that
8910 // later stages do not have to re-derive it from VLEN and the lane count.
8911 // vbool<R>_t has RVVBitsPerBlock / R lanes at vscale=1.
8913 llvm::Log2_32(llvm::RISCV::RVVBitsPerBlock / MinElts), SubByteLanes);
8914 } else {
8915 ExpectedSize *= EltSize;
8916 NumElts = VecSize / EltSize;
8917
8918 // Record the LMUL of the sizeless type in the vector kind, so that later
8919 // stages do not have to re-derive it from VLEN and the element count.
8920 // LMUL = MinElts * EltSize / RVVBitsPerBlock
8922 int(llvm::Log2_32(MinElts * EltSize)) -
8923 int(llvm::Log2_32(llvm::RISCV::RVVBitsPerBlock)));
8924 }
8925
8926 // The attribute vector size must match -mrvv-vector-bits.
8927 if (VecSize != ExpectedSize) {
8928 S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size)
8929 << VecSize << ExpectedSize;
8930 Attr.setInvalid();
8931 return;
8932 }
8933
8934 CurType = S.Context.getVectorType(EltType, NumElts, VecKind);
8935}
8936
8937/// Handle OpenCL Access Qualifier Attribute.
8938static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8939 Sema &S) {
8940 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8941 if (!(CurType->isImageType() || CurType->isPipeType())) {
8942 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8943 Attr.setInvalid();
8944 return;
8945 }
8946
8947 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8948 QualType BaseTy = TypedefTy->desugar();
8949
8950 std::string PrevAccessQual;
8951 if (BaseTy->isPipeType()) {
8952 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8953 OpenCLAccessAttr *Attr =
8954 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8955 PrevAccessQual = Attr->getSpelling();
8956 } else {
8957 PrevAccessQual = "read_only";
8958 }
8959 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8960
8961 switch (ImgType->getKind()) {
8962 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8963 case BuiltinType::Id: \
8964 PrevAccessQual = #Access; \
8965 break;
8966 #include "clang/Basic/OpenCLImageTypes.def"
8967 default:
8968 llvm_unreachable("Unable to find corresponding image type.");
8969 }
8970 } else {
8971 llvm_unreachable("unexpected type");
8972 }
8973 StringRef AttrName = Attr.getAttrName()->getName();
8974 if (PrevAccessQual == AttrName.ltrim("_")) {
8975 // Duplicated qualifiers
8976 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8977 << AttrName << Attr.getRange();
8978 } else {
8979 // Contradicting qualifiers
8980 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8981 }
8982
8983 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8984 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8985 } else if (CurType->isPipeType()) {
8986 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8987 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8988 CurType = S.Context.getWritePipeType(ElemType);
8989 }
8990 }
8991}
8992
8993/// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8994static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8995 Sema &S) {
8996 if (!S.getLangOpts().MatrixTypes) {
8997 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8998 return;
8999 }
9000
9001 Expr *RowsExpr = Attr.getArgAsExpr(0);
9002 Expr *ColsExpr = Attr.getArgAsExpr(1);
9003 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
9004 if (!T.isNull())
9005 CurType = T;
9006}
9007
9008static void HandleAnnotateTypeAttr(TypeProcessingState &State,
9009 QualType &CurType, const ParsedAttr &PA) {
9010 Sema &S = State.getSema();
9011
9012 if (PA.getNumArgs() < 1) {
9013 S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
9014 return;
9015 }
9016
9017 // Make sure that there is a string literal as the annotation's first
9018 // argument.
9019 StringRef Str;
9020 if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
9021 return;
9022
9024 Args.reserve(PA.getNumArgs() - 1);
9025 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
9026 assert(!PA.isArgIdent(Idx));
9027 Args.push_back(PA.getArgAsExpr(Idx));
9028 }
9029 if (!S.ConstantFoldAttrArgs(PA, Args))
9030 return;
9031 auto *AnnotateTypeAttr =
9032 AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
9033 CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
9034}
9035
9036static void HandleLifetimeBoundAttr(TypeProcessingState &State,
9037 QualType &CurType,
9038 ParsedAttr &Attr) {
9039 if (State.getDeclarator().isDeclarationOfFunction()) {
9040 CurType = State.getAttributedType(
9041 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
9042 CurType, CurType);
9043 return;
9044 }
9045 State.getSema().Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
9048}
9049
9050static void HandleLifetimeCaptureByAttr(TypeProcessingState &State,
9051 QualType &CurType, ParsedAttr &PA) {
9052 if (State.getDeclarator().isDeclarationOfFunction()) {
9053 auto *Attr = State.getSema().ParseLifetimeCaptureByAttr(PA, "this");
9054 if (Attr)
9055 CurType = State.getAttributedType(Attr, CurType, CurType);
9056 }
9057}
9058
9059static void HandleHLSLParamModifierAttr(TypeProcessingState &State,
9060 QualType &CurType,
9061 const ParsedAttr &Attr, Sema &S) {
9062 // Don't apply this attribute to template dependent types. It is applied on
9063 // substitution during template instantiation. Also skip parsing this if we've
9064 // already modified the type based on an earlier attribute.
9065 if (CurType->isDependentType() || State.didParseHLSLParamMod())
9066 return;
9067 if (Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout ||
9068 Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out) {
9069 State.setParsedHLSLParamMod(true);
9070 }
9071}
9072
9074 // A DeclSpec attribute runs this once per declarator, as in
9075 // `IP __counted_by(n) a, b;`. Reuse one node, as the eager path does, so no
9076 // node is left without a count.
9077 if (LA.TypeToComplete) {
9078 QT = QualType(LA.TypeToComplete, 0);
9079 return true;
9080 }
9081
9082 // Nesting is checked once the enclosing declarator chunks wrap the node.
9083 BoundsAttrFlags Flags;
9085 SourceRange(LA.NameLoc),
9086 /*PointerNestLevel=*/0, Flags))
9087 return false;
9088
9089 // The argument isn't parsed yet, so build the type without a count.
9091 QT, Flags.CountInBytes, Flags.OrNull);
9092 QT = QualType(CATy, 0);
9093 LA.TypeToComplete = CATy;
9094 return true;
9095}
9096
9097static void processTypeAttrs(TypeProcessingState &state, QualType &type,
9098 TypeAttrLocation TAL,
9099 const ParsedAttributesView &attrs,
9100 CUDAFunctionTarget CFT) {
9101
9102 state.setParsedNoDeref(false);
9103 if (attrs.empty())
9104 return;
9105
9106 // Scan through and apply attributes to this type where it makes sense. Some
9107 // attributes (such as __address_space__, __vector_size__, etc) apply to the
9108 // type, but others can be present in the type specifiers even though they
9109 // apply to the decl. Here we apply type attributes and ignore the rest.
9110
9111 // This loop modifies the list pretty frequently, but we still need to make
9112 // sure we visit every element once. Copy the attributes list, and iterate
9113 // over that.
9114 ParsedAttributesView AttrsCopy{attrs};
9115 for (ParsedAttr &attr : AttrsCopy) {
9116
9117 // Skip attributes that were marked to be invalid.
9118 if (attr.isInvalid())
9119 continue;
9120
9121 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) {
9122 // [[gnu::...]] attributes are treated as declaration attributes, so may
9123 // not appertain to a DeclaratorChunk. If we handle them as type
9124 // attributes, accept them in that position and diagnose the GCC
9125 // incompatibility.
9126 if (attr.isGNUScope()) {
9127 assert(attr.isStandardAttributeSyntax());
9128 bool IsTypeAttr = attr.isTypeAttr();
9129 if (TAL == TAL_DeclChunk) {
9130 state.getSema().Diag(attr.getLoc(),
9131 IsTypeAttr
9132 ? diag::warn_gcc_ignores_type_attr
9133 : diag::warn_cxx11_gnu_attribute_on_type)
9134 << attr;
9135 if (!IsTypeAttr)
9136 continue;
9137 }
9138 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
9139 !attr.isTypeAttr()) {
9140 // Otherwise, only consider type processing for a C++11 attribute if
9141 // - it has actually been applied to a type (decl-specifier-seq or
9142 // declarator chunk), or
9143 // - it is a type attribute, irrespective of where it was applied (so
9144 // that we can support the legacy behavior of some type attributes
9145 // that can be applied to the declaration name).
9146 continue;
9147 }
9148 }
9149
9150 if (attr.isTypeAttr() &&
9151 state.getSema().checkCommonAttributeFeatures(type, attr)) {
9152 attr.setInvalid();
9153 continue;
9154 }
9155
9156 // If this is an attribute we can handle, do so now,
9157 // otherwise, add it to the FnAttrs list for rechaining.
9158 switch (attr.getKind()) {
9159 default:
9160 // A [[]] attribute on a declarator chunk must appertain to a type.
9161 if ((attr.isStandardAttributeSyntax() ||
9162 attr.isRegularKeywordAttribute()) &&
9163 TAL == TAL_DeclChunk) {
9164 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
9165 << attr << attr.isRegularKeywordAttribute();
9166 attr.setUsedAsTypeAttr();
9167 }
9168 break;
9169
9171 if (attr.isStandardAttributeSyntax()) {
9172 state.getSema().DiagnoseUnknownAttribute(attr);
9173 // Mark the attribute as invalid so we don't emit the same diagnostic
9174 // multiple times.
9175 attr.setInvalid();
9176 }
9177 break;
9178
9180 break;
9181
9182 case ParsedAttr::AT_BTFTypeTag:
9184 attr.setUsedAsTypeAttr();
9185 break;
9186
9187 case ParsedAttr::AT_MayAlias:
9188 // FIXME: This attribute needs to actually be handled, but if we ignore
9189 // it it breaks large amounts of Linux software.
9190 attr.setUsedAsTypeAttr();
9191 break;
9192 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
9193 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
9194 state.getSema().Diag(attr.getLoc(), diag::warn_deprecated_attribute)
9195 << attr;
9196 [[fallthrough]];
9197 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
9198 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
9199 case ParsedAttr::AT_OpenCLLocalAddressSpace:
9200 case ParsedAttr::AT_OpenCLConstantAddressSpace:
9201 case ParsedAttr::AT_OpenCLGenericAddressSpace:
9202 case ParsedAttr::AT_AddressSpace:
9203 case ParsedAttr::AT_SYCLPrivateAddressSpace:
9204 case ParsedAttr::AT_SYCLGlobalAddressSpace:
9205 case ParsedAttr::AT_SYCLLocalAddressSpace:
9206 case ParsedAttr::AT_SYCLConstantAddressSpace:
9207 case ParsedAttr::AT_SYCLGenericAddressSpace:
9209 attr.setUsedAsTypeAttr();
9210 break;
9211 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
9213 if (state.getDeclarator().getContext() == DeclaratorContext::Prototype) {
9214 if (state.getSema().getLangOpts().getHLSLVersion() <
9216 state.getSema().Diag(attr.getLoc(), diag::warn_hlsl_groupshared_202x);
9217
9218 // Note: we don't check for the usage of HLSLParamModifiers in/out/inout
9219 // here because the check in the AT_HLSLParamModifier case is sufficient
9220 // regardless of the order of groupshared or in/out/inout specified in
9221 // the parameter. And checking there produces a better error message.
9222 }
9223 attr.setUsedAsTypeAttr();
9224 break;
9225 case ParsedAttr::AT_HLSLRowMajor:
9226 case ParsedAttr::AT_HLSLColumnMajor:
9227 if (Attr *A =
9228 state.getSema().HLSL().buildMatrixLayoutTypeAttr(type, attr)) {
9229 MatrixType::LayoutKind Layout =
9230 attr.getKind() == ParsedAttr::AT_HLSLRowMajor
9234 state.getSema().Context.getMatrixTypeWithLayout(type, Layout);
9235 type = state.getAttributedType(A, type, Equivalent);
9236 }
9237 attr.setUsedAsTypeAttr();
9238 break;
9240 if (!handleObjCPointerTypeAttr(state, attr, type))
9242 attr.setUsedAsTypeAttr();
9243 break;
9244 case ParsedAttr::AT_VectorSize:
9245 HandleVectorSizeAttr(type, attr, state.getSema());
9246 attr.setUsedAsTypeAttr();
9247 break;
9248 case ParsedAttr::AT_ExtVectorType:
9249 HandleExtVectorTypeAttr(type, attr, state.getSema());
9250 attr.setUsedAsTypeAttr();
9251 break;
9252 case ParsedAttr::AT_NeonVectorType:
9254 attr.setUsedAsTypeAttr();
9255 break;
9256 case ParsedAttr::AT_NeonPolyVectorType:
9257 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
9259 attr.setUsedAsTypeAttr();
9260 break;
9261 case ParsedAttr::AT_ArmSveVectorBits:
9262 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
9263 attr.setUsedAsTypeAttr();
9264 break;
9265 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
9267 attr.setUsedAsTypeAttr();
9268 break;
9269 }
9270 case ParsedAttr::AT_RISCVRVVVectorBits:
9271 HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema());
9272 attr.setUsedAsTypeAttr();
9273 break;
9274 case ParsedAttr::AT_OpenCLAccess:
9275 HandleOpenCLAccessAttr(type, attr, state.getSema());
9276 attr.setUsedAsTypeAttr();
9277 break;
9278 case ParsedAttr::AT_PointerAuth:
9279 HandlePtrAuthQualifier(state.getSema().Context, type, attr,
9280 state.getSema());
9281 attr.setUsedAsTypeAttr();
9282 break;
9283 case ParsedAttr::AT_LifetimeBound:
9284 if (TAL == TAL_DeclChunk)
9286 break;
9287 case ParsedAttr::AT_LifetimeCaptureBy:
9288 if (TAL == TAL_DeclChunk)
9290 break;
9291 case ParsedAttr::AT_OverflowBehavior:
9293 attr.setUsedAsTypeAttr();
9294 break;
9295
9296 case ParsedAttr::AT_NoDeref: {
9297 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
9298 // See https://github.com/llvm/llvm-project/issues/55790 for details.
9299 // For the time being, we simply emit a warning that the attribute is
9300 // ignored.
9301 if (attr.isStandardAttributeSyntax()) {
9302 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
9303 << attr;
9304 break;
9305 }
9306 ASTContext &Ctx = state.getSema().Context;
9307 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
9308 type, type);
9309 attr.setUsedAsTypeAttr();
9310 state.setParsedNoDeref(true);
9311 break;
9312 }
9313
9314 case ParsedAttr::AT_MatrixType:
9315 HandleMatrixTypeAttr(type, attr, state.getSema());
9316 attr.setUsedAsTypeAttr();
9317 break;
9318
9319 case ParsedAttr::AT_WebAssemblyFuncref: {
9321 attr.setUsedAsTypeAttr();
9322 break;
9323 }
9324
9325 case ParsedAttr::AT_HLSLParamModifier: {
9326 HandleHLSLParamModifierAttr(state, type, attr, state.getSema());
9327 if (attrs.hasAttribute(ParsedAttr::AT_HLSLGroupSharedAddressSpace)) {
9328 state.getSema().Diag(attr.getLoc(), diag::err_hlsl_attr_incompatible)
9329 << attr << "'groupshared'";
9330 attr.setInvalid();
9331 return;
9332 }
9333 attr.setUsedAsTypeAttr();
9334 break;
9335 }
9336
9337 case ParsedAttr::AT_SwiftAttr: {
9338 HandleSwiftAttr(state, TAL, type, attr);
9339 break;
9340 }
9341
9344 attr.setUsedAsTypeAttr();
9345 break;
9346
9347
9349 // Either add nullability here or try to distribute it. We
9350 // don't want to distribute the nullability specifier past any
9351 // dependent type, because that complicates the user model.
9352 if (type->canHaveNullability() || type->isDependentType() ||
9353 type->isArrayType() ||
9355 unsigned endIndex;
9356 if (TAL == TAL_DeclChunk)
9357 endIndex = state.getCurrentChunkIndex();
9358 else
9359 endIndex = state.getDeclarator().getNumTypeObjects();
9360 bool allowOnArrayType =
9361 state.getDeclarator().isPrototypeContext() &&
9362 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
9364 allowOnArrayType)) {
9365 attr.setInvalid();
9366 }
9367
9368 attr.setUsedAsTypeAttr();
9369 }
9370 break;
9371
9372 case ParsedAttr::AT_ObjCKindOf:
9373 // '__kindof' must be part of the decl-specifiers.
9374 switch (TAL) {
9375 case TAL_DeclSpec:
9376 break;
9377
9378 case TAL_DeclChunk:
9379 case TAL_DeclName:
9380 state.getSema().Diag(attr.getLoc(),
9381 diag::err_objc_kindof_wrong_position)
9382 << FixItHint::CreateRemoval(attr.getLoc())
9384 state.getDeclarator().getDeclSpec().getBeginLoc(),
9385 "__kindof ");
9386 break;
9387 }
9388
9389 // Apply it regardless.
9390 if (checkObjCKindOfType(state, type, attr))
9391 attr.setInvalid();
9392 break;
9393
9394 case ParsedAttr::AT_NoThrow:
9395 // Exception Specifications aren't generally supported in C mode throughout
9396 // clang, so revert to attribute-based handling for C.
9397 if (!state.getSema().getLangOpts().CPlusPlus)
9398 break;
9399 [[fallthrough]];
9401
9402 attr.setUsedAsTypeAttr();
9403
9404 // Attributes with standard syntax have strict rules for what they
9405 // appertain to and hence should not use the "distribution" logic below.
9406 if (attr.isStandardAttributeSyntax() ||
9407 attr.isRegularKeywordAttribute()) {
9408 if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
9409 diagnoseBadTypeAttribute(state.getSema(), attr, type);
9410 attr.setInvalid();
9411 }
9412 break;
9413 }
9414
9415 // Never process function type attributes as part of the
9416 // declaration-specifiers.
9417 if (TAL == TAL_DeclSpec)
9419
9420 // Otherwise, handle the possible delays.
9421 else if (!handleFunctionTypeAttr(state, attr, type, CFT))
9423 break;
9424 case ParsedAttr::AT_AcquireHandle: {
9425 if (!type->isFunctionType())
9426 return;
9427
9428 if (attr.getNumArgs() != 1) {
9429 state.getSema().Diag(attr.getLoc(),
9430 diag::err_attribute_wrong_number_arguments)
9431 << attr << 1;
9432 attr.setInvalid();
9433 return;
9434 }
9435
9436 StringRef HandleType;
9437 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
9438 return;
9439 type = state.getAttributedType(
9440 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
9441 type, type);
9442 attr.setUsedAsTypeAttr();
9443 break;
9444 }
9445 case ParsedAttr::AT_AnnotateType: {
9447 attr.setUsedAsTypeAttr();
9448 break;
9449 }
9450 case ParsedAttr::AT_HLSLResourceClass:
9451 case ParsedAttr::AT_HLSLResourceDimension:
9452 case ParsedAttr::AT_HLSLIsROV:
9453 case ParsedAttr::AT_HLSLRawBuffer:
9454 case ParsedAttr::AT_HLSLIsArray:
9455 case ParsedAttr::AT_HLSLIsMultiSampled:
9456 case ParsedAttr::AT_HLSLContainedType: {
9457 // Only collect HLSL resource type attributes that are in
9458 // decl-specifier-seq; do not collect attributes on declarations or those
9459 // that get to slide after declaration name.
9460 if (TAL == TAL_DeclSpec &&
9461 state.getSema().HLSL().handleResourceTypeAttr(type, attr))
9462 attr.setUsedAsTypeAttr();
9463 break;
9464 }
9465 }
9466
9467 // Handle attributes that are defined in a macro. We do not want this to be
9468 // applied to ObjC builtin attributes.
9469 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
9470 !type.getQualifiers().hasObjCLifetime() &&
9471 !type.getQualifiers().hasObjCGCAttr() &&
9472 attr.getKind() != ParsedAttr::AT_ObjCGC &&
9473 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
9474 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
9475 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
9476 state.setExpansionLocForMacroQualifiedType(
9477 cast<MacroQualifiedType>(type.getTypePtr()),
9478 attr.getMacroExpansionLoc());
9479 }
9480 }
9481}
9482
9484 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
9485 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9486 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
9487 auto *Def = Var->getDefinition();
9488 if (!Def) {
9489 SourceLocation PointOfInstantiation = E->getExprLoc();
9490 runWithSufficientStackSpace(PointOfInstantiation, [&] {
9491 InstantiateVariableDefinition(PointOfInstantiation, Var);
9492 });
9493 Def = Var->getDefinition();
9494
9495 // If we don't already have a point of instantiation, and we managed
9496 // to instantiate a definition, this is the point of instantiation.
9497 // Otherwise, we don't request an end-of-TU instantiation, so this is
9498 // not a point of instantiation.
9499 // FIXME: Is this really the right behavior?
9500 if (Var->getPointOfInstantiation().isInvalid() && Def) {
9501 assert(Var->getTemplateSpecializationKind() ==
9503 "explicit instantiation with no point of instantiation");
9504 Var->setTemplateSpecializationKind(
9505 Var->getTemplateSpecializationKind(), PointOfInstantiation);
9506 }
9507 }
9508
9509 // Update the type to the definition's type both here and within the
9510 // expression.
9511 if (Def) {
9512 DRE->setDecl(Def);
9513 QualType T = Def->getType();
9514 DRE->setType(T);
9515 // FIXME: Update the type on all intervening expressions.
9516 E->setType(T);
9517 }
9518
9519 // We still go on to try to complete the type independently, as it
9520 // may also require instantiations or diagnostics if it remains
9521 // incomplete.
9522 }
9523 }
9524 }
9525 if (const auto CastE = dyn_cast<ExplicitCastExpr>(E)) {
9526 QualType DestType = CastE->getTypeAsWritten();
9527 if (const auto *IAT = Context.getAsIncompleteArrayType(DestType)) {
9528 // C++20 [expr.static.cast]p.4: ... If T is array of unknown bound,
9529 // this direct-initialization defines the type of the expression
9530 // as U[1]
9531 QualType ResultType = Context.getConstantArrayType(
9532 IAT->getElementType(),
9533 llvm::APInt(Context.getTypeSize(Context.getSizeType()), 1),
9534 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal,
9535 /*IndexTypeQuals=*/0);
9536 E->setType(ResultType);
9537 }
9538 }
9539}
9540
9542 // Incomplete array types may be completed by the initializer attached to
9543 // their definitions. For static data members of class templates and for
9544 // variable templates, we need to instantiate the definition to get this
9545 // initializer and complete the type.
9546 if (E->getType()->isIncompleteArrayType())
9548
9549 // FIXME: Are there other cases which require instantiating something other
9550 // than the type to complete the type of an expression?
9551
9552 return E->getType();
9553}
9554
9556 TypeDiagnoser &Diagnoser) {
9557 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
9558 Diagnoser);
9559}
9560
9561bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9562 BoundTypeDiagnoser<> Diagnoser(DiagID);
9564}
9565
9567 CompleteTypeKind Kind,
9568 TypeDiagnoser &Diagnoser) {
9569 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
9570 return true;
9571 if (auto *TD = T->getAsTagDecl(); TD && !TD->isCompleteDefinitionRequired()) {
9572 TD->setCompleteDefinitionRequired();
9573 Consumer.HandleTagDeclRequiredDefinition(TD);
9574 }
9575 return false;
9576}
9577
9580 if (!Suggested)
9581 return false;
9582
9583 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9584 // and isolate from other C++ specific checks.
9586 getLangOpts(), D->getASTContext(), Suggested->getASTContext(),
9587 NonEquivalentDecls, StructuralEquivalenceKind::Default,
9588 /*StrictTypeSpelling=*/false, /*Complain=*/true,
9589 /*ErrorOnTagTypeMismatch=*/true);
9590 return Ctx.IsEquivalent(D, Suggested);
9591}
9592
9594 AcceptableKind Kind, bool OnlyNeedComplete) {
9595 // Easy case: if we don't have modules, all declarations are visible.
9596 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9597 return true;
9598
9599 // If this definition was instantiated from a template, map back to the
9600 // pattern from which it was instantiated.
9601 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined())
9602 // We're in the middle of defining it; this definition should be treated
9603 // as visible.
9604 return true;
9605
9606 auto DefinitionIsAcceptable = [&](NamedDecl *D) {
9607 // The (primary) definition might be in a visible module.
9608 if (isAcceptable(D, Kind))
9609 return true;
9610
9611 // A visible module might have a merged definition instead.
9614 if (CodeSynthesisContexts.empty() &&
9615 !getLangOpts().ModulesLocalVisibility) {
9616 // Cache the fact that this definition is implicitly visible because
9617 // there is a visible merged definition.
9619 }
9620 return true;
9621 }
9622
9623 return false;
9624 };
9625 auto IsDefinition = [](NamedDecl *D) {
9626 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
9627 return RD->isThisDeclarationADefinition();
9628 if (auto *ED = dyn_cast<EnumDecl>(D))
9629 return ED->isThisDeclarationADefinition();
9630 if (auto *FD = dyn_cast<FunctionDecl>(D))
9631 return FD->isThisDeclarationADefinition();
9632 if (auto *VD = dyn_cast<VarDecl>(D))
9633 return VD->isThisDeclarationADefinition() == VarDecl::Definition;
9634 llvm_unreachable("unexpected decl type");
9635 };
9636 auto FoundAcceptableDefinition = [&](NamedDecl *D) {
9638 return DefinitionIsAcceptable(D);
9639
9640 // See ASTDeclReader::attachPreviousDeclImpl. Now we still
9641 // may demote definition to declaration for decls in haeder modules,
9642 // so avoid looking at its redeclaration to save time.
9643 // NOTE: If we don't demote definition to declarations for decls
9644 // in header modules, remove the condition.
9646 return DefinitionIsAcceptable(D);
9647
9648 for (auto *RD : D->redecls()) {
9649 auto *ND = cast<NamedDecl>(RD);
9650 if (!IsDefinition(ND))
9651 continue;
9652 if (DefinitionIsAcceptable(ND)) {
9653 *Suggested = ND;
9654 return true;
9655 }
9656 }
9657
9658 return false;
9659 };
9660
9661 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9662 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9663 RD = Pattern;
9664 D = RD->getDefinition();
9665 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
9666 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9667 ED = Pattern;
9668 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9669 // If the enum has a fixed underlying type, it may have been forward
9670 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9671 // the enum and assign it the underlying type of `int`. Since we're only
9672 // looking for a complete type (not a definition), any visible declaration
9673 // of it will do.
9674 *Suggested = nullptr;
9675 for (auto *Redecl : ED->redecls()) {
9676 if (isAcceptable(Redecl, Kind))
9677 return true;
9678 if (Redecl->isThisDeclarationADefinition() ||
9679 (Redecl->isCanonicalDecl() && !*Suggested))
9680 *Suggested = Redecl;
9681 }
9682
9683 return false;
9684 }
9685 D = ED->getDefinition();
9686 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
9687 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9688 FD = Pattern;
9689 D = FD->getDefinition();
9690 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
9691 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9692 VD = Pattern;
9693 D = VD->getDefinition();
9694 }
9695
9696 assert(D && "missing definition for pattern of instantiated definition");
9697
9698 *Suggested = D;
9699
9700 if (FoundAcceptableDefinition(D))
9701 return true;
9702
9703 // The external source may have additional definitions of this entity that are
9704 // visible, so complete the redeclaration chain now and ask again.
9705 if (auto *Source = Context.getExternalSource()) {
9706 Source->CompleteRedeclChain(D);
9707 return FoundAcceptableDefinition(D);
9708 }
9709
9710 return false;
9711}
9712
9713/// Determine whether there is any declaration of \p D that was ever a
9714/// definition (perhaps before module merging) and is currently visible.
9715/// \param D The definition of the entity.
9716/// \param Suggested Filled in with the declaration that should be made visible
9717/// in order to provide a definition of this entity.
9718/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9719/// not defined. This only matters for enums with a fixed underlying
9720/// type, since in all other cases, a type is complete if and only if it
9721/// is defined.
9723 bool OnlyNeedComplete) {
9725 OnlyNeedComplete);
9726}
9727
9728/// Determine whether there is any declaration of \p D that was ever a
9729/// definition (perhaps before module merging) and is currently
9730/// reachable.
9731/// \param D The definition of the entity.
9732/// \param Suggested Filled in with the declaration that should be made
9733/// reachable
9734/// in order to provide a definition of this entity.
9735/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9736/// not defined. This only matters for enums with a fixed underlying
9737/// type, since in all other cases, a type is complete if and only if it
9738/// is defined.
9740 bool OnlyNeedComplete) {
9742 OnlyNeedComplete);
9743}
9744
9745/// Locks in the inheritance model for the given class and all of its bases.
9747 RD = RD->getMostRecentDecl();
9748 if (!RD->hasAttr<MSInheritanceAttr>()) {
9750 bool BestCase = false;
9753 BestCase = true;
9754 IM = RD->calculateInheritanceModel();
9755 break;
9758 break;
9761 break;
9764 break;
9765 }
9766
9769 : RD->getSourceRange();
9770 RD->addAttr(MSInheritanceAttr::CreateImplicit(
9771 S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
9773 }
9774}
9775
9776bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9777 CompleteTypeKind Kind,
9778 TypeDiagnoser *Diagnoser) {
9779 // FIXME: Add this assertion to make sure we always get instantiation points.
9780 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9781 // FIXME: Add this assertion to help us flush out problems with
9782 // checking for dependent types and type-dependent expressions.
9783 //
9784 // assert(!T->isDependentType() &&
9785 // "Can't ask whether a dependent type is complete");
9786
9787 if (const auto *MPTy = dyn_cast<MemberPointerType>(T.getCanonicalType())) {
9788 if (CXXRecordDecl *RD = MPTy->getMostRecentCXXRecordDecl();
9789 RD && !RD->isDependentType()) {
9790 CanQualType T = Context.getCanonicalTagType(RD);
9791 if (getLangOpts().CompleteMemberPointers && !RD->isBeingDefined() &&
9792 RequireCompleteType(Loc, T, Kind, diag::err_memptr_incomplete))
9793 return true;
9794
9795 // We lock in the inheritance model once somebody has asked us to ensure
9796 // that a pointer-to-member type is complete.
9797 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9798 (void)isCompleteType(Loc, T);
9799 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
9800 }
9801 }
9802 }
9803
9804 NamedDecl *Def = nullptr;
9806 bool Incomplete = (T->isIncompleteType(&Def) ||
9808
9809 // Check that any necessary explicit specializations are visible. For an
9810 // enum, we just need the declaration, so don't check this.
9811 if (Def && !isa<EnumDecl>(Def))
9813
9814 // If we have a complete type, we're done.
9815 if (!Incomplete) {
9816 NamedDecl *Suggested = nullptr;
9817 if (Def &&
9818 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
9819 // If the user is going to see an error here, recover by making the
9820 // definition visible.
9821 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9822 if (Diagnoser && Suggested)
9824 /*Recover*/ TreatAsComplete);
9825 return !TreatAsComplete;
9826 }
9827 return false;
9828 }
9829
9830 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
9831 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
9832
9833 // Give the external source a chance to provide a definition of the type.
9834 // This is kept separate from completing the redeclaration chain so that
9835 // external sources such as LLDB can avoid synthesizing a type definition
9836 // unless it's actually needed.
9837 if (Tag || IFace) {
9838 // Avoid diagnosing invalid decls as incomplete.
9839 if (Def->isInvalidDecl())
9840 return true;
9841
9842 // Give the external AST source a chance to complete the type.
9843 if (auto *Source = Context.getExternalSource()) {
9844 if (Tag && Tag->hasExternalLexicalStorage())
9845 Source->CompleteType(Tag);
9846 if (IFace && IFace->hasExternalLexicalStorage())
9847 Source->CompleteType(IFace);
9848 // If the external source completed the type, go through the motions
9849 // again to ensure we're allowed to use the completed type.
9850 if (!T->isIncompleteType())
9851 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9852 }
9853 }
9854
9855 // If we have a class template specialization or a class member of a
9856 // class template specialization, or an array with known size of such,
9857 // try to instantiate it.
9858 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
9859 bool Instantiated = false;
9860 bool Diagnosed = false;
9861 if (RD->isDependentContext()) {
9862 // Don't try to instantiate a dependent class (eg, a member template of
9863 // an instantiated class template specialization).
9864 // FIXME: Can this ever happen?
9865 } else if (auto *ClassTemplateSpec =
9866 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
9867 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9870 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9871 /*Complain=*/Diagnoser, ClassTemplateSpec->hasStrictPackMatch());
9872 });
9873 Instantiated = true;
9874 }
9875 } else {
9876 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9877 if (!RD->isBeingDefined() && Pattern) {
9878 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9879 assert(MSI && "Missing member specialization information?");
9880 // This record was instantiated from a class within a template.
9881 if (MSI->getTemplateSpecializationKind() !=
9884 Diagnosed = InstantiateClass(Loc, RD, Pattern,
9887 /*Complain=*/Diagnoser);
9888 });
9889 Instantiated = true;
9890 }
9891 }
9892 }
9893
9894 if (Instantiated) {
9895 // Instantiate* might have already complained that the template is not
9896 // defined, if we asked it to.
9897 if (Diagnoser && Diagnosed)
9898 return true;
9899 // If we instantiated a definition, check that it's usable, even if
9900 // instantiation produced an error, so that repeated calls to this
9901 // function give consistent answers.
9902 if (!T->isIncompleteType())
9903 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9904 }
9905 }
9906
9907 // FIXME: If we didn't instantiate a definition because of an explicit
9908 // specialization declaration, check that it's visible.
9909
9910 if (!Diagnoser)
9911 return true;
9912
9913 Diagnoser->diagnose(*this, Loc, T);
9914
9915 // If the type was a forward declaration of a class/struct/union
9916 // type, produce a note.
9917 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9918 Diag(Tag->getLocation(), Tag->isBeingDefined()
9919 ? diag::note_type_being_defined
9920 : diag::note_forward_declaration)
9921 << Context.getCanonicalTagType(Tag);
9922
9923 // If the Objective-C class was a forward declaration, produce a note.
9924 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9925 Diag(IFace->getLocation(), diag::note_forward_class);
9926
9927 // If we have external information that we can use to suggest a fix,
9928 // produce a note.
9929 if (ExternalSource)
9930 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9931
9932 return true;
9933}
9934
9936 CompleteTypeKind Kind, unsigned DiagID) {
9937 BoundTypeDiagnoser<> Diagnoser(DiagID);
9938 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9939}
9940
9941/// Get diagnostic %select index for tag kind for
9942/// literal type diagnostic message.
9943/// WARNING: Indexes apply to particular diagnostics only!
9944///
9945/// \returns diagnostic %select index.
9947 switch (Tag) {
9949 return 0;
9951 return 1;
9952 case TagTypeKind::Class:
9953 return 2;
9954 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9955 }
9956}
9957
9959 TypeDiagnoser &Diagnoser) {
9960 assert(!T->isDependentType() && "type should not be dependent");
9961
9962 QualType ElemType = Context.getBaseElementType(T);
9963 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9964 T->isLiteralType(Context))
9965 return false;
9966
9967 Diagnoser.diagnose(*this, Loc, T);
9968
9969 if (T->isVariableArrayType())
9970 return true;
9971
9972 if (!ElemType->isRecordType())
9973 return true;
9974
9975 // A partially-defined class type can't be a literal type, because a literal
9976 // class type must have a trivial destructor (which can't be checked until
9977 // the class definition is complete).
9978 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9979 return true;
9980
9981 const auto *RD = ElemType->castAsCXXRecordDecl();
9982 // [expr.prim.lambda]p3:
9983 // This class type is [not] a literal type.
9984 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9985 Diag(RD->getLocation(), diag::note_non_literal_lambda);
9986 return true;
9987 }
9988
9989 // If the class has virtual base classes, then it's not an aggregate, and
9990 // cannot have any constexpr constructors or a trivial default constructor,
9991 // so is non-literal. This is better to diagnose than the resulting absence
9992 // of constexpr constructors.
9993 if (!getLangOpts().CPlusPlus26 && RD->getNumVBases()) {
9994 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9995 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9996 for (const auto &I : RD->vbases())
9997 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9998 << I.getSourceRange();
9999 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
10000 !RD->hasTrivialDefaultConstructor()) {
10001 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
10002 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
10003 for (const auto &I : RD->bases()) {
10004 if (!I.getType()->isLiteralType(Context)) {
10005 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
10006 << RD << I.getType() << I.getSourceRange();
10007 return true;
10008 }
10009 }
10010 for (const auto *I : RD->fields()) {
10011 if (!I->getType()->isLiteralType(Context) ||
10012 I->getType().isVolatileQualified()) {
10013 Diag(I->getLocation(), diag::note_non_literal_field)
10014 << RD << I << I->getType()
10015 << I->getType().isVolatileQualified();
10016 return true;
10017 }
10018 }
10019 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
10020 : !RD->hasTrivialDestructor()) {
10021 // All fields and bases are of literal types, so have trivial or constexpr
10022 // destructors. If this class's destructor is non-trivial / non-constexpr,
10023 // it must be user-declared.
10024 CXXDestructorDecl *Dtor = RD->getDestructor();
10025 assert(Dtor && "class has literal fields and bases but no dtor?");
10026 if (!Dtor)
10027 return true;
10028
10029 if (getLangOpts().CPlusPlus20) {
10030 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
10031 << RD;
10032 } else {
10033 Diag(Dtor->getLocation(), Dtor->isUserProvided()
10034 ? diag::note_non_literal_user_provided_dtor
10035 : diag::note_non_literal_nontrivial_dtor)
10036 << RD;
10037 if (!Dtor->isUserProvided())
10040 /*Diagnose*/ true);
10041 }
10042 }
10043
10044 return true;
10045}
10046
10048 BoundTypeDiagnoser<> Diagnoser(DiagID);
10049 return RequireLiteralType(Loc, T, Diagnoser);
10050}
10051
10053 assert(!E->hasPlaceholderType() && "unexpected placeholder");
10054
10055 if (!getLangOpts().CPlusPlus && E->refersToBitField())
10056 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
10057 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
10058
10059 if (!E->isTypeDependent()) {
10060 QualType T = E->getType();
10061 if (const TagType *TT = T->getAs<TagType>())
10062 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
10063 }
10064 return Context.getTypeOfExprType(E, Kind);
10065}
10066
10067static void
10070 // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl.
10071 auto *CountDecl = cast<DeclRefExpr>(E)->getDecl();
10072 Decls.push_back(TypeCoupledDeclRefInfo(CountDecl, /*IsDref*/ false));
10073}
10074
10076 FieldDecl *FD, Expr *Arg) {
10077 assert(Arg);
10078
10079 // Only the counted_by family exists so far.
10080 auto *CATy = cast<CountAttributedType>(BATy);
10081
10082 auto Reject = [&]() -> bool {
10083 // Guarded so shared declarators (`IP __counted_by(n) a, b;`) only complete
10084 // the node once.
10085 if (!CATy->getCountExpr())
10086 Context.completeCountAttributedType(CATy, Arg, {});
10087 FD->setInvalidDecl();
10088 return false;
10089 };
10090
10091 if (Arg->containsErrors())
10092 return Reject();
10093
10094 if (CheckCountedByAttrOnField(FD, Arg, CATy->isCountInBytes(),
10095 CATy->isOrNull()))
10096 return Reject();
10097
10099 BuildTypeCoupledDecls(Arg, Decls);
10100 // Several declarators can share one node when the attribute was written in
10101 // declaration-specifier position (`IP __counted_by(n) a, b;`), so this runs
10102 // once per field
10103 if (!CATy->getCountExpr())
10104 Context.completeCountAttributedType(CATy, Arg, Decls);
10105
10106 return true;
10107}
10108
10110 Expr *CountExpr,
10111 bool CountInBytes,
10112 bool OrNull) {
10113 assert(WrappedTy->isIncompleteArrayType() || WrappedTy->isPointerType());
10114
10116 BuildTypeCoupledDecls(CountExpr, Decls);
10117 /// When the resulting expression is invalid, we still create the AST using
10118 /// the original count expression for the sake of AST dump.
10119 return Context.getCountAttributedType(WrappedTy, CountExpr, CountInBytes,
10120 OrNull, Decls);
10121}
10122
10123/// getDecltypeForExpr - Given an expr, will return the decltype for
10124/// that expression, according to the rules in C++11
10125/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
10127
10128 Expr *IDExpr = E;
10129 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
10130 IDExpr = ImplCastExpr->getSubExpr();
10131
10132 if (auto *PackExpr = dyn_cast<PackIndexingExpr>(E)) {
10133 if (E->isInstantiationDependent())
10134 IDExpr = PackExpr->getPackIdExpression();
10135 else
10136 IDExpr = PackExpr->getSelectedExpr();
10137 }
10138
10139 if (E->isTypeDependent())
10140 return Context.DependentTy;
10141
10142 // C++11 [dcl.type.simple]p4:
10143 // The type denoted by decltype(e) is defined as follows:
10144
10145 // C++20:
10146 // - if E is an unparenthesized id-expression naming a non-type
10147 // template-parameter (13.2), decltype(E) is the type of the
10148 // template-parameter after performing any necessary type deduction
10149 // Note that this does not pick up the implicit 'const' for a template
10150 // parameter object. This rule makes no difference before C++20 so we apply
10151 // it unconditionally.
10152 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
10153 IDExpr = SNTTPE->getReplacement();
10154
10155 // - if e is an unparenthesized id-expression or an unparenthesized class
10156 // member access (5.2.5), decltype(e) is the type of the entity named
10157 // by e. If there is no such entity, or if e names a set of overloaded
10158 // functions, the program is ill-formed;
10159 //
10160 // We apply the same rules for Objective-C ivar and property references.
10161 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
10162 const ValueDecl *VD = DRE->getDecl();
10163 QualType T = VD->getType();
10164 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
10165 }
10166 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
10167 if (const auto *VD = ME->getMemberDecl())
10168 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
10169 return VD->getType();
10170 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
10171 return IR->getDecl()->getType();
10172 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
10173 if (PR->isExplicitProperty())
10174 return PR->getExplicitProperty()->getType();
10175 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
10176 return PE->getType();
10177 }
10178
10179 // C++11 [expr.lambda.prim]p18:
10180 // Every occurrence of decltype((x)) where x is a possibly
10181 // parenthesized id-expression that names an entity of automatic
10182 // storage duration is treated as if x were transformed into an
10183 // access to a corresponding data member of the closure type that
10184 // would have been declared if x were an odr-use of the denoted
10185 // entity.
10186 if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
10187 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
10188 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
10189 QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
10190 if (!T.isNull())
10191 return Context.getLValueReferenceType(T);
10192 }
10193 }
10194 }
10195
10196 return Context.getReferenceQualifiedType(E);
10197}
10198
10199QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
10200 assert(!E->hasPlaceholderType() && "unexpected placeholder");
10201
10202 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
10203 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
10204 // The expression operand for decltype is in an unevaluated expression
10205 // context, so side effects could result in unintended consequences.
10206 // Exclude instantiation-dependent expressions, because 'decltype' is often
10207 // used to build SFINAE gadgets.
10208 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
10209 }
10210 return Context.getDecltypeType(E, getDecltypeForExpr(E));
10211}
10212
10214 SourceLocation Loc) {
10215 if (!IndexExpr)
10216 return QualType();
10217
10218 // Diagnose unexpanded packs but continue to improve recovery.
10219 if (!Pattern->containsUnexpandedParameterPack())
10220 Diag(Loc, diag::err_expected_name_of_pack) << Pattern;
10221
10222 QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc);
10223
10224 if (!Type.isNull())
10225 DiagCompat(Loc, diag_compat::pack_indexing);
10226 return Type;
10227}
10228
10230 SourceLocation Loc, bool FullySubstituted,
10231 ArrayRef<QualType> Expansions) {
10232
10233 UnsignedOrNone Index = std::nullopt;
10234 if (!IndexExpr->isInstantiationDependent()) {
10235 llvm::APSInt Value;
10237 IndexExpr, Context.getSizeType(), Value, CCEKind::PackIndex);
10238
10239 if (!Res.isUsable() || !Value.isRepresentableByInt64())
10240 return QualType();
10241
10242 IndexExpr = Res.get();
10243 uint64_t V = Value.getZExtValue();
10244 if (FullySubstituted && V >= Expansions.size()) {
10245 Diag(IndexExpr->getBeginLoc(), diag::err_pack_index_out_of_bound)
10246 << V << Pattern << Expansions.size();
10247 return QualType();
10248 }
10249 Index = static_cast<unsigned>(V);
10250 }
10251
10252 return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted,
10253 Expansions, Index);
10254}
10255
10257 SourceLocation Loc) {
10258 assert(BaseType->isEnumeralType());
10259 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
10260
10261 S.DiagnoseUseOfDecl(ED, Loc);
10262
10263 QualType Underlying = ED->getIntegerType();
10264 if (Underlying.isNull()) {
10265 Underlying = ED->getDefinition()->getIntegerType();
10266 assert(!Underlying.isNull());
10267 }
10268
10269 return Underlying;
10270}
10271
10273 SourceLocation Loc) {
10274 if (!BaseType->isEnumeralType()) {
10275 Diag(Loc, diag::err_only_enums_have_underlying_types);
10276 return QualType();
10277 }
10278
10279 // The enum could be incomplete if we're parsing its definition or
10280 // recovering from an error.
10281 NamedDecl *FwdDecl = nullptr;
10282 if (BaseType->isIncompleteType(&FwdDecl)) {
10283 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
10284 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
10285 return QualType();
10286 }
10287
10288 return GetEnumUnderlyingType(*this, BaseType, Loc);
10289}
10290
10292 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
10293 ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
10295 : BaseType;
10296
10297 return Pointer.isNull() ? QualType() : Pointer;
10298}
10299
10301 if (!BaseType->isAnyPointerType())
10302 return BaseType;
10303
10304 return BaseType->getPointeeType();
10305}
10306
10308 QualType Underlying = BaseType.getNonReferenceType();
10309 if (Underlying->isArrayType())
10310 return Context.getDecayedType(Underlying);
10311
10312 if (Underlying->isFunctionType())
10313 return BuiltinAddPointer(BaseType, Loc);
10314
10315 SplitQualType Split = Underlying.getSplitUnqualifiedType();
10316 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
10317 // in the same group of qualifiers as 'const' and 'volatile', we're extending
10318 // '__decay(T)' so that it removes all qualifiers.
10319 Split.Quals.removeCVRQualifiers();
10320 return Context.getQualifiedType(Split);
10321}
10322
10324 SourceLocation Loc) {
10325 assert(LangOpts.CPlusPlus);
10327 BaseType.isReferenceable()
10328 ? BuildReferenceType(BaseType,
10329 UKind == UnaryTransformType::AddLvalueReference,
10330 Loc, DeclarationName())
10331 : BaseType;
10332 return Reference.isNull() ? QualType() : Reference;
10333}
10334
10336 SourceLocation Loc) {
10337 if (UKind == UnaryTransformType::RemoveAllExtents)
10338 return Context.getBaseElementType(BaseType);
10339
10340 if (const auto *AT = Context.getAsArrayType(BaseType))
10341 return AT->getElementType();
10342
10343 return BaseType;
10344}
10345
10347 SourceLocation Loc) {
10348 assert(LangOpts.CPlusPlus);
10349 QualType T = BaseType.getNonReferenceType();
10350 if (UKind == UTTKind::RemoveCVRef &&
10351 (T.isConstQualified() || T.isVolatileQualified())) {
10352 Qualifiers Quals;
10353 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
10354 Quals.removeConst();
10355 Quals.removeVolatile();
10356 T = Context.getQualifiedType(Unqual, Quals);
10357 }
10358 return T;
10359}
10360
10362 SourceLocation Loc) {
10363 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
10364 BaseType->isFunctionType())
10365 return BaseType;
10366
10367 Qualifiers Quals;
10368 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
10369
10370 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
10371 Quals.removeConst();
10372 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
10373 Quals.removeVolatile();
10374 if (UKind == UTTKind::RemoveRestrict)
10375 Quals.removeRestrict();
10376
10377 return Context.getQualifiedType(Unqual, Quals);
10378}
10379
10381 bool IsMakeSigned,
10382 SourceLocation Loc) {
10383 if (BaseType->isEnumeralType()) {
10384 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
10385 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
10386 unsigned int Bits = BitInt->getNumBits();
10387 if (Bits > 1)
10388 return S.Context.getBitIntType(!IsMakeSigned, Bits);
10389
10390 S.Diag(Loc, diag::err_make_signed_integral_only)
10391 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
10392 return QualType();
10393 }
10394 if (Underlying->isBooleanType()) {
10395 S.Diag(Loc, diag::err_make_signed_integral_only)
10396 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
10397 << Underlying;
10398 return QualType();
10399 }
10400 }
10401
10402 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
10403 std::array<CanQualType *, 6> AllSignedIntegers = {
10406 ArrayRef<CanQualType *> AvailableSignedIntegers(
10407 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
10408 std::array<CanQualType *, 6> AllUnsignedIntegers = {
10412 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
10413 AllUnsignedIntegers.size() -
10414 Int128Unsupported);
10415 ArrayRef<CanQualType *> *Consider =
10416 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
10417
10418 uint64_t BaseSize = S.Context.getTypeSize(BaseType);
10419 auto *Result =
10420 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
10421 return BaseSize == S.Context.getTypeSize(T->getTypePtr());
10422 });
10423
10424 assert(Result != Consider->end());
10425 return QualType((*Result)->getTypePtr(), 0);
10426}
10427
10429 SourceLocation Loc) {
10430 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
10431 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
10432 BaseType->isBooleanType() ||
10433 (BaseType->isBitIntType() &&
10434 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
10435 Diag(Loc, diag::err_make_signed_integral_only)
10436 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
10437 return QualType();
10438 }
10439
10440 bool IsNonIntIntegral =
10441 BaseType->isChar16Type() || BaseType->isChar32Type() ||
10442 BaseType->isWideCharType() || BaseType->isEnumeralType();
10443
10444 QualType Underlying =
10445 IsNonIntIntegral
10446 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
10447 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
10448 : Context.getCorrespondingUnsignedType(BaseType);
10449 if (Underlying.isNull())
10450 return Underlying;
10451 return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
10452}
10453
10455 SourceLocation Loc) {
10456 if (BaseType->isDependentType())
10457 return Context.getUnaryTransformType(BaseType, BaseType, UKind);
10459 switch (UKind) {
10460 case UnaryTransformType::EnumUnderlyingType: {
10461 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
10462 break;
10463 }
10464 case UnaryTransformType::AddPointer: {
10465 Result = BuiltinAddPointer(BaseType, Loc);
10466 break;
10467 }
10468 case UnaryTransformType::RemovePointer: {
10469 Result = BuiltinRemovePointer(BaseType, Loc);
10470 break;
10471 }
10472 case UnaryTransformType::Decay: {
10473 Result = BuiltinDecay(BaseType, Loc);
10474 break;
10475 }
10476 case UnaryTransformType::AddLvalueReference:
10477 case UnaryTransformType::AddRvalueReference: {
10478 Result = BuiltinAddReference(BaseType, UKind, Loc);
10479 break;
10480 }
10481 case UnaryTransformType::RemoveAllExtents:
10482 case UnaryTransformType::RemoveExtent: {
10483 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
10484 break;
10485 }
10486 case UnaryTransformType::RemoveCVRef:
10487 case UnaryTransformType::RemoveReference: {
10488 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
10489 break;
10490 }
10491 case UnaryTransformType::RemoveConst:
10492 case UnaryTransformType::RemoveCV:
10493 case UnaryTransformType::RemoveRestrict:
10494 case UnaryTransformType::RemoveVolatile: {
10495 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
10496 break;
10497 }
10498 case UnaryTransformType::MakeSigned:
10499 case UnaryTransformType::MakeUnsigned: {
10500 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
10501 break;
10502 }
10503 }
10504
10505 return !Result.isNull()
10506 ? Context.getUnaryTransformType(BaseType, Result, UKind)
10507 : Result;
10508}
10509
10511 if (!T->isDependentType() && !isa<AutoType>(T)) {
10512 // FIXME: It isn't entirely clear whether incomplete atomic types
10513 // are allowed or not; for simplicity, ban them for the moment.
10514 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
10515 return QualType();
10516
10517 int DisallowedKind = -1;
10518 if (T->isArrayType())
10519 DisallowedKind = 1;
10520 else if (T->isFunctionType())
10521 DisallowedKind = 2;
10522 else if (T->isReferenceType())
10523 DisallowedKind = 3;
10524 else if (T->isAtomicType())
10525 DisallowedKind = 4;
10526 else if (T.hasQualifiers())
10527 DisallowedKind = 5;
10528 else if (T->isSizelessType())
10529 DisallowedKind = 6;
10530 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus)
10531 // Some other non-trivially-copyable type (probably a C++ class)
10532 DisallowedKind = 7;
10533 else if (T->isBitIntType())
10534 DisallowedKind = 8;
10535 else if (getLangOpts().C23 && T->isUndeducedAutoType())
10536 // _Atomic auto is prohibited in C23
10537 DisallowedKind = 9;
10538 else if (T->isOverflowBehaviorType())
10539 // Overflow behavior types do not compose with _Atomic
10540 DisallowedKind = 10;
10541
10542 if (DisallowedKind != -1) {
10543 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
10544 return QualType();
10545 }
10546
10547 // FIXME: Do we need any handling for ARC here?
10548 }
10549
10550 // Build the pointer type.
10551 return Context.getAtomicType(T);
10552}
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 void fillVectorTypeLoc(VectorTypeLoc VTL, const ParsedAttributesView &Attrs)
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:2713
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2725
void setParensRange(SourceRange Range)
Definition TypeLoc.h:2749
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:2497
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2463
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2513
TemplateName getNamedConcept() const
Definition TypeLoc.h:2487
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2506
void setConceptReference(ConceptReference *CR)
Definition TypeLoc.h:2457
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2481
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition TypeLoc.h:2524
unsigned getNumArgs() const
Definition TypeLoc.h:2520
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2493
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2451
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:2924
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:2343
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2340
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:2664
void initializeLocal(ASTContext &Context, SourceLocation Loc)
Definition TypeLoc.h:2152
void initializeLocal(ASTContext &Context, SourceLocation Loc)
Definition TypeLoc.h:2118
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:4194
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4367
EnumDecl * getDefinition() const
Definition Decl.h:4306
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:3341
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:2183
void setAttrColumnOperand(Expr *e)
Definition TypeLoc.h:2189
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2198
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2177
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:2772
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2777
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:120
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:1424
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7918
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
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:13888
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1165
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:8444
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9545
UnaryTransformType::UTTKind UTTKind
Definition Sema.h:15750
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:1571
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:1511
@ AcceptSizeless
Relax the normal rules for complete types so that they include sizeless built-in types.
Definition Sema.h:15430
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:1332
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:231
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:1556
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:935
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:1799
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:14769
const LangOptions & getLangOpts() const
Definition Sema.h:928
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:1331
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:1330
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2740
SemaHLSL & HLSL()
Definition Sema.h:1521
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:1877
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:6683
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:15405
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1367
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:2477
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:651
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1484
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:1566
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:8381
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:15862
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:14258
SourceManager & getSourceManager() const
Definition Sema.h:933
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:4274
@ NTCUK_Copy
Definition Sema.h:4275
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:13979
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15804
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:1622
ASTConsumer & Consumer
Definition Sema.h:1333
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:1335
DiagnosticsEngine & Diags
Definition Sema.h:1334
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:929
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:1872
llvm::BumpPtrAllocator BumpAlloc
Definition Sema.h:1277
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:2281
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:3900
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:4031
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:4001
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:5030
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:3721
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:2317
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:3850
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3745
void setParensRange(SourceRange range)
Definition TypeLoc.h:2276
void setTypeofLoc(SourceLocation Loc)
Definition TypeLoc.h:2252
void setParensRange(SourceRange Range)
Definition TypeLoc.h:2420
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2396
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition TypeLoc.h:2408
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:3446
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 initializeLocal(ASTContext &Context, SourceLocation Loc)
Definition TypeLoc.h:2090
void setSizeExpr(Expr *E)
Definition TypeLoc.h:2084
void setAttrNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2081
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:453
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:556
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:641
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:384
@ 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:838
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
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:434
OptionalUnsigned< NullabilityKind > NullabilityKindOrNone
Definition Specifiers.h:366
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
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:247
SourceLocation PointerEndLoc
The end location for the first pointer declarator in the file.
Definition Sema.h:254
SourceLocation PointerLoc
The first pointer declarator (of any pointer kind) in the file that does not have a corresponding nul...
Definition Sema.h:250
bool SawTypeNullability
Whether we saw any type nullability annotations in the given file.
Definition Sema.h:260
uint8_t PointerKind
Which kind of pointer declarator we saw.
Definition Sema.h:257
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:8458
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.