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