clang 20.0.0git
SemaType.cpp
Go to the documentation of this file.
1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements type-related semantic analysis.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprObjC.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLoc.h"
33#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Lookup.h"
39#include "clang/Sema/SemaCUDA.h"
40#include "clang/Sema/SemaHLSL.h"
41#include "clang/Sema/SemaObjC.h"
43#include "clang/Sema/Template.h"
45#include "llvm/ADT/ArrayRef.h"
46#include "llvm/ADT/STLForwardCompat.h"
47#include "llvm/ADT/StringExtras.h"
48#include "llvm/IR/DerivedTypes.h"
49#include "llvm/Support/ErrorHandling.h"
50#include <bitset>
51#include <optional>
52
53using namespace clang;
54
59};
60
61/// isOmittedBlockReturnType - Return true if this declarator is missing a
62/// return type because this is a omitted return type on a block literal.
64 if (D.getContext() != DeclaratorContext::BlockLiteral ||
65 D.getDeclSpec().hasTypeSpecifier())
66 return false;
67
68 if (D.getNumTypeObjects() == 0)
69 return true; // ^{ ... }
70
71 if (D.getNumTypeObjects() == 1 &&
72 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
73 return true; // ^(int X, float Y) { ... }
74
75 return false;
76}
77
78/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
79/// doesn't apply to the given type.
80static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
81 QualType type) {
82 TypeDiagSelector WhichType;
83 bool useExpansionLoc = true;
84 switch (attr.getKind()) {
85 case ParsedAttr::AT_ObjCGC:
86 WhichType = TDS_Pointer;
87 break;
88 case ParsedAttr::AT_ObjCOwnership:
89 WhichType = TDS_ObjCObjOrBlock;
90 break;
91 default:
92 // Assume everything else was a function attribute.
93 WhichType = TDS_Function;
94 useExpansionLoc = false;
95 break;
96 }
97
98 SourceLocation loc = attr.getLoc();
99 StringRef name = attr.getAttrName()->getName();
100
101 // The GC attributes are usually written with macros; special-case them.
102 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
103 : nullptr;
104 if (useExpansionLoc && loc.isMacroID() && II) {
105 if (II->isStr("strong")) {
106 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
107 } else if (II->isStr("weak")) {
108 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
109 }
110 }
111
112 S.Diag(loc, attr.isRegularKeywordAttribute()
113 ? diag::err_type_attribute_wrong_type
114 : diag::warn_type_attribute_wrong_type)
115 << name << WhichType << type;
116}
117
118// objc_gc applies to Objective-C pointers or, otherwise, to the
119// smallest available pointer type (i.e. 'void*' in 'void**').
120#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
121 case ParsedAttr::AT_ObjCGC: \
122 case ParsedAttr::AT_ObjCOwnership
123
124// Calling convention attributes.
125#define CALLING_CONV_ATTRS_CASELIST \
126 case ParsedAttr::AT_CDecl: \
127 case ParsedAttr::AT_FastCall: \
128 case ParsedAttr::AT_StdCall: \
129 case ParsedAttr::AT_ThisCall: \
130 case ParsedAttr::AT_RegCall: \
131 case ParsedAttr::AT_Pascal: \
132 case ParsedAttr::AT_SwiftCall: \
133 case ParsedAttr::AT_SwiftAsyncCall: \
134 case ParsedAttr::AT_VectorCall: \
135 case ParsedAttr::AT_AArch64VectorPcs: \
136 case ParsedAttr::AT_AArch64SVEPcs: \
137 case ParsedAttr::AT_AMDGPUKernelCall: \
138 case ParsedAttr::AT_MSABI: \
139 case ParsedAttr::AT_SysVABI: \
140 case ParsedAttr::AT_Pcs: \
141 case ParsedAttr::AT_IntelOclBicc: \
142 case ParsedAttr::AT_PreserveMost: \
143 case ParsedAttr::AT_PreserveAll: \
144 case ParsedAttr::AT_M68kRTD: \
145 case ParsedAttr::AT_PreserveNone: \
146 case ParsedAttr::AT_RISCVVectorCC
147
148// Function type attributes.
149#define FUNCTION_TYPE_ATTRS_CASELIST \
150 case ParsedAttr::AT_NSReturnsRetained: \
151 case ParsedAttr::AT_NoReturn: \
152 case ParsedAttr::AT_NonBlocking: \
153 case ParsedAttr::AT_NonAllocating: \
154 case ParsedAttr::AT_Blocking: \
155 case ParsedAttr::AT_Allocating: \
156 case ParsedAttr::AT_Regparm: \
157 case ParsedAttr::AT_CmseNSCall: \
158 case ParsedAttr::AT_ArmStreaming: \
159 case ParsedAttr::AT_ArmStreamingCompatible: \
160 case ParsedAttr::AT_ArmPreserves: \
161 case ParsedAttr::AT_ArmIn: \
162 case ParsedAttr::AT_ArmOut: \
163 case ParsedAttr::AT_ArmInOut: \
164 case ParsedAttr::AT_ArmAgnostic: \
165 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
166 case ParsedAttr::AT_AnyX86NoCfCheck: \
167 CALLING_CONV_ATTRS_CASELIST
168
169// Microsoft-specific type qualifiers.
170#define MS_TYPE_ATTRS_CASELIST \
171 case ParsedAttr::AT_Ptr32: \
172 case ParsedAttr::AT_Ptr64: \
173 case ParsedAttr::AT_SPtr: \
174 case ParsedAttr::AT_UPtr
175
176// Nullability qualifiers.
177#define NULLABILITY_TYPE_ATTRS_CASELIST \
178 case ParsedAttr::AT_TypeNonNull: \
179 case ParsedAttr::AT_TypeNullable: \
180 case ParsedAttr::AT_TypeNullableResult: \
181 case ParsedAttr::AT_TypeNullUnspecified
182
183namespace {
184 /// An object which stores processing state for the entire
185 /// GetTypeForDeclarator process.
186 class TypeProcessingState {
187 Sema &sema;
188
189 /// The declarator being processed.
190 Declarator &declarator;
191
192 /// The index of the declarator chunk we're currently processing.
193 /// May be the total number of valid chunks, indicating the
194 /// DeclSpec.
195 unsigned chunkIndex;
196
197 /// The original set of attributes on the DeclSpec.
199
200 /// A list of attributes to diagnose the uselessness of when the
201 /// processing is complete.
202 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
203
204 /// Attributes corresponding to AttributedTypeLocs that we have not yet
205 /// populated.
206 // FIXME: The two-phase mechanism by which we construct Types and fill
207 // their TypeLocs makes it hard to correctly assign these. We keep the
208 // attributes in creation order as an attempt to make them line up
209 // properly.
210 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
211 SmallVector<TypeAttrPair, 8> AttrsForTypes;
212 bool AttrsForTypesSorted = true;
213
214 /// MacroQualifiedTypes mapping to macro expansion locations that will be
215 /// stored in a MacroQualifiedTypeLoc.
216 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
217
218 /// Flag to indicate we parsed a noderef attribute. This is used for
219 /// validating that noderef was used on a pointer or array.
220 bool parsedNoDeref;
221
222 // Flag to indicate that we already parsed a HLSL parameter modifier
223 // attribute. This prevents double-mutating the type.
224 bool ParsedHLSLParamMod;
225
226 public:
227 TypeProcessingState(Sema &sema, Declarator &declarator)
228 : sema(sema), declarator(declarator),
229 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false),
230 ParsedHLSLParamMod(false) {}
231
232 Sema &getSema() const {
233 return sema;
234 }
235
236 Declarator &getDeclarator() const {
237 return declarator;
238 }
239
240 bool isProcessingDeclSpec() const {
241 return chunkIndex == declarator.getNumTypeObjects();
242 }
243
244 unsigned getCurrentChunkIndex() const {
245 return chunkIndex;
246 }
247
248 void setCurrentChunkIndex(unsigned idx) {
249 assert(idx <= declarator.getNumTypeObjects());
250 chunkIndex = idx;
251 }
252
253 ParsedAttributesView &getCurrentAttributes() const {
254 if (isProcessingDeclSpec())
255 return getMutableDeclSpec().getAttributes();
256 return declarator.getTypeObject(chunkIndex).getAttrs();
257 }
258
259 /// Save the current set of attributes on the DeclSpec.
260 void saveDeclSpecAttrs() {
261 // Don't try to save them multiple times.
262 if (!savedAttrs.empty())
263 return;
264
265 DeclSpec &spec = getMutableDeclSpec();
266 llvm::append_range(savedAttrs,
267 llvm::make_pointer_range(spec.getAttributes()));
268 }
269
270 /// Record that we had nowhere to put the given type attribute.
271 /// We will diagnose such attributes later.
272 void addIgnoredTypeAttr(ParsedAttr &attr) {
273 ignoredTypeAttrs.push_back(&attr);
274 }
275
276 /// Diagnose all the ignored type attributes, given that the
277 /// declarator worked out to the given type.
278 void diagnoseIgnoredTypeAttrs(QualType type) const {
279 for (auto *Attr : ignoredTypeAttrs)
280 diagnoseBadTypeAttribute(getSema(), *Attr, type);
281 }
282
283 /// Get an attributed type for the given attribute, and remember the Attr
284 /// object so that we can attach it to the AttributedTypeLoc.
285 QualType getAttributedType(Attr *A, QualType ModifiedType,
286 QualType EquivType) {
287 QualType T =
288 sema.Context.getAttributedType(A, ModifiedType, EquivType);
289 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
290 AttrsForTypesSorted = false;
291 return T;
292 }
293
294 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
295 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
296 QualType WrappedType) {
297 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
298 }
299
300 /// Completely replace the \c auto in \p TypeWithAuto by
301 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
302 /// necessary.
303 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
304 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
305 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
306 // Attributed type still should be an attributed type after replacement.
307 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
308 for (TypeAttrPair &A : AttrsForTypes) {
309 if (A.first == AttrTy)
310 A.first = NewAttrTy;
311 }
312 AttrsForTypesSorted = false;
313 }
314 return T;
315 }
316
317 /// Extract and remove the Attr* for a given attributed type.
318 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
319 if (!AttrsForTypesSorted) {
320 llvm::stable_sort(AttrsForTypes, llvm::less_first());
321 AttrsForTypesSorted = true;
322 }
323
324 // FIXME: This is quadratic if we have lots of reuses of the same
325 // attributed type.
326 for (auto It = std::partition_point(
327 AttrsForTypes.begin(), AttrsForTypes.end(),
328 [=](const TypeAttrPair &A) { return A.first < AT; });
329 It != AttrsForTypes.end() && It->first == AT; ++It) {
330 if (It->second) {
331 const Attr *Result = It->second;
332 It->second = nullptr;
333 return Result;
334 }
335 }
336
337 llvm_unreachable("no Attr* for AttributedType*");
338 }
339
341 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
342 auto FoundLoc = LocsForMacros.find(MQT);
343 assert(FoundLoc != LocsForMacros.end() &&
344 "Unable to find macro expansion location for MacroQualifedType");
345 return FoundLoc->second;
346 }
347
348 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
350 LocsForMacros[MQT] = Loc;
351 }
352
353 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
354
355 bool didParseNoDeref() const { return parsedNoDeref; }
356
357 void setParsedHLSLParamMod(bool Parsed) { ParsedHLSLParamMod = Parsed; }
358
359 bool didParseHLSLParamMod() const { return ParsedHLSLParamMod; }
360
361 ~TypeProcessingState() {
362 if (savedAttrs.empty())
363 return;
364
365 getMutableDeclSpec().getAttributes().clearListOnly();
366 for (ParsedAttr *AL : savedAttrs)
367 getMutableDeclSpec().getAttributes().addAtEnd(AL);
368 }
369
370 private:
371 DeclSpec &getMutableDeclSpec() const {
372 return const_cast<DeclSpec&>(declarator.getDeclSpec());
373 }
374 };
375} // end anonymous namespace
376
378 ParsedAttributesView &fromList,
379 ParsedAttributesView &toList) {
380 fromList.remove(&attr);
381 toList.addAtEnd(&attr);
382}
383
384/// The location of a type attribute.
386 /// The attribute is in the decl-specifier-seq.
388 /// The attribute is part of a DeclaratorChunk.
390 /// The attribute is immediately after the declaration's name.
393
394static void
395processTypeAttrs(TypeProcessingState &state, QualType &type,
396 TypeAttrLocation TAL, const ParsedAttributesView &attrs,
397 CUDAFunctionTarget CFT = CUDAFunctionTarget::HostDevice);
398
399static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
401
402static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
403 ParsedAttr &attr, QualType &type);
404
405static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
406 QualType &type);
407
408static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
409 ParsedAttr &attr, QualType &type);
410
411static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
412 ParsedAttr &attr, QualType &type) {
413 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
414 return handleObjCGCTypeAttr(state, attr, type);
415 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
416 return handleObjCOwnershipTypeAttr(state, attr, type);
417}
418
419/// Given the index of a declarator chunk, check whether that chunk
420/// directly specifies the return type of a function and, if so, find
421/// an appropriate place for it.
422///
423/// \param i - a notional index which the search will start
424/// immediately inside
425///
426/// \param onlyBlockPointers Whether we should only look into block
427/// pointer types (vs. all pointer types).
429 unsigned i,
430 bool onlyBlockPointers) {
431 assert(i <= declarator.getNumTypeObjects());
432
433 DeclaratorChunk *result = nullptr;
434
435 // First, look inwards past parens for a function declarator.
436 for (; i != 0; --i) {
437 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
438 switch (fnChunk.Kind) {
440 continue;
441
442 // If we find anything except a function, bail out.
449 return result;
450
451 // If we do find a function declarator, scan inwards from that,
452 // looking for a (block-)pointer declarator.
454 for (--i; i != 0; --i) {
455 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
456 switch (ptrChunk.Kind) {
462 continue;
463
466 if (onlyBlockPointers)
467 continue;
468
469 [[fallthrough]];
470
472 result = &ptrChunk;
473 goto continue_outer;
474 }
475 llvm_unreachable("bad declarator chunk kind");
476 }
477
478 // If we run out of declarators doing that, we're done.
479 return result;
480 }
481 llvm_unreachable("bad declarator chunk kind");
482
483 // Okay, reconsider from our new point.
484 continue_outer: ;
485 }
486
487 // Ran out of chunks, bail out.
488 return result;
489}
490
491/// Given that an objc_gc attribute was written somewhere on a
492/// declaration *other* than on the declarator itself (for which, use
493/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
494/// didn't apply in whatever position it was written in, try to move
495/// it to a more appropriate position.
496static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
497 ParsedAttr &attr, QualType type) {
498 Declarator &declarator = state.getDeclarator();
499
500 // Move it to the outermost normal or block pointer declarator.
501 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
502 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
503 switch (chunk.Kind) {
506 // But don't move an ARC ownership attribute to the return type
507 // of a block.
508 DeclaratorChunk *destChunk = nullptr;
509 if (state.isProcessingDeclSpec() &&
510 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
511 destChunk = maybeMovePastReturnType(declarator, i - 1,
512 /*onlyBlockPointers=*/true);
513 if (!destChunk) destChunk = &chunk;
514
515 moveAttrFromListToList(attr, state.getCurrentAttributes(),
516 destChunk->getAttrs());
517 return;
518 }
519
522 continue;
523
524 // We may be starting at the return type of a block.
526 if (state.isProcessingDeclSpec() &&
527 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
529 declarator, i,
530 /*onlyBlockPointers=*/true)) {
531 moveAttrFromListToList(attr, state.getCurrentAttributes(),
532 dest->getAttrs());
533 return;
534 }
535 }
536 goto error;
537
538 // Don't walk through these.
542 goto error;
543 }
544 }
545 error:
546
547 diagnoseBadTypeAttribute(state.getSema(), attr, type);
548}
549
550/// Distribute an objc_gc type attribute that was written on the
551/// declarator.
553 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
554 Declarator &declarator = state.getDeclarator();
555
556 // objc_gc goes on the innermost pointer to something that's not a
557 // pointer.
558 unsigned innermost = -1U;
559 bool considerDeclSpec = true;
560 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
561 DeclaratorChunk &chunk = declarator.getTypeObject(i);
562 switch (chunk.Kind) {
565 innermost = i;
566 continue;
567
573 continue;
574
576 considerDeclSpec = false;
577 goto done;
578 }
579 }
580 done:
581
582 // That might actually be the decl spec if we weren't blocked by
583 // anything in the declarator.
584 if (considerDeclSpec) {
585 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
586 // Splice the attribute into the decl spec. Prevents the
587 // attribute from being applied multiple times and gives
588 // the source-location-filler something to work with.
589 state.saveDeclSpecAttrs();
591 declarator.getAttributes(), &attr);
592 return;
593 }
594 }
595
596 // Otherwise, if we found an appropriate chunk, splice the attribute
597 // into it.
598 if (innermost != -1U) {
600 declarator.getTypeObject(innermost).getAttrs());
601 return;
602 }
603
604 // Otherwise, diagnose when we're done building the type.
605 declarator.getAttributes().remove(&attr);
606 state.addIgnoredTypeAttr(attr);
607}
608
609/// A function type attribute was written somewhere in a declaration
610/// *other* than on the declarator itself or in the decl spec. Given
611/// that it didn't apply in whatever position it was written in, try
612/// to move it to a more appropriate position.
613static void distributeFunctionTypeAttr(TypeProcessingState &state,
614 ParsedAttr &attr, QualType type) {
615 Declarator &declarator = state.getDeclarator();
616
617 // Try to push the attribute from the return type of a function to
618 // the function itself.
619 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
620 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
621 switch (chunk.Kind) {
623 moveAttrFromListToList(attr, state.getCurrentAttributes(),
624 chunk.getAttrs());
625 return;
626
634 continue;
635 }
636 }
637
638 diagnoseBadTypeAttribute(state.getSema(), attr, type);
639}
640
641/// Try to distribute a function type attribute to the innermost
642/// function chunk or type. Returns true if the attribute was
643/// distributed, false if no location was found.
645 TypeProcessingState &state, ParsedAttr &attr,
646 ParsedAttributesView &attrList, QualType &declSpecType,
647 CUDAFunctionTarget CFT) {
648 Declarator &declarator = state.getDeclarator();
649
650 // Put it on the innermost function chunk, if there is one.
651 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
652 DeclaratorChunk &chunk = declarator.getTypeObject(i);
653 if (chunk.Kind != DeclaratorChunk::Function) continue;
654
655 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
656 return true;
657 }
658
659 return handleFunctionTypeAttr(state, attr, declSpecType, CFT);
660}
661
662/// A function type attribute was written in the decl spec. Try to
663/// apply it somewhere.
664static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
665 ParsedAttr &attr,
666 QualType &declSpecType,
667 CUDAFunctionTarget CFT) {
668 state.saveDeclSpecAttrs();
669
670 // Try to distribute to the innermost.
672 state, attr, state.getCurrentAttributes(), declSpecType, CFT))
673 return;
674
675 // If that failed, diagnose the bad attribute when the declarator is
676 // fully built.
677 state.addIgnoredTypeAttr(attr);
678}
679
680/// A function type attribute was written on the declarator or declaration.
681/// Try to apply it somewhere.
682/// `Attrs` is the attribute list containing the declaration (either of the
683/// declarator or the declaration).
684static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
685 ParsedAttr &attr,
686 QualType &declSpecType,
687 CUDAFunctionTarget CFT) {
688 Declarator &declarator = state.getDeclarator();
689
690 // Try to distribute to the innermost.
692 state, attr, declarator.getAttributes(), declSpecType, CFT))
693 return;
694
695 // If that failed, diagnose the bad attribute when the declarator is
696 // fully built.
697 declarator.getAttributes().remove(&attr);
698 state.addIgnoredTypeAttr(attr);
699}
700
701/// Given that there are attributes written on the declarator or declaration
702/// itself, try to distribute any type attributes to the appropriate
703/// declarator chunk.
704///
705/// These are attributes like the following:
706/// int f ATTR;
707/// int (f ATTR)();
708/// but not necessarily this:
709/// int f() ATTR;
710///
711/// `Attrs` is the attribute list containing the declaration (either of the
712/// declarator or the declaration).
713static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
714 QualType &declSpecType,
715 CUDAFunctionTarget CFT) {
716 // The called functions in this loop actually remove things from the current
717 // list, so iterating over the existing list isn't possible. Instead, make a
718 // non-owning copy and iterate over that.
719 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
720 for (ParsedAttr &attr : AttrsCopy) {
721 // Do not distribute [[]] attributes. They have strict rules for what
722 // they appertain to.
723 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute())
724 continue;
725
726 switch (attr.getKind()) {
729 break;
730
732 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT);
733 break;
734
736 // Microsoft type attributes cannot go after the declarator-id.
737 continue;
738
740 // Nullability specifiers cannot go after the declarator-id.
741
742 // Objective-C __kindof does not get distributed.
743 case ParsedAttr::AT_ObjCKindOf:
744 continue;
745
746 default:
747 break;
748 }
749 }
750}
751
752/// Add a synthetic '()' to a block-literal declarator if it is
753/// required, given the return type.
754static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
755 QualType declSpecType) {
756 Declarator &declarator = state.getDeclarator();
757
758 // First, check whether the declarator would produce a function,
759 // i.e. whether the innermost semantic chunk is a function.
760 if (declarator.isFunctionDeclarator()) {
761 // If so, make that declarator a prototyped declarator.
762 declarator.getFunctionTypeInfo().hasPrototype = true;
763 return;
764 }
765
766 // If there are any type objects, the type as written won't name a
767 // function, regardless of the decl spec type. This is because a
768 // block signature declarator is always an abstract-declarator, and
769 // abstract-declarators can't just be parentheses chunks. Therefore
770 // we need to build a function chunk unless there are no type
771 // objects and the decl spec type is a function.
772 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
773 return;
774
775 // Note that there *are* cases with invalid declarators where
776 // declarators consist solely of parentheses. In general, these
777 // occur only in failed efforts to make function declarators, so
778 // faking up the function chunk is still the right thing to do.
779
780 // Otherwise, we need to fake up a function declarator.
781 SourceLocation loc = declarator.getBeginLoc();
782
783 // ...and *prepend* it to the declarator.
784 SourceLocation NoLoc;
786 /*HasProto=*/true,
787 /*IsAmbiguous=*/false,
788 /*LParenLoc=*/NoLoc,
789 /*ArgInfo=*/nullptr,
790 /*NumParams=*/0,
791 /*EllipsisLoc=*/NoLoc,
792 /*RParenLoc=*/NoLoc,
793 /*RefQualifierIsLvalueRef=*/true,
794 /*RefQualifierLoc=*/NoLoc,
795 /*MutableLoc=*/NoLoc, EST_None,
796 /*ESpecRange=*/SourceRange(),
797 /*Exceptions=*/nullptr,
798 /*ExceptionRanges=*/nullptr,
799 /*NumExceptions=*/0,
800 /*NoexceptExpr=*/nullptr,
801 /*ExceptionSpecTokens=*/nullptr,
802 /*DeclsInPrototype=*/{}, loc, loc, declarator));
803
804 // For consistency, make sure the state still has us as processing
805 // the decl spec.
806 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
807 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
808}
809
811 unsigned &TypeQuals,
812 QualType TypeSoFar,
813 unsigned RemoveTQs,
814 unsigned DiagID) {
815 // If this occurs outside a template instantiation, warn the user about
816 // it; they probably didn't mean to specify a redundant qualifier.
817 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
818 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
821 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
822 if (!(RemoveTQs & Qual.first))
823 continue;
824
825 if (!S.inTemplateInstantiation()) {
826 if (TypeQuals & Qual.first)
827 S.Diag(Qual.second, DiagID)
828 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
829 << FixItHint::CreateRemoval(Qual.second);
830 }
831
832 TypeQuals &= ~Qual.first;
833 }
834}
835
836/// Return true if this is omitted block return type. Also check type
837/// attributes and type qualifiers when returning true.
838static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
839 QualType Result) {
840 if (!isOmittedBlockReturnType(declarator))
841 return false;
842
843 // Warn if we see type attributes for omitted return type on a block literal.
845 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
846 if (AL.isInvalid() || !AL.isTypeAttr())
847 continue;
848 S.Diag(AL.getLoc(),
849 diag::warn_block_literal_attributes_on_omitted_return_type)
850 << AL;
851 ToBeRemoved.push_back(&AL);
852 }
853 // Remove bad attributes from the list.
854 for (ParsedAttr *AL : ToBeRemoved)
855 declarator.getMutableDeclSpec().getAttributes().remove(AL);
856
857 // Warn if we see type qualifiers for omitted return type on a block literal.
858 const DeclSpec &DS = declarator.getDeclSpec();
859 unsigned TypeQuals = DS.getTypeQualifiers();
860 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
861 diag::warn_block_literal_qualifiers_on_omitted_return_type);
863
864 return true;
865}
866
867static OpenCLAccessAttr::Spelling
869 for (const ParsedAttr &AL : Attrs)
870 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
871 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
872 return OpenCLAccessAttr::Keyword_read_only;
873}
874
877 switch (SwitchTST) {
878#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
879 case TST_##Trait: \
880 return UnaryTransformType::Enum;
881#include "clang/Basic/TransformTypeTraits.def"
882 default:
883 llvm_unreachable("attempted to parse a non-unary transform builtin");
884 }
885}
886
887/// Convert the specified declspec to the appropriate type
888/// object.
889/// \param state Specifies the declarator containing the declaration specifier
890/// to be converted, along with other associated processing state.
891/// \returns The type described by the declaration specifiers. This function
892/// never returns null.
893static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
894 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
895 // checking.
896
897 Sema &S = state.getSema();
898 Declarator &declarator = state.getDeclarator();
899 DeclSpec &DS = declarator.getMutableDeclSpec();
900 SourceLocation DeclLoc = declarator.getIdentifierLoc();
901 if (DeclLoc.isInvalid())
902 DeclLoc = DS.getBeginLoc();
903
904 ASTContext &Context = S.Context;
905
906 QualType Result;
907 switch (DS.getTypeSpecType()) {
909 Result = Context.VoidTy;
910 break;
912 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
913 Result = Context.CharTy;
914 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
915 Result = Context.SignedCharTy;
916 else {
917 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
918 "Unknown TSS value");
919 Result = Context.UnsignedCharTy;
920 }
921 break;
923 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
924 Result = Context.WCharTy;
925 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
926 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
928 Context.getPrintingPolicy());
929 Result = Context.getSignedWCharType();
930 } else {
931 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
932 "Unknown TSS value");
933 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
935 Context.getPrintingPolicy());
936 Result = Context.getUnsignedWCharType();
937 }
938 break;
940 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
941 "Unknown TSS value");
942 Result = Context.Char8Ty;
943 break;
945 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
946 "Unknown TSS value");
947 Result = Context.Char16Ty;
948 break;
950 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
951 "Unknown TSS value");
952 Result = Context.Char32Ty;
953 break;
955 // If this is a missing declspec in a block literal return context, then it
956 // is inferred from the return statements inside the block.
957 // The declspec is always missing in a lambda expr context; it is either
958 // specified with a trailing return type or inferred.
959 if (S.getLangOpts().CPlusPlus14 &&
960 declarator.getContext() == DeclaratorContext::LambdaExpr) {
961 // In C++1y, a lambda's implicit return type is 'auto'.
962 Result = Context.getAutoDeductType();
963 break;
964 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
965 checkOmittedBlockReturnType(S, declarator,
966 Context.DependentTy)) {
967 Result = Context.DependentTy;
968 break;
969 }
970
971 // Unspecified typespec defaults to int in C90. However, the C90 grammar
972 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
973 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
974 // Note that the one exception to this is function definitions, which are
975 // allowed to be completely missing a declspec. This is handled in the
976 // parser already though by it pretending to have seen an 'int' in this
977 // case.
979 S.Diag(DeclLoc, diag::warn_missing_type_specifier)
980 << DS.getSourceRange()
982 } else if (!DS.hasTypeSpecifier()) {
983 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
984 // "At least one type specifier shall be given in the declaration
985 // specifiers in each declaration, and in the specifier-qualifier list in
986 // each struct declaration and type name."
987 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
988 S.Diag(DeclLoc, diag::err_missing_type_specifier)
989 << DS.getSourceRange();
990
991 // When this occurs, often something is very broken with the value
992 // being declared, poison it as invalid so we don't get chains of
993 // errors.
994 declarator.setInvalidType(true);
995 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
996 DS.isTypeSpecPipe()) {
997 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
998 << DS.getSourceRange();
999 declarator.setInvalidType(true);
1000 } else {
1001 assert(S.getLangOpts().isImplicitIntAllowed() &&
1002 "implicit int is disabled?");
1003 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1004 << DS.getSourceRange()
1006 }
1007 }
1008
1009 [[fallthrough]];
1010 case DeclSpec::TST_int: {
1011 if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1012 switch (DS.getTypeSpecWidth()) {
1013 case TypeSpecifierWidth::Unspecified:
1014 Result = Context.IntTy;
1015 break;
1016 case TypeSpecifierWidth::Short:
1017 Result = Context.ShortTy;
1018 break;
1019 case TypeSpecifierWidth::Long:
1020 Result = Context.LongTy;
1021 break;
1022 case TypeSpecifierWidth::LongLong:
1023 Result = Context.LongLongTy;
1024
1025 // 'long long' is a C99 or C++11 feature.
1026 if (!S.getLangOpts().C99) {
1027 if (S.getLangOpts().CPlusPlus)
1029 S.getLangOpts().CPlusPlus11 ?
1030 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1031 else
1032 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1033 }
1034 break;
1035 }
1036 } else {
1037 switch (DS.getTypeSpecWidth()) {
1038 case TypeSpecifierWidth::Unspecified:
1039 Result = Context.UnsignedIntTy;
1040 break;
1041 case TypeSpecifierWidth::Short:
1042 Result = Context.UnsignedShortTy;
1043 break;
1044 case TypeSpecifierWidth::Long:
1045 Result = Context.UnsignedLongTy;
1046 break;
1047 case TypeSpecifierWidth::LongLong:
1048 Result = Context.UnsignedLongLongTy;
1049
1050 // 'long long' is a C99 or C++11 feature.
1051 if (!S.getLangOpts().C99) {
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 }
1062 break;
1063 }
1064 case DeclSpec::TST_bitint: {
1066 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1067 Result =
1068 S.BuildBitIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1069 DS.getRepAsExpr(), DS.getBeginLoc());
1070 if (Result.isNull()) {
1071 Result = Context.IntTy;
1072 declarator.setInvalidType(true);
1073 }
1074 break;
1075 }
1076 case DeclSpec::TST_accum: {
1077 switch (DS.getTypeSpecWidth()) {
1078 case TypeSpecifierWidth::Short:
1079 Result = Context.ShortAccumTy;
1080 break;
1081 case TypeSpecifierWidth::Unspecified:
1082 Result = Context.AccumTy;
1083 break;
1084 case TypeSpecifierWidth::Long:
1085 Result = Context.LongAccumTy;
1086 break;
1087 case TypeSpecifierWidth::LongLong:
1088 llvm_unreachable("Unable to specify long long as _Accum width");
1089 }
1090
1091 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1092 Result = Context.getCorrespondingUnsignedType(Result);
1093
1094 if (DS.isTypeSpecSat())
1095 Result = Context.getCorrespondingSaturatedType(Result);
1096
1097 break;
1098 }
1099 case DeclSpec::TST_fract: {
1100 switch (DS.getTypeSpecWidth()) {
1101 case TypeSpecifierWidth::Short:
1102 Result = Context.ShortFractTy;
1103 break;
1104 case TypeSpecifierWidth::Unspecified:
1105 Result = Context.FractTy;
1106 break;
1107 case TypeSpecifierWidth::Long:
1108 Result = Context.LongFractTy;
1109 break;
1110 case TypeSpecifierWidth::LongLong:
1111 llvm_unreachable("Unable to specify long long as _Fract width");
1112 }
1113
1114 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1115 Result = Context.getCorrespondingUnsignedType(Result);
1116
1117 if (DS.isTypeSpecSat())
1118 Result = Context.getCorrespondingSaturatedType(Result);
1119
1120 break;
1121 }
1123 if (!S.Context.getTargetInfo().hasInt128Type() &&
1124 !(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice ||
1125 (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice)))
1126 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1127 << "__int128";
1128 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1129 Result = Context.UnsignedInt128Ty;
1130 else
1131 Result = Context.Int128Ty;
1132 break;
1134 // CUDA host and device may have different _Float16 support, therefore
1135 // do not diagnose _Float16 usage to avoid false alarm.
1136 // ToDo: more precise diagnostics for CUDA.
1137 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1138 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1139 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1140 << "_Float16";
1141 Result = Context.Float16Ty;
1142 break;
1143 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1146 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) &&
1147 !S.getLangOpts().SYCLIsDevice)
1148 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16";
1149 Result = Context.BFloat16Ty;
1150 break;
1151 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1153 if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1154 Result = Context.LongDoubleTy;
1155 else
1156 Result = Context.DoubleTy;
1157 if (S.getLangOpts().OpenCL) {
1158 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1159 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1160 << 0 << Result
1162 ? "cl_khr_fp64 and __opencl_c_fp64"
1163 : "cl_khr_fp64");
1164 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1165 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1166 }
1167 break;
1170 !S.getLangOpts().SYCLIsDevice && !S.getLangOpts().CUDAIsDevice &&
1171 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1172 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1173 << "__float128";
1174 Result = Context.Float128Ty;
1175 break;
1177 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1178 !S.getLangOpts().SYCLIsDevice &&
1179 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1180 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1181 Result = Context.Ibm128Ty;
1182 break;
1183 case DeclSpec::TST_bool:
1184 Result = Context.BoolTy; // _Bool or bool
1185 break;
1186 case DeclSpec::TST_decimal32: // _Decimal32
1187 case DeclSpec::TST_decimal64: // _Decimal64
1188 case DeclSpec::TST_decimal128: // _Decimal128
1189 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1190 Result = Context.IntTy;
1191 declarator.setInvalidType(true);
1192 break;
1194 case DeclSpec::TST_enum:
1198 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1199 if (!D) {
1200 // This can happen in C++ with ambiguous lookups.
1201 Result = Context.IntTy;
1202 declarator.setInvalidType(true);
1203 break;
1204 }
1205
1206 // If the type is deprecated or unavailable, diagnose it.
1208
1209 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1210 DS.getTypeSpecComplex() == 0 &&
1211 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1212 "No qualifiers on tag names!");
1213
1214 // TypeQuals handled by caller.
1215 Result = Context.getTypeDeclType(D);
1216
1217 // In both C and C++, make an ElaboratedType.
1218 ElaboratedTypeKeyword Keyword
1219 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1220 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1221 DS.isTypeSpecOwned() ? D : nullptr);
1222 break;
1223 }
1225 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1226 DS.getTypeSpecComplex() == 0 &&
1227 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1228 "Can't handle qualifiers on typedef names yet!");
1229 Result = S.GetTypeFromParser(DS.getRepAsType());
1230 if (Result.isNull()) {
1231 declarator.setInvalidType(true);
1232 }
1233
1234 // TypeQuals handled by caller.
1235 break;
1236 }
1239 // FIXME: Preserve type source info.
1240 Result = S.GetTypeFromParser(DS.getRepAsType());
1241 assert(!Result.isNull() && "Didn't get a type for typeof?");
1242 if (!Result->isDependentType())
1243 if (const TagType *TT = Result->getAs<TagType>())
1244 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1245 // TypeQuals handled by caller.
1246 Result = Context.getTypeOfType(
1248 ? TypeOfKind::Unqualified
1249 : TypeOfKind::Qualified);
1250 break;
1253 Expr *E = DS.getRepAsExpr();
1254 assert(E && "Didn't get an expression for typeof?");
1255 // TypeQuals handled by caller.
1256 Result = S.BuildTypeofExprType(E, DS.getTypeSpecType() ==
1258 ? TypeOfKind::Unqualified
1259 : TypeOfKind::Qualified);
1260 if (Result.isNull()) {
1261 Result = Context.IntTy;
1262 declarator.setInvalidType(true);
1263 }
1264 break;
1265 }
1267 Expr *E = DS.getRepAsExpr();
1268 assert(E && "Didn't get an expression for decltype?");
1269 // TypeQuals handled by caller.
1270 Result = S.BuildDecltypeType(E);
1271 if (Result.isNull()) {
1272 Result = Context.IntTy;
1273 declarator.setInvalidType(true);
1274 }
1275 break;
1276 }
1278 Expr *E = DS.getPackIndexingExpr();
1279 assert(E && "Didn't get an expression for pack indexing");
1280 QualType Pattern = S.GetTypeFromParser(DS.getRepAsType());
1281 Result = S.BuildPackIndexingType(Pattern, E, DS.getBeginLoc(),
1282 DS.getEllipsisLoc());
1283 if (Result.isNull()) {
1284 declarator.setInvalidType(true);
1285 Result = Context.IntTy;
1286 }
1287 break;
1288 }
1289
1290#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1291#include "clang/Basic/TransformTypeTraits.def"
1292 Result = S.GetTypeFromParser(DS.getRepAsType());
1293 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1294 Result = S.BuildUnaryTransformType(
1296 DS.getTypeSpecTypeLoc());
1297 if (Result.isNull()) {
1298 Result = Context.IntTy;
1299 declarator.setInvalidType(true);
1300 }
1301 break;
1302
1303 case DeclSpec::TST_auto:
1305 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1306 ? AutoTypeKeyword::DecltypeAuto
1307 : AutoTypeKeyword::Auto;
1308
1309 ConceptDecl *TypeConstraintConcept = nullptr;
1311 if (DS.isConstrainedAuto()) {
1312 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1313 TypeConstraintConcept =
1314 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1315 TemplateArgumentListInfo TemplateArgsInfo;
1316 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1317 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1318 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1319 TemplateId->NumArgs);
1320 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1321 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1322 TemplateArgs.push_back(ArgLoc.getArgument());
1323 } else {
1324 declarator.setInvalidType(true);
1325 }
1326 }
1327 Result = S.Context.getAutoType(QualType(), AutoKW,
1328 /*IsDependent*/ false, /*IsPack=*/false,
1329 TypeConstraintConcept, TemplateArgs);
1330 break;
1331 }
1332
1334 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1335 break;
1336
1338 Result = Context.UnknownAnyTy;
1339 break;
1340
1342 Result = S.GetTypeFromParser(DS.getRepAsType());
1343 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1344 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1345 if (Result.isNull()) {
1346 Result = Context.IntTy;
1347 declarator.setInvalidType(true);
1348 }
1349 break;
1350
1351#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1352 case DeclSpec::TST_##ImgType##_t: \
1353 switch (getImageAccess(DS.getAttributes())) { \
1354 case OpenCLAccessAttr::Keyword_write_only: \
1355 Result = Context.Id##WOTy; \
1356 break; \
1357 case OpenCLAccessAttr::Keyword_read_write: \
1358 Result = Context.Id##RWTy; \
1359 break; \
1360 case OpenCLAccessAttr::Keyword_read_only: \
1361 Result = Context.Id##ROTy; \
1362 break; \
1363 case OpenCLAccessAttr::SpellingNotCalculated: \
1364 llvm_unreachable("Spelling not yet calculated"); \
1365 } \
1366 break;
1367#include "clang/Basic/OpenCLImageTypes.def"
1368
1369#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1370 case DeclSpec::TST_##Name: \
1371 Result = Context.SingletonId; \
1372 break;
1373#include "clang/Basic/HLSLIntangibleTypes.def"
1374
1376 Result = Context.IntTy;
1377 declarator.setInvalidType(true);
1378 break;
1379 }
1380
1381 // FIXME: we want resulting declarations to be marked invalid, but claiming
1382 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1383 // a null type.
1384 if (Result->containsErrors())
1385 declarator.setInvalidType();
1386
1387 if (S.getLangOpts().OpenCL) {
1388 const auto &OpenCLOptions = S.getOpenCLOptions();
1389 bool IsOpenCLC30Compatible =
1391 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1392 // support.
1393 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1394 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1395 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1396 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1397 // only when the optional feature is supported
1398 if ((Result->isImageType() || Result->isSamplerT()) &&
1399 (IsOpenCLC30Compatible &&
1400 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1401 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1402 << 0 << Result << "__opencl_c_images";
1403 declarator.setInvalidType();
1404 } else if (Result->isOCLImage3dWOType() &&
1405 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1406 S.getLangOpts())) {
1407 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1408 << 0 << Result
1409 << (IsOpenCLC30Compatible
1410 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1411 : "cl_khr_3d_image_writes");
1412 declarator.setInvalidType();
1413 }
1414 }
1415
1416 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1418
1419 // Only fixed point types can be saturated
1420 if (DS.isTypeSpecSat() && !IsFixedPointType)
1421 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1423 Context.getPrintingPolicy());
1424
1425 // Handle complex types.
1427 if (S.getLangOpts().Freestanding)
1428 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1429 Result = Context.getComplexType(Result);
1430 } else if (DS.isTypeAltiVecVector()) {
1431 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1432 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1433 VectorKind VecKind = VectorKind::AltiVecVector;
1434 if (DS.isTypeAltiVecPixel())
1435 VecKind = VectorKind::AltiVecPixel;
1436 else if (DS.isTypeAltiVecBool())
1437 VecKind = VectorKind::AltiVecBool;
1438 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1439 }
1440
1441 // _Imaginary was a feature of C99 through C23 but was never supported in
1442 // Clang. The feature was removed in C2y, but we retain the unsupported
1443 // diagnostic for an improved user experience.
1445 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1446
1447 // Before we process any type attributes, synthesize a block literal
1448 // function declarator if necessary.
1449 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1450 maybeSynthesizeBlockSignature(state, Result);
1451
1452 // Apply any type attributes from the decl spec. This may cause the
1453 // list of type attributes to be temporarily saved while the type
1454 // attributes are pushed around.
1455 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1456 if (!DS.isTypeSpecPipe()) {
1457 // We also apply declaration attributes that "slide" to the decl spec.
1458 // Ordering can be important for attributes. The decalaration attributes
1459 // come syntactically before the decl spec attributes, so we process them
1460 // in that order.
1461 ParsedAttributesView SlidingAttrs;
1462 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1463 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1464 SlidingAttrs.addAtEnd(&AL);
1465
1466 // For standard syntax attributes, which would normally appertain to the
1467 // declaration here, suggest moving them to the type instead. But only
1468 // do this for our own vendor attributes; moving other vendors'
1469 // attributes might hurt portability.
1470 // There's one special case that we need to deal with here: The
1471 // `MatrixType` attribute may only be used in a typedef declaration. If
1472 // it's being used anywhere else, don't output the warning as
1473 // ProcessDeclAttributes() will output an error anyway.
1474 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1475 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1477 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1478 << AL;
1479 }
1480 }
1481 }
1482 // During this call to processTypeAttrs(),
1483 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1484 // reference to the DeclSpec attributes, rather than the declaration
1485 // attributes. However, this doesn't matter, as getCurrentAttributes()
1486 // is only called when distributing attributes from one attribute list
1487 // to another. Declaration attributes are always C++11 attributes, and these
1488 // are never distributed.
1489 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1490 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1491 }
1492
1493 // Apply const/volatile/restrict qualifiers to T.
1494 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1495 // Warn about CV qualifiers on function types.
1496 // C99 6.7.3p8:
1497 // If the specification of a function type includes any type qualifiers,
1498 // the behavior is undefined.
1499 // C2y changed this behavior to be implementation-defined. Clang defines
1500 // the behavior in all cases to ignore the qualifier, as in C++.
1501 // C++11 [dcl.fct]p7:
1502 // The effect of a cv-qualifier-seq in a function declarator is not the
1503 // same as adding cv-qualification on top of the function type. In the
1504 // latter case, the cv-qualifiers are ignored.
1505 if (Result->isFunctionType()) {
1506 unsigned DiagId = diag::warn_typecheck_function_qualifiers_ignored;
1507 if (!S.getLangOpts().CPlusPlus && !S.getLangOpts().C2y)
1508 DiagId = diag::ext_typecheck_function_qualifiers_unspecified;
1510 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1511 DiagId);
1512 // No diagnostic for 'restrict' or '_Atomic' applied to a
1513 // function type; we'll diagnose those later, in BuildQualifiedType.
1514 }
1515
1516 // C++11 [dcl.ref]p1:
1517 // Cv-qualified references are ill-formed except when the
1518 // cv-qualifiers are introduced through the use of a typedef-name
1519 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1520 //
1521 // There don't appear to be any other contexts in which a cv-qualified
1522 // reference type could be formed, so the 'ill-formed' clause here appears
1523 // to never happen.
1524 if (TypeQuals && Result->isReferenceType()) {
1526 S, DS, TypeQuals, Result,
1528 diag::warn_typecheck_reference_qualifiers);
1529 }
1530
1531 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1532 // than once in the same specifier-list or qualifier-list, either directly
1533 // or via one or more typedefs."
1534 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1535 && TypeQuals & Result.getCVRQualifiers()) {
1536 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1537 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1538 << "const";
1539 }
1540
1541 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1542 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1543 << "volatile";
1544 }
1545
1546 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1547 // produce a warning in this case.
1548 }
1549
1550 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1551
1552 // If adding qualifiers fails, just use the unqualified type.
1553 if (Qualified.isNull())
1554 declarator.setInvalidType(true);
1555 else
1556 Result = Qualified;
1557 }
1558
1559 if (S.getLangOpts().HLSL)
1560 Result = S.HLSL().ProcessResourceTypeAttributes(Result);
1561
1562 assert(!Result.isNull() && "This function should not return a null type");
1563 return Result;
1564}
1565
1566static std::string getPrintableNameForEntity(DeclarationName Entity) {
1567 if (Entity)
1568 return Entity.getAsString();
1569
1570 return "type name";
1571}
1572
1574 if (T->isDependentType())
1575 return true;
1576
1577 const auto *AT = dyn_cast<AutoType>(T);
1578 return AT && AT->isGNUAutoType();
1579}
1580
1582 Qualifiers Qs, const DeclSpec *DS) {
1583 if (T.isNull())
1584 return QualType();
1585
1586 // Ignore any attempt to form a cv-qualified reference.
1587 if (T->isReferenceType()) {
1588 Qs.removeConst();
1589 Qs.removeVolatile();
1590 }
1591
1592 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1593 // object or incomplete types shall not be restrict-qualified."
1594 if (Qs.hasRestrict()) {
1595 unsigned DiagID = 0;
1596 QualType ProblemTy;
1597
1598 if (T->isAnyPointerType() || T->isReferenceType() ||
1600 QualType EltTy;
1602 EltTy = T;
1603 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1604 EltTy = PTy->getPointeeType();
1605 else
1606 EltTy = T->getPointeeType();
1607
1608 // If we have a pointer or reference, the pointee must have an object
1609 // incomplete type.
1610 if (!EltTy->isIncompleteOrObjectType()) {
1611 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1612 ProblemTy = EltTy;
1613 }
1614 } else if (!isDependentOrGNUAutoType(T)) {
1615 // For an __auto_type variable, we may not have seen the initializer yet
1616 // and so have no idea whether the underlying type is a pointer type or
1617 // not.
1618 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1619 ProblemTy = T;
1620 }
1621
1622 if (DiagID) {
1623 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1624 Qs.removeRestrict();
1625 }
1626 }
1627
1628 return Context.getQualifiedType(T, Qs);
1629}
1630
1632 unsigned CVRAU, const DeclSpec *DS) {
1633 if (T.isNull())
1634 return QualType();
1635
1636 // Ignore any attempt to form a cv-qualified reference.
1637 if (T->isReferenceType())
1638 CVRAU &=
1640
1641 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1642 // TQ_unaligned;
1643 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1644
1645 // C11 6.7.3/5:
1646 // If the same qualifier appears more than once in the same
1647 // specifier-qualifier-list, either directly or via one or more typedefs,
1648 // the behavior is the same as if it appeared only once.
1649 //
1650 // It's not specified what happens when the _Atomic qualifier is applied to
1651 // a type specified with the _Atomic specifier, but we assume that this
1652 // should be treated as if the _Atomic qualifier appeared multiple times.
1653 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1654 // C11 6.7.3/5:
1655 // If other qualifiers appear along with the _Atomic qualifier in a
1656 // specifier-qualifier-list, the resulting type is the so-qualified
1657 // atomic type.
1658 //
1659 // Don't need to worry about array types here, since _Atomic can't be
1660 // applied to such types.
1661 SplitQualType Split = T.getSplitUnqualifiedType();
1662 T = BuildAtomicType(QualType(Split.Ty, 0),
1663 DS ? DS->getAtomicSpecLoc() : Loc);
1664 if (T.isNull())
1665 return T;
1666 Split.Quals.addCVRQualifiers(CVR);
1667 return BuildQualifiedType(T, Loc, Split.Quals);
1668 }
1669
1672 return BuildQualifiedType(T, Loc, Q, DS);
1673}
1674
1676 return Context.getParenType(T);
1677}
1678
1679/// Given that we're building a pointer or reference to the given
1681 SourceLocation loc,
1682 bool isReference) {
1683 // Bail out if retention is unrequired or already specified.
1684 if (!type->isObjCLifetimeType() ||
1685 type.getObjCLifetime() != Qualifiers::OCL_None)
1686 return type;
1687
1689
1690 // If the object type is const-qualified, we can safely use
1691 // __unsafe_unretained. This is safe (because there are no read
1692 // barriers), and it'll be safe to coerce anything but __weak* to
1693 // the resulting type.
1694 if (type.isConstQualified()) {
1695 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1696
1697 // Otherwise, check whether the static type does not require
1698 // retaining. This currently only triggers for Class (possibly
1699 // protocol-qualifed, and arrays thereof).
1700 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1701 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1702
1703 // If we are in an unevaluated context, like sizeof, skip adding a
1704 // qualification.
1705 } else if (S.isUnevaluatedContext()) {
1706 return type;
1707
1708 // If that failed, give an error and recover using __strong. __strong
1709 // is the option most likely to prevent spurious second-order diagnostics,
1710 // like when binding a reference to a field.
1711 } else {
1712 // These types can show up in private ivars in system headers, so
1713 // we need this to not be an error in those cases. Instead we
1714 // want to delay.
1718 diag::err_arc_indirect_no_ownership, type, isReference));
1719 } else {
1720 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1721 }
1722 implicitLifetime = Qualifiers::OCL_Strong;
1723 }
1724 assert(implicitLifetime && "didn't infer any lifetime!");
1725
1726 Qualifiers qs;
1727 qs.addObjCLifetime(implicitLifetime);
1728 return S.Context.getQualifiedType(type, qs);
1729}
1730
1731static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1732 std::string Quals = FnTy->getMethodQuals().getAsString();
1733
1734 switch (FnTy->getRefQualifier()) {
1735 case RQ_None:
1736 break;
1737
1738 case RQ_LValue:
1739 if (!Quals.empty())
1740 Quals += ' ';
1741 Quals += '&';
1742 break;
1743
1744 case RQ_RValue:
1745 if (!Quals.empty())
1746 Quals += ' ';
1747 Quals += "&&";
1748 break;
1749 }
1750
1751 return Quals;
1752}
1753
1754namespace {
1755/// Kinds of declarator that cannot contain a qualified function type.
1756///
1757/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1758/// a function type with a cv-qualifier or a ref-qualifier can only appear
1759/// at the topmost level of a type.
1760///
1761/// Parens and member pointers are permitted. We don't diagnose array and
1762/// function declarators, because they don't allow function types at all.
1763///
1764/// The values of this enum are used in diagnostics.
1765enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1766} // end anonymous namespace
1767
1768/// Check whether the type T is a qualified function type, and if it is,
1769/// diagnose that it cannot be contained within the given kind of declarator.
1771 QualifiedFunctionKind QFK) {
1772 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1773 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1774 if (!FPT ||
1775 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1776 return false;
1777
1778 S.Diag(Loc, diag::err_compound_qualified_function_type)
1779 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1781 return true;
1782}
1783
1785 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1786 if (!FPT ||
1787 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1788 return false;
1789
1790 Diag(Loc, diag::err_qualified_function_typeid)
1792 return true;
1793}
1794
1795// Helper to deduce addr space of a pointee type in OpenCL mode.
1797 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
1798 !PointeeType->isSamplerT() &&
1799 !PointeeType.hasAddressSpace())
1800 PointeeType = S.getASTContext().getAddrSpaceQualType(
1802 return PointeeType;
1803}
1804
1807 if (T->isReferenceType()) {
1808 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1809 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1810 << getPrintableNameForEntity(Entity) << T;
1811 return QualType();
1812 }
1813
1814 if (T->isFunctionType() && getLangOpts().OpenCL &&
1815 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1816 getLangOpts())) {
1817 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
1818 return QualType();
1819 }
1820
1821 if (getLangOpts().HLSL && Loc.isValid()) {
1822 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
1823 return QualType();
1824 }
1825
1826 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1827 return QualType();
1828
1829 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1830
1831 // In ARC, it is forbidden to build pointers to unqualified pointers.
1832 if (getLangOpts().ObjCAutoRefCount)
1833 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1834
1835 if (getLangOpts().OpenCL)
1837
1838 // In WebAssembly, pointers to reference types and pointers to tables are
1839 // illegal.
1840 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
1841 if (T.isWebAssemblyReferenceType()) {
1842 Diag(Loc, diag::err_wasm_reference_pr) << 0;
1843 return QualType();
1844 }
1845
1846 // We need to desugar the type here in case T is a ParenType.
1848 Diag(Loc, diag::err_wasm_table_pr) << 0;
1849 return QualType();
1850 }
1851 }
1852
1853 // Build the pointer type.
1854 return Context.getPointerType(T);
1855}
1856
1859 DeclarationName Entity) {
1861 "Unresolved overloaded function type");
1862
1863 // C++0x [dcl.ref]p6:
1864 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1865 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1866 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1867 // the type "lvalue reference to T", while an attempt to create the type
1868 // "rvalue reference to cv TR" creates the type TR.
1869 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1870
1871 // C++ [dcl.ref]p4: There shall be no references to references.
1872 //
1873 // According to C++ DR 106, references to references are only
1874 // diagnosed when they are written directly (e.g., "int & &"),
1875 // but not when they happen via a typedef:
1876 //
1877 // typedef int& intref;
1878 // typedef intref& intref2;
1879 //
1880 // Parser::ParseDeclaratorInternal diagnoses the case where
1881 // references are written directly; here, we handle the
1882 // collapsing of references-to-references as described in C++0x.
1883 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1884
1885 // C++ [dcl.ref]p1:
1886 // A declarator that specifies the type "reference to cv void"
1887 // is ill-formed.
1888 if (T->isVoidType()) {
1889 Diag(Loc, diag::err_reference_to_void);
1890 return QualType();
1891 }
1892
1893 if (getLangOpts().HLSL && Loc.isValid()) {
1894 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
1895 return QualType();
1896 }
1897
1898 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1899 return QualType();
1900
1901 if (T->isFunctionType() && getLangOpts().OpenCL &&
1902 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1903 getLangOpts())) {
1904 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
1905 return QualType();
1906 }
1907
1908 // In ARC, it is forbidden to build references to unqualified pointers.
1909 if (getLangOpts().ObjCAutoRefCount)
1910 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1911
1912 if (getLangOpts().OpenCL)
1914
1915 // In WebAssembly, references to reference types and tables are illegal.
1916 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
1917 T.isWebAssemblyReferenceType()) {
1918 Diag(Loc, diag::err_wasm_reference_pr) << 1;
1919 return QualType();
1920 }
1921 if (T->isWebAssemblyTableType()) {
1922 Diag(Loc, diag::err_wasm_table_pr) << 1;
1923 return QualType();
1924 }
1925
1926 // Handle restrict on references.
1927 if (LValueRef)
1928 return Context.getLValueReferenceType(T, SpelledAsLValue);
1930}
1931
1933 return Context.getReadPipeType(T);
1934}
1935
1937 return Context.getWritePipeType(T);
1938}
1939
1940QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
1942 if (BitWidth->isInstantiationDependent())
1943 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
1944
1945 llvm::APSInt Bits(32);
1946 ExprResult ICE =
1947 VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
1948
1949 if (ICE.isInvalid())
1950 return QualType();
1951
1952 size_t NumBits = Bits.getZExtValue();
1953 if (!IsUnsigned && NumBits < 2) {
1954 Diag(Loc, diag::err_bit_int_bad_size) << 0;
1955 return QualType();
1956 }
1957
1958 if (IsUnsigned && NumBits < 1) {
1959 Diag(Loc, diag::err_bit_int_bad_size) << 1;
1960 return QualType();
1961 }
1962
1963 const TargetInfo &TI = getASTContext().getTargetInfo();
1964 if (NumBits > TI.getMaxBitIntWidth()) {
1965 Diag(Loc, diag::err_bit_int_max_size)
1966 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
1967 return QualType();
1968 }
1969
1970 return Context.getBitIntType(IsUnsigned, NumBits);
1971}
1972
1973/// Check whether the specified array bound can be evaluated using the relevant
1974/// language rules. If so, returns the possibly-converted expression and sets
1975/// SizeVal to the size. If not, but the expression might be a VLA bound,
1976/// returns ExprResult(). Otherwise, produces a diagnostic and returns
1977/// ExprError().
1978static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
1979 llvm::APSInt &SizeVal, unsigned VLADiag,
1980 bool VLAIsError) {
1981 if (S.getLangOpts().CPlusPlus14 &&
1982 (VLAIsError ||
1983 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
1984 // C++14 [dcl.array]p1:
1985 // The constant-expression shall be a converted constant expression of
1986 // type std::size_t.
1987 //
1988 // Don't apply this rule if we might be forming a VLA: in that case, we
1989 // allow non-constant expressions and constant-folding. We only need to use
1990 // the converted constant expression rules (to properly convert the source)
1991 // when the source expression is of class type.
1993 ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
1994 }
1995
1996 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1997 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1998 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1999 public:
2000 unsigned VLADiag;
2001 bool VLAIsError;
2002 bool IsVLA = false;
2003
2004 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2005 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2006
2007 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2008 QualType T) override {
2009 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2010 }
2011
2012 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2013 SourceLocation Loc) override {
2014 IsVLA = !VLAIsError;
2015 return S.Diag(Loc, VLADiag);
2016 }
2017
2018 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2019 SourceLocation Loc) override {
2020 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2021 }
2022 } Diagnoser(VLADiag, VLAIsError);
2023
2024 ExprResult R =
2025 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2026 if (Diagnoser.IsVLA)
2027 return ExprResult();
2028 return R;
2029}
2030
2032 EltTy = Context.getBaseElementType(EltTy);
2033 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2034 EltTy->isUndeducedType())
2035 return true;
2036
2037 CharUnits Size = Context.getTypeSizeInChars(EltTy);
2038 CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2039
2040 if (Size.isMultipleOf(Alignment))
2041 return true;
2042
2043 Diag(Loc, diag::err_array_element_alignment)
2044 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2045 return false;
2046}
2047
2049 Expr *ArraySize, unsigned Quals,
2050 SourceRange Brackets, DeclarationName Entity) {
2051
2052 SourceLocation Loc = Brackets.getBegin();
2053 if (getLangOpts().CPlusPlus) {
2054 // C++ [dcl.array]p1:
2055 // T is called the array element type; this type shall not be a reference
2056 // type, the (possibly cv-qualified) type void, a function type or an
2057 // abstract class type.
2058 //
2059 // C++ [dcl.array]p3:
2060 // When several "array of" specifications are adjacent, [...] only the
2061 // first of the constant expressions that specify the bounds of the arrays
2062 // may be omitted.
2063 //
2064 // Note: function types are handled in the common path with C.
2065 if (T->isReferenceType()) {
2066 Diag(Loc, diag::err_illegal_decl_array_of_references)
2067 << getPrintableNameForEntity(Entity) << T;
2068 return QualType();
2069 }
2070
2071 if (T->isVoidType() || T->isIncompleteArrayType()) {
2072 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2073 return QualType();
2074 }
2075
2076 if (RequireNonAbstractType(Brackets.getBegin(), T,
2077 diag::err_array_of_abstract_type))
2078 return QualType();
2079
2080 // Mentioning a member pointer type for an array type causes us to lock in
2081 // an inheritance model, even if it's inside an unused typedef.
2083 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2084 if (!MPTy->getClass()->isDependentType())
2085 (void)isCompleteType(Loc, T);
2086
2087 } else {
2088 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2089 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2090 if (!T.isWebAssemblyReferenceType() &&
2092 diag::err_array_incomplete_or_sizeless_type))
2093 return QualType();
2094 }
2095
2096 // Multi-dimensional arrays of WebAssembly references are not allowed.
2097 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2098 const auto *ATy = dyn_cast<ArrayType>(T);
2099 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2100 Diag(Loc, diag::err_wasm_reftype_multidimensional_array);
2101 return QualType();
2102 }
2103 }
2104
2105 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2106 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2107 return QualType();
2108 }
2109
2110 if (T->isFunctionType()) {
2111 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2112 << getPrintableNameForEntity(Entity) << T;
2113 return QualType();
2114 }
2115
2116 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2117 // If the element type is a struct or union that contains a variadic
2118 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2119 if (EltTy->getDecl()->hasFlexibleArrayMember())
2120 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2121 } else if (T->isObjCObjectType()) {
2122 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2123 return QualType();
2124 }
2125
2127 return QualType();
2128
2129 // Do placeholder conversions on the array size expression.
2130 if (ArraySize && ArraySize->hasPlaceholderType()) {
2132 if (Result.isInvalid()) return QualType();
2133 ArraySize = Result.get();
2134 }
2135
2136 // Do lvalue-to-rvalue conversions on the array size expression.
2137 if (ArraySize && !ArraySize->isPRValue()) {
2139 if (Result.isInvalid())
2140 return QualType();
2141
2142 ArraySize = Result.get();
2143 }
2144
2145 // C99 6.7.5.2p1: The size expression shall have integer type.
2146 // C++11 allows contextual conversions to such types.
2147 if (!getLangOpts().CPlusPlus11 &&
2148 ArraySize && !ArraySize->isTypeDependent() &&
2150 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2151 << ArraySize->getType() << ArraySize->getSourceRange();
2152 return QualType();
2153 }
2154
2155 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2156 if (!ArraySize)
2157 return false;
2158
2159 // If the array size expression is a conditional expression whose branches
2160 // are both integer constant expressions, one negative and one positive,
2161 // then it's assumed to be like an old-style static assertion. e.g.,
2162 // int old_style_assert[expr ? 1 : -1];
2163 // We will accept any integer constant expressions instead of assuming the
2164 // values 1 and -1 are always used.
2165 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2166 ArraySize->IgnoreParenImpCasts())) {
2167 std::optional<llvm::APSInt> LHS =
2168 CondExpr->getLHS()->getIntegerConstantExpr(Context);
2169 std::optional<llvm::APSInt> RHS =
2170 CondExpr->getRHS()->getIntegerConstantExpr(Context);
2171 return LHS && RHS && LHS->isNegative() != RHS->isNegative();
2172 }
2173 return false;
2174 };
2175
2176 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2177 unsigned VLADiag;
2178 bool VLAIsError;
2179 if (getLangOpts().OpenCL) {
2180 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2181 VLADiag = diag::err_opencl_vla;
2182 VLAIsError = true;
2183 } else if (getLangOpts().C99) {
2184 VLADiag = diag::warn_vla_used;
2185 VLAIsError = false;
2186 } else if (isSFINAEContext()) {
2187 VLADiag = diag::err_vla_in_sfinae;
2188 VLAIsError = true;
2189 } else if (getLangOpts().OpenMP && OpenMP().isInOpenMPTaskUntiedContext()) {
2190 VLADiag = diag::err_openmp_vla_in_task_untied;
2191 VLAIsError = true;
2192 } else if (getLangOpts().CPlusPlus) {
2193 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context))
2194 VLADiag = getLangOpts().GNUMode
2195 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2196 : diag::ext_vla_cxx_static_assert;
2197 else
2198 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode
2199 : diag::ext_vla_cxx;
2200 VLAIsError = false;
2201 } else {
2202 VLADiag = diag::ext_vla;
2203 VLAIsError = false;
2204 }
2205
2206 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2207 if (!ArraySize) {
2208 if (ASM == ArraySizeModifier::Star) {
2209 Diag(Loc, VLADiag);
2210 if (VLAIsError)
2211 return QualType();
2212
2213 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2214 } else {
2215 T = Context.getIncompleteArrayType(T, ASM, Quals);
2216 }
2217 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2218 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2219 } else {
2220 ExprResult R =
2221 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2222 if (R.isInvalid())
2223 return QualType();
2224
2225 if (!R.isUsable()) {
2226 // C99: an array with a non-ICE size is a VLA. We accept any expression
2227 // that we can fold to a non-zero positive value as a non-VLA as an
2228 // extension.
2229 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2230 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2231 !T->isConstantSizeType()) {
2232 // C99: an array with an element type that has a non-constant-size is a
2233 // VLA.
2234 // FIXME: Add a note to explain why this isn't a VLA.
2235 Diag(Loc, VLADiag);
2236 if (VLAIsError)
2237 return QualType();
2238 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2239 } else {
2240 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2241 // have a value greater than zero.
2242 // In C++, this follows from narrowing conversions being disallowed.
2243 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2244 if (Entity)
2245 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2246 << getPrintableNameForEntity(Entity)
2247 << ArraySize->getSourceRange();
2248 else
2249 Diag(ArraySize->getBeginLoc(),
2250 diag::err_typecheck_negative_array_size)
2251 << ArraySize->getSourceRange();
2252 return QualType();
2253 }
2254 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2255 // GCC accepts zero sized static arrays. We allow them when
2256 // we're not in a SFINAE context.
2257 Diag(ArraySize->getBeginLoc(),
2258 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2259 : diag::ext_typecheck_zero_array_size)
2260 << 0 << ArraySize->getSourceRange();
2261 }
2262
2263 // Is the array too large?
2264 unsigned ActiveSizeBits =
2268 : ConstVal.getActiveBits();
2269 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2270 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2271 << toString(ConstVal, 10) << ArraySize->getSourceRange();
2272 return QualType();
2273 }
2274
2275 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2276 }
2277 }
2278
2279 if (T->isVariableArrayType()) {
2281 // CUDA device code and some other targets don't support VLAs.
2282 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2284 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2285 << (IsCUDADevice ? llvm::to_underlying(CUDA().CurrentTarget()) : 0);
2286 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2287 // VLAs are supported on this target, but we may need to do delayed
2288 // checking that the VLA is not being used within a coroutine.
2289 FSI->setHasVLA(Loc);
2290 }
2291 }
2292
2293 // If this is not C99, diagnose array size modifiers on non-VLAs.
2294 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2295 (ASM != ArraySizeModifier::Normal || Quals != 0)) {
2296 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2297 : diag::ext_c99_array_usage)
2298 << llvm::to_underlying(ASM);
2299 }
2300
2301 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2302 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2303 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2304 if (getLangOpts().OpenCL) {
2305 const QualType ArrType = Context.getBaseElementType(T);
2306 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2307 ArrType->isSamplerT() || ArrType->isImageType()) {
2308 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2309 return QualType();
2310 }
2311 }
2312
2313 return T;
2314}
2315
2317 const BitIntType *BIT,
2318 bool ForMatrixType = false) {
2319 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2320 unsigned NumBits = BIT->getNumBits();
2321 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8)
2322 return S.Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2323 << ForMatrixType << (NumBits < 8);
2324 return false;
2325}
2326
2328 SourceLocation AttrLoc) {
2329 // The base type must be integer (not Boolean or enumeration) or float, and
2330 // can't already be a vector.
2331 if ((!CurType->isDependentType() &&
2332 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2333 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2334 !CurType->isBitIntType()) ||
2335 CurType->isArrayType()) {
2336 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2337 return QualType();
2338 }
2339
2340 if (const auto *BIT = CurType->getAs<BitIntType>();
2341 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2342 return QualType();
2343
2344 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2345 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2347
2348 std::optional<llvm::APSInt> VecSize =
2350 if (!VecSize) {
2351 Diag(AttrLoc, diag::err_attribute_argument_type)
2352 << "vector_size" << AANT_ArgumentIntegerConstant
2353 << SizeExpr->getSourceRange();
2354 return QualType();
2355 }
2356
2357 if (CurType->isDependentType())
2358 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2360
2361 // vecSize is specified in bytes - convert to bits.
2362 if (!VecSize->isIntN(61)) {
2363 // Bit size will overflow uint64.
2364 Diag(AttrLoc, diag::err_attribute_size_too_large)
2365 << SizeExpr->getSourceRange() << "vector";
2366 return QualType();
2367 }
2368 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2369 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2370
2371 if (VectorSizeBits == 0) {
2372 Diag(AttrLoc, diag::err_attribute_zero_size)
2373 << SizeExpr->getSourceRange() << "vector";
2374 return QualType();
2375 }
2376
2377 if (!TypeSize || VectorSizeBits % TypeSize) {
2378 Diag(AttrLoc, diag::err_attribute_invalid_size)
2379 << SizeExpr->getSourceRange();
2380 return QualType();
2381 }
2382
2383 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2384 Diag(AttrLoc, diag::err_attribute_size_too_large)
2385 << SizeExpr->getSourceRange() << "vector";
2386 return QualType();
2387 }
2388
2389 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2391}
2392
2394 SourceLocation AttrLoc) {
2395 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2396 // in conjunction with complex types (pointers, arrays, functions, etc.).
2397 //
2398 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2399 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2400 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2401 // of bool aren't allowed.
2402 //
2403 // We explicitly allow bool elements in ext_vector_type for C/C++.
2404 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2405 if ((!T->isDependentType() && !T->isIntegerType() &&
2406 !T->isRealFloatingType()) ||
2407 (IsNoBoolVecLang && T->isBooleanType())) {
2408 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2409 return QualType();
2410 }
2411
2412 if (const auto *BIT = T->getAs<BitIntType>();
2413 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2414 return QualType();
2415
2416 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2417 std::optional<llvm::APSInt> vecSize =
2418 ArraySize->getIntegerConstantExpr(Context);
2419 if (!vecSize) {
2420 Diag(AttrLoc, diag::err_attribute_argument_type)
2421 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2422 << ArraySize->getSourceRange();
2423 return QualType();
2424 }
2425
2426 if (!vecSize->isIntN(32)) {
2427 Diag(AttrLoc, diag::err_attribute_size_too_large)
2428 << ArraySize->getSourceRange() << "vector";
2429 return QualType();
2430 }
2431 // Unlike gcc's vector_size attribute, the size is specified as the
2432 // number of elements, not the number of bytes.
2433 unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2434
2435 if (vectorSize == 0) {
2436 Diag(AttrLoc, diag::err_attribute_zero_size)
2437 << ArraySize->getSourceRange() << "vector";
2438 return QualType();
2439 }
2440
2441 return Context.getExtVectorType(T, vectorSize);
2442 }
2443
2444 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2445}
2446
2447QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2448 SourceLocation AttrLoc) {
2449 assert(Context.getLangOpts().MatrixTypes &&
2450 "Should never build a matrix type when it is disabled");
2451
2452 // Check element type, if it is not dependent.
2453 if (!ElementTy->isDependentType() &&
2454 !MatrixType::isValidElementType(ElementTy)) {
2455 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2456 return QualType();
2457 }
2458
2459 if (const auto *BIT = ElementTy->getAs<BitIntType>();
2460 BIT &&
2461 CheckBitIntElementType(*this, AttrLoc, BIT, /*ForMatrixType=*/true))
2462 return QualType();
2463
2464 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2465 NumRows->isValueDependent() || NumCols->isValueDependent())
2466 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2467 AttrLoc);
2468
2469 std::optional<llvm::APSInt> ValueRows =
2471 std::optional<llvm::APSInt> ValueColumns =
2473
2474 auto const RowRange = NumRows->getSourceRange();
2475 auto const ColRange = NumCols->getSourceRange();
2476
2477 // Both are row and column expressions are invalid.
2478 if (!ValueRows && !ValueColumns) {
2479 Diag(AttrLoc, diag::err_attribute_argument_type)
2480 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2481 << ColRange;
2482 return QualType();
2483 }
2484
2485 // Only the row expression is invalid.
2486 if (!ValueRows) {
2487 Diag(AttrLoc, diag::err_attribute_argument_type)
2488 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2489 return QualType();
2490 }
2491
2492 // Only the column expression is invalid.
2493 if (!ValueColumns) {
2494 Diag(AttrLoc, diag::err_attribute_argument_type)
2495 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2496 return QualType();
2497 }
2498
2499 // Check the matrix dimensions.
2500 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2501 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2502 if (MatrixRows == 0 && MatrixColumns == 0) {
2503 Diag(AttrLoc, diag::err_attribute_zero_size)
2504 << "matrix" << RowRange << ColRange;
2505 return QualType();
2506 }
2507 if (MatrixRows == 0) {
2508 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2509 return QualType();
2510 }
2511 if (MatrixColumns == 0) {
2512 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2513 return QualType();
2514 }
2515 if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2516 Diag(AttrLoc, diag::err_attribute_size_too_large)
2517 << RowRange << "matrix row";
2518 return QualType();
2519 }
2520 if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2521 Diag(AttrLoc, diag::err_attribute_size_too_large)
2522 << ColRange << "matrix column";
2523 return QualType();
2524 }
2525 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2526}
2527
2529 if (T->isArrayType() || T->isFunctionType()) {
2530 Diag(Loc, diag::err_func_returning_array_function)
2531 << T->isFunctionType() << T;
2532 return true;
2533 }
2534
2535 // Functions cannot return half FP.
2536 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2538 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2540 return true;
2541 }
2542
2543 // Methods cannot return interface types. All ObjC objects are
2544 // passed by reference.
2545 if (T->isObjCObjectType()) {
2546 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2547 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2548 return true;
2549 }
2550
2551 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2552 T.hasNonTrivialToPrimitiveCopyCUnion())
2555
2556 // C++2a [dcl.fct]p12:
2557 // A volatile-qualified return type is deprecated
2558 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2559 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2560
2561 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2562 return true;
2563 return false;
2564}
2565
2566/// Check the extended parameter information. Most of the necessary
2567/// checking should occur when applying the parameter attribute; the
2568/// only other checks required are positional restrictions.
2571 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2572 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2573
2574 bool emittedError = false;
2575 auto actualCC = EPI.ExtInfo.getCC();
2576 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2577 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2578 bool isCompatible =
2579 (required == RequiredCC::OnlySwift)
2580 ? (actualCC == CC_Swift)
2581 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2582 if (isCompatible || emittedError)
2583 return;
2584 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2586 << (required == RequiredCC::OnlySwift);
2587 emittedError = true;
2588 };
2589 for (size_t paramIndex = 0, numParams = paramTypes.size();
2590 paramIndex != numParams; ++paramIndex) {
2591 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2592 // Nothing interesting to check for orindary-ABI parameters.
2596 continue;
2597
2598 // swift_indirect_result parameters must be a prefix of the function
2599 // arguments.
2601 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2602 if (paramIndex != 0 &&
2603 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2605 S.Diag(getParamLoc(paramIndex),
2606 diag::err_swift_indirect_result_not_first);
2607 }
2608 continue;
2609
2611 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2612 continue;
2613
2614 // SwiftAsyncContext is not limited to swiftasynccall functions.
2616 continue;
2617
2618 // swift_error parameters must be preceded by a swift_context parameter.
2620 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2621 if (paramIndex == 0 ||
2622 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2624 S.Diag(getParamLoc(paramIndex),
2625 diag::err_swift_error_result_not_after_swift_context);
2626 }
2627 continue;
2628 }
2629 llvm_unreachable("bad ABI kind");
2630 }
2631}
2632
2634 MutableArrayRef<QualType> ParamTypes,
2637 bool Invalid = false;
2638
2640
2641 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2642 // FIXME: Loc is too inprecise here, should use proper locations for args.
2643 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2644 if (ParamType->isVoidType()) {
2645 Diag(Loc, diag::err_param_with_void_type);
2646 Invalid = true;
2647 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2649 // Disallow half FP arguments.
2650 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2652 Invalid = true;
2653 } else if (ParamType->isWebAssemblyTableType()) {
2654 Diag(Loc, diag::err_wasm_table_as_function_parameter);
2655 Invalid = true;
2656 }
2657
2658 // C++2a [dcl.fct]p4:
2659 // A parameter with volatile-qualified type is deprecated
2660 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2661 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2662
2663 ParamTypes[Idx] = ParamType;
2664 }
2665
2666 if (EPI.ExtParameterInfos) {
2667 checkExtParameterInfos(*this, ParamTypes, EPI,
2668 [=](unsigned i) { return Loc; });
2669 }
2670
2671 if (EPI.ExtInfo.getProducesResult()) {
2672 // This is just a warning, so we can't fail to build if we see it.
2674 }
2675
2676 if (Invalid)
2677 return QualType();
2678
2679 return Context.getFunctionType(T, ParamTypes, EPI);
2680}
2681
2684 DeclarationName Entity) {
2685 // Verify that we're not building a pointer to pointer to function with
2686 // exception specification.
2688 Diag(Loc, diag::err_distant_exception_spec);
2689 return QualType();
2690 }
2691
2692 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2693 // with reference type, or "cv void."
2694 if (T->isReferenceType()) {
2695 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2696 << getPrintableNameForEntity(Entity) << T;
2697 return QualType();
2698 }
2699
2700 if (T->isVoidType()) {
2701 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2702 << getPrintableNameForEntity(Entity);
2703 return QualType();
2704 }
2705
2706 if (!Class->isDependentType() && !Class->isRecordType()) {
2707 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2708 return QualType();
2709 }
2710
2711 if (T->isFunctionType() && getLangOpts().OpenCL &&
2712 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2713 getLangOpts())) {
2714 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2715 return QualType();
2716 }
2717
2718 if (getLangOpts().HLSL && Loc.isValid()) {
2719 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2720 return QualType();
2721 }
2722
2723 // Adjust the default free function calling convention to the default method
2724 // calling convention.
2725 bool IsCtorOrDtor =
2728 if (T->isFunctionType())
2729 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
2730
2731 return Context.getMemberPointerType(T, Class.getTypePtr());
2732}
2733
2736 DeclarationName Entity) {
2737 if (!T->isFunctionType()) {
2738 Diag(Loc, diag::err_nonfunction_block_type);
2739 return QualType();
2740 }
2741
2742 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2743 return QualType();
2744
2745 if (getLangOpts().OpenCL)
2747
2749}
2750
2752 QualType QT = Ty.get();
2753 if (QT.isNull()) {
2754 if (TInfo) *TInfo = nullptr;
2755 return QualType();
2756 }
2757
2758 TypeSourceInfo *DI = nullptr;
2759 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2760 QT = LIT->getType();
2761 DI = LIT->getTypeSourceInfo();
2762 }
2763
2764 if (TInfo) *TInfo = DI;
2765 return QT;
2766}
2767
2768static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2769 Qualifiers::ObjCLifetime ownership,
2770 unsigned chunkIndex);
2771
2772/// Given that this is the declaration of a parameter under ARC,
2773/// attempt to infer attributes and such for pointer-to-whatever
2774/// types.
2775static void inferARCWriteback(TypeProcessingState &state,
2776 QualType &declSpecType) {
2777 Sema &S = state.getSema();
2778 Declarator &declarator = state.getDeclarator();
2779
2780 // TODO: should we care about decl qualifiers?
2781
2782 // Check whether the declarator has the expected form. We walk
2783 // from the inside out in order to make the block logic work.
2784 unsigned outermostPointerIndex = 0;
2785 bool isBlockPointer = false;
2786 unsigned numPointers = 0;
2787 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2788 unsigned chunkIndex = i;
2789 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2790 switch (chunk.Kind) {
2792 // Ignore parens.
2793 break;
2794
2797 // Count the number of pointers. Treat references
2798 // interchangeably as pointers; if they're mis-ordered, normal
2799 // type building will discover that.
2800 outermostPointerIndex = chunkIndex;
2801 numPointers++;
2802 break;
2803
2805 // If we have a pointer to block pointer, that's an acceptable
2806 // indirect reference; anything else is not an application of
2807 // the rules.
2808 if (numPointers != 1) return;
2809 numPointers++;
2810 outermostPointerIndex = chunkIndex;
2811 isBlockPointer = true;
2812
2813 // We don't care about pointer structure in return values here.
2814 goto done;
2815
2816 case DeclaratorChunk::Array: // suppress if written (id[])?
2820 return;
2821 }
2822 }
2823 done:
2824
2825 // If we have *one* pointer, then we want to throw the qualifier on
2826 // the declaration-specifiers, which means that it needs to be a
2827 // retainable object type.
2828 if (numPointers == 1) {
2829 // If it's not a retainable object type, the rule doesn't apply.
2830 if (!declSpecType->isObjCRetainableType()) return;
2831
2832 // If it already has lifetime, don't do anything.
2833 if (declSpecType.getObjCLifetime()) return;
2834
2835 // Otherwise, modify the type in-place.
2836 Qualifiers qs;
2837
2838 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2840 else
2842 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2843
2844 // If we have *two* pointers, then we want to throw the qualifier on
2845 // the outermost pointer.
2846 } else if (numPointers == 2) {
2847 // If we don't have a block pointer, we need to check whether the
2848 // declaration-specifiers gave us something that will turn into a
2849 // retainable object pointer after we slap the first pointer on it.
2850 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2851 return;
2852
2853 // Look for an explicit lifetime attribute there.
2854 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2855 if (chunk.Kind != DeclaratorChunk::Pointer &&
2857 return;
2858 for (const ParsedAttr &AL : chunk.getAttrs())
2859 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2860 return;
2861
2863 outermostPointerIndex);
2864
2865 // Any other number of pointers/references does not trigger the rule.
2866 } else return;
2867
2868 // TODO: mark whether we did this inference?
2869}
2870
2871void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2872 SourceLocation FallbackLoc,
2873 SourceLocation ConstQualLoc,
2874 SourceLocation VolatileQualLoc,
2875 SourceLocation RestrictQualLoc,
2876 SourceLocation AtomicQualLoc,
2877 SourceLocation UnalignedQualLoc) {
2878 if (!Quals)
2879 return;
2880
2881 struct Qual {
2882 const char *Name;
2883 unsigned Mask;
2885 } const QualKinds[5] = {
2886 { "const", DeclSpec::TQ_const, ConstQualLoc },
2887 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2888 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2889 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2890 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2891 };
2892
2893 SmallString<32> QualStr;
2894 unsigned NumQuals = 0;
2896 FixItHint FixIts[5];
2897
2898 // Build a string naming the redundant qualifiers.
2899 for (auto &E : QualKinds) {
2900 if (Quals & E.Mask) {
2901 if (!QualStr.empty()) QualStr += ' ';
2902 QualStr += E.Name;
2903
2904 // If we have a location for the qualifier, offer a fixit.
2905 SourceLocation QualLoc = E.Loc;
2906 if (QualLoc.isValid()) {
2907 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2908 if (Loc.isInvalid() ||
2909 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2910 Loc = QualLoc;
2911 }
2912
2913 ++NumQuals;
2914 }
2915 }
2916
2917 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2918 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2919}
2920
2921// Diagnose pointless type qualifiers on the return type of a function.
2923 Declarator &D,
2924 unsigned FunctionChunkIndex) {
2926 D.getTypeObject(FunctionChunkIndex).Fun;
2927 if (FTI.hasTrailingReturnType()) {
2928 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2929 RetTy.getLocalCVRQualifiers(),
2931 return;
2932 }
2933
2934 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2935 End = D.getNumTypeObjects();
2936 OuterChunkIndex != End; ++OuterChunkIndex) {
2937 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2938 switch (OuterChunk.Kind) {
2940 continue;
2941
2943 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2945 diag::warn_qual_return_type,
2946 PTI.TypeQuals,
2948 PTI.ConstQualLoc,
2949 PTI.VolatileQualLoc,
2950 PTI.RestrictQualLoc,
2951 PTI.AtomicQualLoc,
2952 PTI.UnalignedQualLoc);
2953 return;
2954 }
2955
2962 // FIXME: We can't currently provide an accurate source location and a
2963 // fix-it hint for these.
2964 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2965 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2966 RetTy.getCVRQualifiers() | AtomicQual,
2967 D.getIdentifierLoc());
2968 return;
2969 }
2970
2971 llvm_unreachable("unknown declarator chunk kind");
2972 }
2973
2974 // If the qualifiers come from a conversion function type, don't diagnose
2975 // them -- they're not necessarily redundant, since such a conversion
2976 // operator can be explicitly called as "x.operator const int()".
2978 return;
2979
2980 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2981 // which are present there.
2982 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2983 D.getDeclSpec().getTypeQualifiers(),
2984 D.getIdentifierLoc(),
2985 D.getDeclSpec().getConstSpecLoc(),
2986 D.getDeclSpec().getVolatileSpecLoc(),
2987 D.getDeclSpec().getRestrictSpecLoc(),
2988 D.getDeclSpec().getAtomicSpecLoc(),
2989 D.getDeclSpec().getUnalignedSpecLoc());
2990}
2991
2992static std::pair<QualType, TypeSourceInfo *>
2993InventTemplateParameter(TypeProcessingState &state, QualType T,
2994 TypeSourceInfo *TrailingTSI, AutoType *Auto,
2996 Sema &S = state.getSema();
2997 Declarator &D = state.getDeclarator();
2998
2999 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3000 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3001 const bool IsParameterPack = D.hasEllipsis();
3002
3003 // If auto is mentioned in a lambda parameter or abbreviated function
3004 // template context, convert it to a template parameter type.
3005
3006 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3007 // template parameter type. Template parameters are temporarily added
3008 // to the TU until the associated TemplateDecl is created.
3009 TemplateTypeParmDecl *InventedTemplateParam =
3012 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3013 /*NameLoc=*/D.getIdentifierLoc(),
3014 TemplateParameterDepth, AutoParameterPosition,
3016 D.getIdentifier(), AutoParameterPosition), false,
3017 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3018 InventedTemplateParam->setImplicit();
3019 Info.TemplateParams.push_back(InventedTemplateParam);
3020
3021 // Attach type constraints to the new parameter.
3022 if (Auto->isConstrained()) {
3023 if (TrailingTSI) {
3024 // The 'auto' appears in a trailing return type we've already built;
3025 // extract its type constraints to attach to the template parameter.
3026 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3027 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3028 bool Invalid = false;
3029 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3030 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3033 Invalid = true;
3034 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3035 }
3036
3037 if (!Invalid) {
3039 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3040 AutoLoc.getNamedConcept(), /*FoundDecl=*/AutoLoc.getFoundDecl(),
3041 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3042 InventedTemplateParam,
3043 S.Context.getTypeDeclType(InventedTemplateParam),
3044 D.getEllipsisLoc());
3045 }
3046 } else {
3047 // The 'auto' appears in the decl-specifiers; we've not finished forming
3048 // TypeSourceInfo for it yet.
3049 TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3050 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
3051 TemplateId->RAngleLoc);
3052 bool Invalid = false;
3053 if (TemplateId->LAngleLoc.isValid()) {
3054 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3055 TemplateId->NumArgs);
3056 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3057
3058 if (D.getEllipsisLoc().isInvalid()) {
3059 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3062 Invalid = true;
3063 break;
3064 }
3065 }
3066 }
3067 }
3068 if (!Invalid) {
3069 UsingShadowDecl *USD =
3070 TemplateId->Template.get().getAsUsingShadowDecl();
3071 auto *CD =
3072 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
3074 D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3076 TemplateId->TemplateNameLoc),
3077 CD,
3078 /*FoundDecl=*/
3079 USD ? cast<NamedDecl>(USD) : CD,
3080 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3081 InventedTemplateParam,
3082 S.Context.getTypeDeclType(InventedTemplateParam),
3083 D.getEllipsisLoc());
3084 }
3085 }
3086 }
3087
3088 // Replace the 'auto' in the function parameter with this invented
3089 // template type parameter.
3090 // FIXME: Retain some type sugar to indicate that this was written
3091 // as 'auto'?
3092 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3093 QualType NewT = state.ReplaceAutoType(T, Replacement);
3094 TypeSourceInfo *NewTSI =
3095 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3096 : nullptr;
3097 return {NewT, NewTSI};
3098}
3099
3100static TypeSourceInfo *
3101GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3102 QualType T, TypeSourceInfo *ReturnTypeInfo);
3103
3104static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3105 TypeSourceInfo *&ReturnTypeInfo) {
3106 Sema &SemaRef = state.getSema();
3107 Declarator &D = state.getDeclarator();
3108 QualType T;
3109 ReturnTypeInfo = nullptr;
3110
3111 // The TagDecl owned by the DeclSpec.
3112 TagDecl *OwnedTagDecl = nullptr;
3113
3114 switch (D.getName().getKind()) {
3120 T = ConvertDeclSpecToType(state);
3121
3122 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3123 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3124 // Owned declaration is embedded in declarator.
3125 OwnedTagDecl->setEmbeddedInDeclarator(true);
3126 }
3127 break;
3128
3132 // Constructors and destructors don't have return types. Use
3133 // "void" instead.
3134 T = SemaRef.Context.VoidTy;
3136 D.getMutableDeclSpec().getAttributes());
3137 break;
3138
3140 // Deduction guides have a trailing return type and no type in their
3141 // decl-specifier sequence. Use a placeholder return type for now.
3142 T = SemaRef.Context.DependentTy;
3143 break;
3144
3146 // The result type of a conversion function is the type that it
3147 // converts to.
3148 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3149 &ReturnTypeInfo);
3150 break;
3151 }
3152
3153 // Note: We don't need to distribute declaration attributes (i.e.
3154 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3155 // and those don't get distributed.
3157 state, T, SemaRef.CUDA().IdentifyTarget(D.getAttributes()));
3158
3159 // Find the deduced type in this type. Look in the trailing return type if we
3160 // have one, otherwise in the DeclSpec type.
3161 // FIXME: The standard wording doesn't currently describe this.
3163 bool DeducedIsTrailingReturnType = false;
3164 if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3165 QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3166 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3167 DeducedIsTrailingReturnType = true;
3168 }
3169
3170 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3171 if (Deduced) {
3172 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3173 int Error = -1;
3174
3175 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3176 // class template argument deduction)?
3177 bool IsCXXAutoType =
3178 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3179 bool IsDeducedReturnType = false;
3180
3181 switch (D.getContext()) {
3183 // Declared return type of a lambda-declarator is implicit and is always
3184 // 'auto'.
3185 break;
3188 Error = 0;
3189 break;
3191 Error = 22;
3192 break;
3195 InventedTemplateParameterInfo *Info = nullptr;
3196 if (D.getContext() == DeclaratorContext::Prototype) {
3197 // With concepts we allow 'auto' in function parameters.
3198 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3199 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3200 Error = 0;
3201 break;
3202 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3203 Error = 21;
3204 break;
3205 }
3206
3207 Info = &SemaRef.InventedParameterInfos.back();
3208 } else {
3209 // In C++14, generic lambdas allow 'auto' in their parameters.
3210 if (!SemaRef.getLangOpts().CPlusPlus14 && Auto &&
3211 Auto->getKeyword() == AutoTypeKeyword::Auto) {
3212 Error = 25; // auto not allowed in lambda parameter (before C++14)
3213 break;
3214 } else if (!Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) {
3215 Error = 16; // __auto_type or decltype(auto) not allowed in lambda
3216 // parameter
3217 break;
3218 }
3219 Info = SemaRef.getCurLambda();
3220 assert(Info && "No LambdaScopeInfo on the stack!");
3221 }
3222
3223 // We'll deal with inventing template parameters for 'auto' in trailing
3224 // return types when we pick up the trailing return type when processing
3225 // the function chunk.
3226 if (!DeducedIsTrailingReturnType)
3227 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3228 break;
3229 }
3231 if (D.isStaticMember() || D.isFunctionDeclarator())
3232 break;
3233 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3234 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3235 Error = 6; // Interface member.
3236 } else {
3237 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3238 case TagTypeKind::Enum:
3239 llvm_unreachable("unhandled tag kind");
3241 Error = Cxx ? 1 : 2; /* Struct member */
3242 break;
3243 case TagTypeKind::Union:
3244 Error = Cxx ? 3 : 4; /* Union member */
3245 break;
3246 case TagTypeKind::Class:
3247 Error = 5; /* Class member */
3248 break;
3250 Error = 6; /* Interface member */
3251 break;
3252 }
3253 }
3254 if (D.getDeclSpec().isFriendSpecified())
3255 Error = 20; // Friend type
3256 break;
3257 }
3260 Error = 7; // Exception declaration
3261 break;
3263 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3264 !SemaRef.getLangOpts().CPlusPlus20)
3265 Error = 19; // Template parameter (until C++20)
3266 else if (!SemaRef.getLangOpts().CPlusPlus17)
3267 Error = 8; // Template parameter (until C++17)
3268 break;
3270 Error = 9; // Block literal
3271 break;
3273 // Within a template argument list, a deduced template specialization
3274 // type will be reinterpreted as a template template argument.
3275 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3276 !D.getNumTypeObjects() &&
3277 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3278 break;
3279 [[fallthrough]];
3281 Error = 10; // Template type argument
3282 break;
3285 Error = 12; // Type alias
3286 break;
3289 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3290 Error = 13; // Function return type
3291 IsDeducedReturnType = true;
3292 break;
3294 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3295 Error = 14; // conversion-type-id
3296 IsDeducedReturnType = true;
3297 break;
3299 if (isa<DeducedTemplateSpecializationType>(Deduced))
3300 break;
3301 if (SemaRef.getLangOpts().CPlusPlus23 && IsCXXAutoType &&
3302 !Auto->isDecltypeAuto())
3303 break; // auto(x)
3304 [[fallthrough]];
3307 Error = 15; // Generic
3308 break;
3314 // FIXME: P0091R3 (erroneously) does not permit class template argument
3315 // deduction in conditions, for-init-statements, and other declarations
3316 // that are not simple-declarations.
3317 break;
3319 // FIXME: P0091R3 does not permit class template argument deduction here,
3320 // but we follow GCC and allow it anyway.
3321 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3322 Error = 17; // 'new' type
3323 break;
3325 Error = 18; // K&R function parameter
3326 break;
3327 }
3328
3329 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3330 Error = 11;
3331
3332 // In Objective-C it is an error to use 'auto' on a function declarator
3333 // (and everywhere for '__auto_type').
3334 if (D.isFunctionDeclarator() &&
3335 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3336 Error = 13;
3337
3338 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3340 AutoRange = D.getName().getSourceRange();
3341
3342 if (Error != -1) {
3343 unsigned Kind;
3344 if (Auto) {
3345 switch (Auto->getKeyword()) {
3346 case AutoTypeKeyword::Auto: Kind = 0; break;
3347 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3348 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3349 }
3350 } else {
3351 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3352 "unknown auto type");
3353 Kind = 3;
3354 }
3355
3356 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3357 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3358
3359 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3360 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3361 << QualType(Deduced, 0) << AutoRange;
3362 if (auto *TD = TN.getAsTemplateDecl())
3363 SemaRef.NoteTemplateLocation(*TD);
3364
3365 T = SemaRef.Context.IntTy;
3366 D.setInvalidType(true);
3367 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3368 // If there was a trailing return type, we already got
3369 // warn_cxx98_compat_trailing_return_type in the parser.
3370 SemaRef.Diag(AutoRange.getBegin(),
3372 ? diag::warn_cxx11_compat_generic_lambda
3373 : IsDeducedReturnType
3374 ? diag::warn_cxx11_compat_deduced_return_type
3375 : diag::warn_cxx98_compat_auto_type_specifier)
3376 << AutoRange;
3377 }
3378 }
3379
3380 if (SemaRef.getLangOpts().CPlusPlus &&
3381 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3382 // Check the contexts where C++ forbids the declaration of a new class
3383 // or enumeration in a type-specifier-seq.
3384 unsigned DiagID = 0;
3385 switch (D.getContext()) {
3388 // Class and enumeration definitions are syntactically not allowed in
3389 // trailing return types.
3390 llvm_unreachable("parser should not have allowed this");
3391 break;
3399 // C++11 [dcl.type]p3:
3400 // A type-specifier-seq shall not define a class or enumeration unless
3401 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3402 // the declaration of a template-declaration.
3404 break;
3406 DiagID = diag::err_type_defined_in_alias_template;
3407 break;
3418 DiagID = diag::err_type_defined_in_type_specifier;
3419 break;
3426 // C++ [dcl.fct]p6:
3427 // Types shall not be defined in return or parameter types.
3428 DiagID = diag::err_type_defined_in_param_type;
3429 break;
3431 // C++ 6.4p2:
3432 // The type-specifier-seq shall not contain typedef and shall not declare
3433 // a new class or enumeration.
3434 DiagID = diag::err_type_defined_in_condition;
3435 break;
3436 }
3437
3438 if (DiagID != 0) {
3439 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3440 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3441 D.setInvalidType(true);
3442 }
3443 }
3444
3445 assert(!T.isNull() && "This function should not return a null type");
3446 return T;
3447}
3448
3449/// Produce an appropriate diagnostic for an ambiguity between a function
3450/// declarator and a C++ direct-initializer.
3452 DeclaratorChunk &DeclType, QualType RT) {
3453 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3454 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3455
3456 // If the return type is void there is no ambiguity.
3457 if (RT->isVoidType())
3458 return;
3459
3460 // An initializer for a non-class type can have at most one argument.
3461 if (!RT->isRecordType() && FTI.NumParams > 1)
3462 return;
3463
3464 // An initializer for a reference must have exactly one argument.
3465 if (RT->isReferenceType() && FTI.NumParams != 1)
3466 return;
3467
3468 // Only warn if this declarator is declaring a function at block scope, and
3469 // doesn't have a storage class (such as 'extern') specified.
3470 if (!D.isFunctionDeclarator() ||
3471 D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration ||
3473 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified)
3474 return;
3475
3476 // Inside a condition, a direct initializer is not permitted. We allow one to
3477 // be parsed in order to give better diagnostics in condition parsing.
3478 if (D.getContext() == DeclaratorContext::Condition)
3479 return;
3480
3481 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3482
3483 S.Diag(DeclType.Loc,
3484 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3485 : diag::warn_empty_parens_are_function_decl)
3486 << ParenRange;
3487
3488 // If the declaration looks like:
3489 // T var1,
3490 // f();
3491 // and name lookup finds a function named 'f', then the ',' was
3492 // probably intended to be a ';'.
3493 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3494 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3495 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3496 if (Comma.getFileID() != Name.getFileID() ||
3497 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3498 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3500 if (S.LookupName(Result, S.getCurScope()))
3501 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3502 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3503 << D.getIdentifier();
3504 Result.suppressDiagnostics();
3505 }
3506 }
3507
3508 if (FTI.NumParams > 0) {
3509 // For a declaration with parameters, eg. "T var(T());", suggest adding
3510 // parens around the first parameter to turn the declaration into a
3511 // variable declaration.
3515 // FIXME: Maybe we should suggest adding braces instead of parens
3516 // in C++11 for classes that don't have an initializer_list constructor.
3517 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3520 } else {
3521 // For a declaration without parameters, eg. "T var();", suggest replacing
3522 // the parens with an initializer to turn the declaration into a variable
3523 // declaration.
3524 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3525
3526 // Empty parens mean value-initialization, and no parens mean
3527 // default initialization. These are equivalent if the default
3528 // constructor is user-provided or if zero-initialization is a
3529 // no-op.
3530 if (RD && RD->hasDefinition() &&
3532 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3533 << FixItHint::CreateRemoval(ParenRange);
3534 else {
3535 std::string Init =
3536 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3537 if (Init.empty() && S.LangOpts.CPlusPlus11)
3538 Init = "{}";
3539 if (!Init.empty())
3540 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3541 << FixItHint::CreateReplacement(ParenRange, Init);
3542 }
3543 }
3544}
3545
3546/// Produce an appropriate diagnostic for a declarator with top-level
3547/// parentheses.
3549 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3550 assert(Paren.Kind == DeclaratorChunk::Paren &&
3551 "do not have redundant top-level parentheses");
3552
3553 // This is a syntactic check; we're not interested in cases that arise
3554 // during template instantiation.
3556 return;
3557
3558 // Check whether this could be intended to be a construction of a temporary
3559 // object in C++ via a function-style cast.
3560 bool CouldBeTemporaryObject =
3561 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3562 !D.isInvalidType() && D.getIdentifier() &&
3563 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3564 (T->isRecordType() || T->isDependentType()) &&
3565 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3566
3567 bool StartsWithDeclaratorId = true;
3568 for (auto &C : D.type_objects()) {
3569 switch (C.Kind) {
3571 if (&C == &Paren)
3572 continue;
3573 [[fallthrough]];
3575 StartsWithDeclaratorId = false;
3576 continue;
3577
3579 if (!C.Arr.NumElts)
3580 CouldBeTemporaryObject = false;
3581 continue;
3582
3584 // FIXME: Suppress the warning here if there is no initializer; we're
3585 // going to give an error anyway.
3586 // We assume that something like 'T (&x) = y;' is highly likely to not
3587 // be intended to be a temporary object.
3588 CouldBeTemporaryObject = false;
3589 StartsWithDeclaratorId = false;
3590 continue;
3591
3593 // In a new-type-id, function chunks require parentheses.
3594 if (D.getContext() == DeclaratorContext::CXXNew)
3595 return;
3596 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3597 // redundant-parens warning, but we don't know whether the function
3598 // chunk was syntactically valid as an expression here.
3599 CouldBeTemporaryObject = false;
3600 continue;
3601
3605 // These cannot appear in expressions.
3606 CouldBeTemporaryObject = false;
3607 StartsWithDeclaratorId = false;
3608 continue;
3609 }
3610 }
3611
3612 // FIXME: If there is an initializer, assume that this is not intended to be
3613 // a construction of a temporary object.
3614
3615 // Check whether the name has already been declared; if not, this is not a
3616 // function-style cast.
3617 if (CouldBeTemporaryObject) {
3618 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3620 if (!S.LookupName(Result, S.getCurScope()))
3621 CouldBeTemporaryObject = false;
3622 Result.suppressDiagnostics();
3623 }
3624
3625 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3626
3627 if (!CouldBeTemporaryObject) {
3628 // If we have A (::B), the parentheses affect the meaning of the program.
3629 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3630 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3631 // formally unambiguous.
3632 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3633 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3634 NNS = NNS->getPrefix()) {
3635 if (NNS->getKind() == NestedNameSpecifier::Global)
3636 return;
3637 }
3638 }
3639
3640 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3641 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3643 return;
3644 }
3645
3646 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3647 << ParenRange << D.getIdentifier();
3648 auto *RD = T->getAsCXXRecordDecl();
3649 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3650 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3651 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3652 << D.getIdentifier();
3653 // FIXME: A cast to void is probably a better suggestion in cases where it's
3654 // valid (when there is no initializer and we're not in a condition).
3655 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3658 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3661}
3662
3663/// Helper for figuring out the default CC for a function declarator type. If
3664/// this is the outermost chunk, then we can determine the CC from the
3665/// declarator context. If not, then this could be either a member function
3666/// type or normal function type.
3668 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3669 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3670 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3671
3672 // Check for an explicit CC attribute.
3673 for (const ParsedAttr &AL : AttrList) {
3674 switch (AL.getKind()) {
3676 // Ignore attributes that don't validate or can't apply to the
3677 // function type. We'll diagnose the failure to apply them in
3678 // handleFunctionTypeAttr.
3679 CallingConv CC;
3680 if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr,
3681 S.CUDA().IdentifyTarget(D.getAttributes())) &&
3682 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3683 return CC;
3684 }
3685 break;
3686 }
3687
3688 default:
3689 break;
3690 }
3691 }
3692
3693 bool IsCXXInstanceMethod = false;
3694
3695 if (S.getLangOpts().CPlusPlus) {
3696 // Look inwards through parentheses to see if this chunk will form a
3697 // member pointer type or if we're the declarator. Any type attributes
3698 // between here and there will override the CC we choose here.
3699 unsigned I = ChunkIndex;
3700 bool FoundNonParen = false;
3701 while (I && !FoundNonParen) {
3702 --I;
3703 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3704 FoundNonParen = true;
3705 }
3706
3707 if (FoundNonParen) {
3708 // If we're not the declarator, we're a regular function type unless we're
3709 // in a member pointer.
3710 IsCXXInstanceMethod =
3711 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3712 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3713 // This can only be a call operator for a lambda, which is an instance
3714 // method, unless explicitly specified as 'static'.
3715 IsCXXInstanceMethod =
3716 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static;
3717 } else {
3718 // We're the innermost decl chunk, so must be a function declarator.
3719 assert(D.isFunctionDeclarator());
3720
3721 // If we're inside a record, we're declaring a method, but it could be
3722 // explicitly or implicitly static.
3723 IsCXXInstanceMethod =
3724 D.isFirstDeclarationOfMember() &&
3725 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3726 !D.isStaticMember();
3727 }
3728 }
3729
3731 IsCXXInstanceMethod);
3732
3733 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3734 // and AMDGPU targets, hence it cannot be treated as a calling
3735 // convention attribute. This is the simplest place to infer
3736 // calling convention for OpenCL kernels.
3737 if (S.getLangOpts().OpenCL) {
3738 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3739 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
3740 CC = CC_OpenCLKernel;
3741 break;
3742 }
3743 }
3744 } else if (S.getLangOpts().CUDA) {
3745 // If we're compiling CUDA/HIP code and targeting HIPSPV we need to make
3746 // sure the kernels will be marked with the right calling convention so that
3747 // they will be visible by the APIs that ingest SPIR-V. We do not do this
3748 // when targeting AMDGCNSPIRV, as it does not rely on OpenCL.
3749 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
3750 if (Triple.isSPIRV() && Triple.getVendor() != llvm::Triple::AMD) {
3751 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3752 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
3753 CC = CC_OpenCLKernel;
3754 break;
3755 }
3756 }
3757 }
3758 }
3759
3760 return CC;
3761}
3762
3763namespace {
3764 /// A simple notion of pointer kinds, which matches up with the various
3765 /// pointer declarators.
3766 enum class SimplePointerKind {
3767 Pointer,
3768 BlockPointer,
3769 MemberPointer,
3770 Array,
3771 };
3772} // end anonymous namespace
3773
3775 switch (nullability) {
3777 if (!Ident__Nonnull)
3778 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3779 return Ident__Nonnull;
3780
3782 if (!Ident__Nullable)
3783 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3784 return Ident__Nullable;
3785
3787 if (!Ident__Nullable_result)
3788 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
3789 return Ident__Nullable_result;
3790
3792 if (!Ident__Null_unspecified)
3793 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3794 return Ident__Null_unspecified;
3795 }
3796 llvm_unreachable("Unknown nullability kind.");
3797}
3798
3799/// Check whether there is a nullability attribute of any kind in the given
3800/// attribute list.
3801static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3802 for (const ParsedAttr &AL : attrs) {
3803 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3804 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3805 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
3806 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3807 return true;
3808 }
3809
3810 return false;
3811}
3812
3813namespace {
3814 /// Describes the kind of a pointer a declarator describes.
3815 enum class PointerDeclaratorKind {
3816 // Not a pointer.
3817 NonPointer,
3818 // Single-level pointer.
3819 SingleLevelPointer,
3820 // Multi-level pointer (of any pointer kind).
3821 MultiLevelPointer,
3822 // CFFooRef*
3823 MaybePointerToCFRef,
3824 // CFErrorRef*
3825 CFErrorRefPointer,
3826 // NSError**
3827 NSErrorPointerPointer,
3828 };
3829
3830 /// Describes a declarator chunk wrapping a pointer that marks inference as
3831 /// unexpected.
3832 // These values must be kept in sync with diagnostics.
3833 enum class PointerWrappingDeclaratorKind {
3834 /// Pointer is top-level.
3835 None = -1,
3836 /// Pointer is an array element.
3837 Array = 0,
3838 /// Pointer is the referent type of a C++ reference.
3839 Reference = 1
3840 };
3841} // end anonymous namespace
3842
3843/// Classify the given declarator, whose type-specified is \c type, based on
3844/// what kind of pointer it refers to.
3845///
3846/// This is used to determine the default nullability.
3847static PointerDeclaratorKind
3849 PointerWrappingDeclaratorKind &wrappingKind) {
3850 unsigned numNormalPointers = 0;
3851
3852 // For any dependent type, we consider it a non-pointer.
3853 if (type->isDependentType())
3854 return PointerDeclaratorKind::NonPointer;
3855
3856 // Look through the declarator chunks to identify pointers.
3857 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3858 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3859 switch (chunk.Kind) {
3861 if (numNormalPointers == 0)
3862 wrappingKind = PointerWrappingDeclaratorKind::Array;
3863 break;
3864
3867 break;
3868
3871 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3872 : PointerDeclaratorKind::SingleLevelPointer;
3873
3875 break;
3876
3878 if (numNormalPointers == 0)
3879 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3880 break;
3881
3883 ++numNormalPointers;
3884 if (numNormalPointers > 2)
3885 return PointerDeclaratorKind::MultiLevelPointer;
3886 break;
3887 }
3888 }
3889
3890 // Then, dig into the type specifier itself.
3891 unsigned numTypeSpecifierPointers = 0;
3892 do {
3893 // Decompose normal pointers.
3894 if (auto ptrType = type->getAs<PointerType>()) {
3895 ++numNormalPointers;
3896
3897 if (numNormalPointers > 2)
3898 return PointerDeclaratorKind::MultiLevelPointer;
3899
3900 type = ptrType->getPointeeType();
3901 ++numTypeSpecifierPointers;
3902 continue;
3903 }
3904
3905 // Decompose block pointers.
3906 if (type->getAs<BlockPointerType>()) {
3907 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3908 : PointerDeclaratorKind::SingleLevelPointer;
3909 }
3910
3911 // Decompose member pointers.
3912 if (type->getAs<MemberPointerType>()) {
3913 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3914 : PointerDeclaratorKind::SingleLevelPointer;
3915 }
3916
3917 // Look at Objective-C object pointers.
3918 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3919 ++numNormalPointers;
3920 ++numTypeSpecifierPointers;
3921
3922 // If this is NSError**, report that.
3923 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3924 if (objcClassDecl->getIdentifier() == S.ObjC().getNSErrorIdent() &&
3925 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3926 return PointerDeclaratorKind::NSErrorPointerPointer;
3927 }
3928 }
3929
3930 break;
3931 }
3932
3933 // Look at Objective-C class types.
3934 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3935 if (objcClass->getInterface()->getIdentifier() ==
3936 S.ObjC().getNSErrorIdent()) {
3937 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3938 return PointerDeclaratorKind::NSErrorPointerPointer;
3939 }
3940
3941 break;
3942 }
3943
3944 // If at this point we haven't seen a pointer, we won't see one.
3945 if (numNormalPointers == 0)
3946 return PointerDeclaratorKind::NonPointer;
3947
3948 if (auto recordType = type->getAs<RecordType>()) {
3949 RecordDecl *recordDecl = recordType->getDecl();
3950
3951 // If this is CFErrorRef*, report it as such.
3952 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
3953 S.ObjC().isCFError(recordDecl)) {
3954 return PointerDeclaratorKind::CFErrorRefPointer;
3955 }
3956 break;
3957 }
3958
3959 break;
3960 } while (true);
3961
3962 switch (numNormalPointers) {
3963 case 0:
3964 return PointerDeclaratorKind::NonPointer;
3965
3966 case 1:
3967 return PointerDeclaratorKind::SingleLevelPointer;
3968
3969 case 2:
3970 return PointerDeclaratorKind::MaybePointerToCFRef;
3971
3972 default:
3973 return PointerDeclaratorKind::MultiLevelPointer;
3974 }
3975}
3976
3978 SourceLocation loc) {
3979 // If we're anywhere in a function, method, or closure context, don't perform
3980 // completeness checks.
3981 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3982 if (ctx->isFunctionOrMethod())
3983 return FileID();
3984
3985 if (ctx->isFileContext())
3986 break;
3987 }
3988
3989 // We only care about the expansion location.
3990 loc = S.SourceMgr.getExpansionLoc(loc);
3991 FileID file = S.SourceMgr.getFileID(loc);
3992 if (file.isInvalid())
3993 return FileID();
3994
3995 // Retrieve file information.
3996 bool invalid = false;
3997 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3998 if (invalid || !sloc.isFile())
3999 return FileID();
4000
4001 // We don't want to perform completeness checks on the main file or in
4002 // system headers.
4003 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4004 if (fileInfo.getIncludeLoc().isInvalid())
4005 return FileID();
4006 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4008 return FileID();
4009 }
4010
4011 return file;
4012}
4013
4014/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4015/// taking into account whitespace before and after.
4016template <typename DiagBuilderT>
4017static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4018 SourceLocation PointerLoc,
4019 NullabilityKind Nullability) {
4020 assert(PointerLoc.isValid());
4021 if (PointerLoc.isMacroID())
4022 return;
4023
4024 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4025 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4026 return;
4027
4028 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4029 if (!NextChar)
4030 return;
4031
4032 SmallString<32> InsertionTextBuf{" "};
4033 InsertionTextBuf += getNullabilitySpelling(Nullability);
4034 InsertionTextBuf += " ";
4035 StringRef InsertionText = InsertionTextBuf.str();
4036
4037 if (isWhitespace(*NextChar)) {
4038 InsertionText = InsertionText.drop_back();
4039 } else if (NextChar[-1] == '[') {
4040 if (NextChar[0] == ']')
4041 InsertionText = InsertionText.drop_back().drop_front();
4042 else
4043 InsertionText = InsertionText.drop_front();
4044 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4045 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4046 InsertionText = InsertionText.drop_back().drop_front();
4047 }
4048
4049 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4050}
4051
4053 SimplePointerKind PointerKind,
4054 SourceLocation PointerLoc,
4055 SourceLocation PointerEndLoc) {
4056 assert(PointerLoc.isValid());
4057
4058 if (PointerKind == SimplePointerKind::Array) {
4059 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4060 } else {
4061 S.Diag(PointerLoc, diag::warn_nullability_missing)
4062 << static_cast<unsigned>(PointerKind);
4063 }
4064
4065 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4066 if (FixItLoc.isMacroID())
4067 return;
4068
4069 auto addFixIt = [&](NullabilityKind Nullability) {
4070 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4071 Diag << static_cast<unsigned>(Nullability);
4072 Diag << static_cast<unsigned>(PointerKind);
4073 fixItNullability(S, Diag, FixItLoc, Nullability);
4074 };
4075 addFixIt(NullabilityKind::Nullable);
4076 addFixIt(NullabilityKind::NonNull);
4077}
4078
4079/// Complains about missing nullability if the file containing \p pointerLoc
4080/// has other uses of nullability (either the keywords or the \c assume_nonnull
4081/// pragma).
4082///
4083/// If the file has \e not seen other uses of nullability, this particular
4084/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4085static void
4086checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4087 SourceLocation pointerLoc,
4088 SourceLocation pointerEndLoc = SourceLocation()) {
4089 // Determine which file we're performing consistency checking for.
4090 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4091 if (file.isInvalid())
4092 return;
4093
4094 // If we haven't seen any type nullability in this file, we won't warn now
4095 // about anything.
4096 FileNullability &fileNullability = S.NullabilityMap[file];
4097 if (!fileNullability.SawTypeNullability) {
4098 // If this is the first pointer declarator in the file, and the appropriate
4099 // warning is on, record it in case we need to diagnose it retroactively.
4100 diag::kind diagKind;
4101 if (pointerKind == SimplePointerKind::Array)
4102 diagKind = diag::warn_nullability_missing_array;
4103 else
4104 diagKind = diag::warn_nullability_missing;
4105
4106 if (fileNullability.PointerLoc.isInvalid() &&
4107 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4108 fileNullability.PointerLoc = pointerLoc;
4109 fileNullability.PointerEndLoc = pointerEndLoc;
4110 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4111 }
4112
4113 return;
4114 }
4115
4116 // Complain about missing nullability.
4117 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4118}
4119
4120/// Marks that a nullability feature has been used in the file containing
4121/// \p loc.
4122///
4123/// If this file already had pointer types in it that were missing nullability,
4124/// the first such instance is retroactively diagnosed.
4125///
4126/// \sa checkNullabilityConsistency
4129 if (file.isInvalid())
4130 return;
4131
4132 FileNullability &fileNullability = S.NullabilityMap[file];
4133 if (fileNullability.SawTypeNullability)
4134 return;
4135 fileNullability.SawTypeNullability = true;
4136
4137 // If we haven't seen any type nullability before, now we have. Retroactively
4138 // diagnose the first unannotated pointer, if there was one.
4139 if (fileNullability.PointerLoc.isInvalid())
4140 return;
4141
4142 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4143 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4144 fileNullability.PointerEndLoc);
4145}
4146
4147/// Returns true if any of the declarator chunks before \p endIndex include a
4148/// level of indirection: array, pointer, reference, or pointer-to-member.
4149///
4150/// Because declarator chunks are stored in outer-to-inner order, testing
4151/// every chunk before \p endIndex is testing all chunks that embed the current
4152/// chunk as part of their type.
4153///
4154/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4155/// end index, in which case all chunks are tested.
4156static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4157 unsigned i = endIndex;
4158 while (i != 0) {
4159 // Walk outwards along the declarator chunks.
4160 --i;
4161 const DeclaratorChunk &DC = D.getTypeObject(i);
4162 switch (DC.Kind) {
4164 break;
4169 return true;
4173 // These are invalid anyway, so just ignore.
4174 break;
4175 }
4176 }
4177 return false;
4178}
4179
4180static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4181 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4182 Chunk.Kind == DeclaratorChunk::Array);
4183}
4184
4185template<typename AttrT>
4186static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4187 AL.setUsedAsTypeAttr();
4188 return ::new (Ctx) AttrT(Ctx, AL);
4189}
4190
4192 NullabilityKind NK) {
4193 switch (NK) {
4195 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4196
4198 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4199
4201 return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4202
4204 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4205 }
4206 llvm_unreachable("unknown NullabilityKind");
4207}
4208
4209// Diagnose whether this is a case with the multiple addr spaces.
4210// Returns true if this is an invalid case.
4211// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4212// by qualifiers for two or more different address spaces."
4214 LangAS ASNew,
4215 SourceLocation AttrLoc) {
4216 if (ASOld != LangAS::Default) {
4217 if (ASOld != ASNew) {
4218 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4219 return true;
4220 }
4221 // Emit a warning if they are identical; it's likely unintended.
4222 S.Diag(AttrLoc,
4223 diag::warn_attribute_address_multiple_identical_qualifiers);
4224 }
4225 return false;
4226}
4227
4228// Whether this is a type broadly expected to have nullability attached.
4229// These types are affected by `#pragma assume_nonnull`, and missing nullability
4230// will be diagnosed with -Wnullability-completeness.
4232 return T->canHaveNullability(/*ResultIfUnknown=*/false) &&
4233 // For now, do not infer/require nullability on C++ smart pointers.
4234 // It's unclear whether the pragma's behavior is useful for C++.
4235 // e.g. treating type-aliases and template-type-parameters differently
4236 // from types of declarations can be surprising.
4237 !isa<RecordType, TemplateSpecializationType>(
4239}
4240
4241static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4242 QualType declSpecType,
4243 TypeSourceInfo *TInfo) {
4244 // The TypeSourceInfo that this function returns will not be a null type.
4245 // If there is an error, this function will fill in a dummy type as fallback.
4246 QualType T = declSpecType;
4247 Declarator &D = state.getDeclarator();
4248 Sema &S = state.getSema();
4249 ASTContext &Context = S.Context;
4250 const LangOptions &LangOpts = S.getLangOpts();
4251
4252 // The name we're declaring, if any.
4253 DeclarationName Name;
4254 if (D.getIdentifier())
4255 Name = D.getIdentifier();
4256
4257 // Does this declaration declare a typedef-name?
4258 bool IsTypedefName =
4259 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4260 D.getContext() == DeclaratorContext::AliasDecl ||
4261 D.getContext() == DeclaratorContext::AliasTemplate;
4262
4263 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4264 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4265 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4266 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4267
4268 // If T is 'decltype(auto)', the only declarators we can have are parens
4269 // and at most one function declarator if this is a function declaration.
4270 // If T is a deduced class template specialization type, we can have no
4271 // declarator chunks at all.
4272 if (auto *DT = T->getAs<DeducedType>()) {
4273 const AutoType *AT = T->getAs<AutoType>();
4274 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4275 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4276 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4277 unsigned Index = E - I - 1;
4278 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4279 unsigned DiagId = IsClassTemplateDeduction
4280 ? diag::err_deduced_class_template_compound_type
4281 : diag::err_decltype_auto_compound_type;
4282 unsigned DiagKind = 0;
4283 switch (DeclChunk.Kind) {
4285 // FIXME: Rejecting this is a little silly.
4286 if (IsClassTemplateDeduction) {
4287 DiagKind = 4;
4288 break;
4289 }
4290 continue;
4292 if (IsClassTemplateDeduction) {
4293 DiagKind = 3;
4294 break;
4295 }
4296 unsigned FnIndex;
4297 if (D.isFunctionDeclarationContext() &&
4298 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4299 continue;
4300 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4301 break;
4302 }
4306 DiagKind = 0;
4307 break;
4309 DiagKind = 1;
4310 break;
4312 DiagKind = 2;
4313 break;
4315 break;
4316 }
4317
4318 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4319 D.setInvalidType(true);
4320 break;
4321 }
4322 }
4323 }
4324
4325 // Determine whether we should infer _Nonnull on pointer types.
4326 std::optional<NullabilityKind> inferNullability;
4327 bool inferNullabilityCS = false;
4328 bool inferNullabilityInnerOnly = false;
4329 bool inferNullabilityInnerOnlyComplete = false;
4330
4331 // Are we in an assume-nonnull region?
4332 bool inAssumeNonNullRegion = false;
4333 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4334 if (assumeNonNullLoc.isValid()) {
4335 inAssumeNonNullRegion = true;
4336 recordNullabilitySeen(S, assumeNonNullLoc);
4337 }
4338
4339 // Whether to complain about missing nullability specifiers or not.
4340 enum {
4341 /// Never complain.
4342 CAMN_No,
4343 /// Complain on the inner pointers (but not the outermost
4344 /// pointer).
4345 CAMN_InnerPointers,
4346 /// Complain about any pointers that don't have nullability
4347 /// specified or inferred.
4348 CAMN_Yes
4349 } complainAboutMissingNullability = CAMN_No;
4350 unsigned NumPointersRemaining = 0;
4351 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4352
4353 if (IsTypedefName) {
4354 // For typedefs, we do not infer any nullability (the default),
4355 // and we only complain about missing nullability specifiers on
4356 // inner pointers.
4357 complainAboutMissingNullability = CAMN_InnerPointers;
4358
4360 // Note that we allow but don't require nullability on dependent types.
4361 ++NumPointersRemaining;
4362 }
4363
4364 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4365 DeclaratorChunk &chunk = D.getTypeObject(i);
4366 switch (chunk.Kind) {
4370 break;
4371
4374 ++NumPointersRemaining;
4375 break;
4376
4379 continue;
4380
4382 ++NumPointersRemaining;
4383 continue;
4384 }
4385 }
4386 } else {
4387 bool isFunctionOrMethod = false;
4388 switch (auto context = state.getDeclarator().getContext()) {
4394 isFunctionOrMethod = true;
4395 [[fallthrough]];
4396
4398 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4399 complainAboutMissingNullability = CAMN_No;
4400 break;
4401 }
4402
4403 // Weak properties are inferred to be nullable.
4404 if (state.getDeclarator().isObjCWeakProperty()) {
4405 // Weak properties cannot be nonnull, and should not complain about
4406 // missing nullable attributes during completeness checks.
4407 complainAboutMissingNullability = CAMN_No;
4408 if (inAssumeNonNullRegion) {
4409 inferNullability = NullabilityKind::Nullable;
4410 }
4411 break;
4412 }
4413
4414 [[fallthrough]];
4415
4418 complainAboutMissingNullability = CAMN_Yes;
4419
4420 // Nullability inference depends on the type and declarator.
4421 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4422 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4423 case PointerDeclaratorKind::NonPointer:
4424 case PointerDeclaratorKind::MultiLevelPointer:
4425 // Cannot infer nullability.
4426 break;
4427
4428 case PointerDeclaratorKind::SingleLevelPointer:
4429 // Infer _Nonnull if we are in an assumes-nonnull region.
4430 if (inAssumeNonNullRegion) {
4431 complainAboutInferringWithinChunk = wrappingKind;
4432 inferNullability = NullabilityKind::NonNull;
4433 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4435 }
4436 break;
4437
4438 case PointerDeclaratorKind::CFErrorRefPointer:
4439 case PointerDeclaratorKind::NSErrorPointerPointer:
4440 // Within a function or method signature, infer _Nullable at both
4441 // levels.
4442 if (isFunctionOrMethod && inAssumeNonNullRegion)
4443 inferNullability = NullabilityKind::Nullable;
4444 break;
4445
4446 case PointerDeclaratorKind::MaybePointerToCFRef:
4447 if (isFunctionOrMethod) {
4448 // On pointer-to-pointer parameters marked cf_returns_retained or
4449 // cf_returns_not_retained, if the outer pointer is explicit then
4450 // infer the inner pointer as _Nullable.
4451 auto hasCFReturnsAttr =
4452 [](const ParsedAttributesView &AttrList) -> bool {
4453 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4454 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4455 };
4456 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4457 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4458 hasCFReturnsAttr(D.getAttributes()) ||
4459 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4460 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4461 inferNullability = NullabilityKind::Nullable;
4462 inferNullabilityInnerOnly = true;
4463 }
4464 }
4465 }
4466 break;
4467 }
4468 break;
4469 }
4470
4472 complainAboutMissingNullability = CAMN_Yes;
4473 break;
4474
4494 // Don't infer in these contexts.
4495 break;
4496 }
4497 }
4498
4499 // Local function that returns true if its argument looks like a va_list.
4500 auto isVaList = [&S](QualType T) -> bool {
4501 auto *typedefTy = T->getAs<TypedefType>();
4502 if (!typedefTy)
4503 return false;
4504 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4505 do {
4506 if (typedefTy->getDecl() == vaListTypedef)
4507 return true;
4508 if (auto *name = typedefTy->getDecl()->getIdentifier())
4509 if (name->isStr("va_list"))
4510 return true;
4511 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4512 } while (typedefTy);
4513 return false;
4514 };
4515
4516 // Local function that checks the nullability for a given pointer declarator.
4517 // Returns true if _Nonnull was inferred.
4518 auto inferPointerNullability =
4519 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4520 SourceLocation pointerEndLoc,
4521 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4522 // We've seen a pointer.
4523 if (NumPointersRemaining > 0)
4524 --NumPointersRemaining;
4525
4526 // If a nullability attribute is present, there's nothing to do.
4527 if (hasNullabilityAttr(attrs))
4528 return nullptr;
4529
4530 // If we're supposed to infer nullability, do so now.
4531 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4532 ParsedAttr::Form form =
4533 inferNullabilityCS
4534 ? ParsedAttr::Form::ContextSensitiveKeyword()
4535 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4536 false /*IsRegularKeywordAttribute*/);
4537 ParsedAttr *nullabilityAttr = Pool.create(
4538 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4539 nullptr, SourceLocation(), nullptr, 0, form);
4540
4541 attrs.addAtEnd(nullabilityAttr);
4542
4543 if (inferNullabilityCS) {
4544 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4545 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4546 }
4547
4548 if (pointerLoc.isValid() &&
4549 complainAboutInferringWithinChunk !=
4550 PointerWrappingDeclaratorKind::None) {
4551 auto Diag =
4552 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4553 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4555 }
4556
4557 if (inferNullabilityInnerOnly)
4558 inferNullabilityInnerOnlyComplete = true;
4559 return nullabilityAttr;
4560 }
4561
4562 // If we're supposed to complain about missing nullability, do so
4563 // now if it's truly missing.
4564 switch (complainAboutMissingNullability) {
4565 case CAMN_No:
4566 break;
4567
4568 case CAMN_InnerPointers:
4569 if (NumPointersRemaining == 0)
4570 break;
4571 [[fallthrough]];
4572
4573 case CAMN_Yes:
4574 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4575 }
4576 return nullptr;
4577 };
4578
4579 // If the type itself could have nullability but does not, infer pointer
4580 // nullability and perform consistency checking.
4581 if (S.CodeSynthesisContexts.empty()) {
4583 if (isVaList(T)) {
4584 // Record that we've seen a pointer, but do nothing else.
4585 if (NumPointersRemaining > 0)
4586 --NumPointersRemaining;
4587 } else {
4588 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4589 if (T->isBlockPointerType())
4590 pointerKind = SimplePointerKind::BlockPointer;
4591 else if (T->isMemberPointerType())
4592 pointerKind = SimplePointerKind::MemberPointer;
4593
4594 if (auto *attr = inferPointerNullability(
4595 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4596 D.getDeclSpec().getEndLoc(),
4597 D.getMutableDeclSpec().getAttributes(),
4598 D.getMutableDeclSpec().getAttributePool())) {
4599 T = state.getAttributedType(
4600 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4601 }
4602 }
4603 }
4604
4605 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
4606 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
4607 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4608 checkNullabilityConsistency(S, SimplePointerKind::Array,
4609 D.getDeclSpec().getTypeSpecTypeLoc());
4610 }
4611 }
4612
4613 bool ExpectNoDerefChunk =
4614 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4615
4616 // Walk the DeclTypeInfo, building the recursive type as we go.
4617 // DeclTypeInfos are ordered from the identifier out, which is
4618 // opposite of what we want :).
4619
4620 // Track if the produced type matches the structure of the declarator.
4621 // This is used later to decide if we can fill `TypeLoc` from
4622 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
4623 // an error by replacing the type with `int`.
4624 bool AreDeclaratorChunksValid = true;
4625 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4626 unsigned chunkIndex = e - i - 1;
4627 state.setCurrentChunkIndex(chunkIndex);
4628 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4629 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4630 switch (DeclType.Kind) {
4632 if (i == 0)
4634 T = S.BuildParenType(T);
4635 break;
4637 // If blocks are disabled, emit an error.
4638 if (!LangOpts.Blocks)
4639 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4640
4641 // Handle pointer nullability.
4642 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4643 DeclType.EndLoc, DeclType.getAttrs(),
4644 state.getDeclarator().getAttributePool());
4645
4646 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4647 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4648 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4649 // qualified with const.
4650 if (LangOpts.OpenCL)
4651 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4652 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4653 }
4654 break;
4656 // Verify that we're not building a pointer to pointer to function with
4657 // exception specification.
4658 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4659 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4660 D.setInvalidType(true);
4661 // Build the type anyway.
4662 }
4663
4664 // Handle pointer nullability
4665 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4666 DeclType.EndLoc, DeclType.getAttrs(),
4667 state.getDeclarator().getAttributePool());
4668
4669 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4670 T = Context.getObjCObjectPointerType(T);
4671 if (DeclType.Ptr.TypeQuals)
4672 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4673 break;
4674 }
4675
4676 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4677 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4678 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4679 if (LangOpts.OpenCL) {
4680 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4681 T->isBlockPointerType()) {
4682 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4683 D.setInvalidType(true);
4684 }
4685 }
4686
4687 T = S.BuildPointerType(T, DeclType.Loc, Name);
4688 if (DeclType.Ptr.TypeQuals)
4689 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4690 break;
4692 // Verify that we're not building a reference to pointer to function with
4693 // exception specification.
4694 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4695 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4696 D.setInvalidType(true);
4697 // Build the type anyway.
4698 }
4699 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4700
4701 if (DeclType.Ref.HasRestrict)
4703 break;
4704 }
4706 // Verify that we're not building an array of pointers to function with
4707 // exception specification.
4708 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4709 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4710 D.setInvalidType(true);
4711 // Build the type anyway.
4712 }
4713 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4714 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4716
4717 // Microsoft property fields can have multiple sizeless array chunks
4718 // (i.e. int x[][][]). Skip all of these except one to avoid creating
4719 // bad incomplete array types.
4720 if (chunkIndex != 0 && !ArraySize &&
4721 D.getDeclSpec().getAttributes().hasMSPropertyAttr()) {
4722 // This is a sizeless chunk. If the next is also, skip this one.
4723 DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1);
4724 if (NextDeclType.Kind == DeclaratorChunk::Array &&
4725 !NextDeclType.Arr.NumElts)
4726 break;
4727 }
4728
4729 if (ATI.isStar)
4731 else if (ATI.hasStatic)
4733 else
4735 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) {
4736 // FIXME: This check isn't quite right: it allows star in prototypes
4737 // for function definitions, and disallows some edge cases detailed
4738 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4739 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4741 D.setInvalidType(true);
4742 }
4743
4744 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4745 // shall appear only in a declaration of a function parameter with an
4746 // array type, ...
4747 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) {
4748 if (!(D.isPrototypeContext() ||
4749 D.getContext() == DeclaratorContext::KNRTypeList)) {
4750 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype)
4751 << (ASM == ArraySizeModifier::Static ? "'static'"
4752 : "type qualifier");
4753 // Remove the 'static' and the type qualifiers.
4754 if (ASM == ArraySizeModifier::Static)
4756 ATI.TypeQuals = 0;
4757 D.setInvalidType(true);
4758 }
4759
4760 // C99 6.7.5.2p1: ... and then only in the outermost array type
4761 // derivation.
4762 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4763 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost)
4764 << (ASM == ArraySizeModifier::Static ? "'static'"
4765 : "type qualifier");
4766 if (ASM == ArraySizeModifier::Static)
4768 ATI.TypeQuals = 0;
4769 D.setInvalidType(true);
4770 }
4771 }
4772
4773 // Array parameters can be marked nullable as well, although it's not
4774 // necessary if they're marked 'static'.
4775 if (complainAboutMissingNullability == CAMN_Yes &&
4776 !hasNullabilityAttr(DeclType.getAttrs()) &&
4777 ASM != ArraySizeModifier::Static && D.isPrototypeContext() &&
4778 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4779 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4780 }
4781
4782 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4783 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4784 break;
4785 }
4787 // If the function declarator has a prototype (i.e. it is not () and
4788 // does not have a K&R-style identifier list), then the arguments are part
4789 // of the type, otherwise the argument list is ().
4790 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4791 IsQualifiedFunction =
4793
4794 // Check for auto functions and trailing return type and adjust the
4795 // return type accordingly.
4796 if (!D.isInvalidType()) {
4797 auto IsClassType = [&](CXXScopeSpec &SS) {
4798 // If there already was an problem with the scope, don’t issue another
4799 // error about the explicit object parameter.
4800 return SS.isInvalid() ||
4801 isa_and_present<CXXRecordDecl>(S.computeDeclContext(SS));
4802 };
4803
4804 // C++23 [dcl.fct]p6:
4805 //
4806 // An explicit-object-parameter-declaration is a parameter-declaration
4807 // with a this specifier. An explicit-object-parameter-declaration shall
4808 // appear only as the first parameter-declaration of a
4809 // parameter-declaration-list of one of:
4810 //
4811 // - a declaration of a member function or member function template
4812 // ([class.mem]), or
4813 //
4814 // - an explicit instantiation ([temp.explicit]) or explicit
4815 // specialization ([temp.expl.spec]) of a templated member function,
4816 // or
4817 //
4818 // - a lambda-declarator [expr.prim.lambda].
4819 DeclaratorContext C = D.getContext();
4821 FTI.NumParams
4822 ? dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param)
4823 : nullptr;
4824
4825 bool IsFunctionDecl = D.getInnermostNonParenChunk() == &DeclType;
4826 if (First && First->isExplicitObjectParameter() &&
4828
4829 // Either not a member or nested declarator in a member.
4830 //
4831 // Note that e.g. 'static' or 'friend' declarations are accepted
4832 // here; we diagnose them later when we build the member function
4833 // because it's easier that way.
4834 (C != DeclaratorContext::Member || !IsFunctionDecl) &&
4835
4836 // Allow out-of-line definitions of member functions.
4837 !IsClassType(D.getCXXScopeSpec())) {
4838 if (IsFunctionDecl)
4839 S.Diag(First->getBeginLoc(),
4840 diag::err_explicit_object_parameter_nonmember)
4841 << /*non-member*/ 2 << /*function*/ 0
4842 << First->getSourceRange();
4843 else
4844 S.Diag(First->getBeginLoc(),
4845 diag::err_explicit_object_parameter_invalid)
4846 << First->getSourceRange();
4847
4848 D.setInvalidType();
4849 AreDeclaratorChunksValid = false;
4850 }
4851
4852 // trailing-return-type is only required if we're declaring a function,
4853 // and not, for instance, a pointer to a function.
4854 if (D.getDeclSpec().hasAutoTypeSpec() &&
4855 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4856 if (!S.getLangOpts().CPlusPlus14) {
4857 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4858 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4859 ? diag::err_auto_missing_trailing_return
4860 : diag::err_deduced_return_type);
4861 T = Context.IntTy;
4862 D.setInvalidType(true);
4863 AreDeclaratorChunksValid = false;
4864 } else {
4865 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4866 diag::warn_cxx11_compat_deduced_return_type);
4867 }
4868 } else if (FTI.hasTrailingReturnType()) {
4869 // T must be exactly 'auto' at this point. See CWG issue 681.
4870 if (isa<ParenType>(T)) {
4871 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4872 << T << D.getSourceRange();
4873 D.setInvalidType(true);
4874 // FIXME: recover and fill decls in `TypeLoc`s.
4875 AreDeclaratorChunksValid = false;
4876 } else if (D.getName().getKind() ==
4878 if (T != Context.DependentTy) {
4879 S.Diag(D.getDeclSpec().getBeginLoc(),
4880 diag::err_deduction_guide_with_complex_decl)
4881 << D.getSourceRange();
4882 D.setInvalidType(true);
4883 // FIXME: recover and fill decls in `TypeLoc`s.
4884 AreDeclaratorChunksValid = false;
4885 }
4886 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
4887 (T.hasQualifiers() || !isa<AutoType>(T) ||
4888 cast<AutoType>(T)->getKeyword() !=
4890 cast<AutoType>(T)->isConstrained())) {
4891 // Attach a valid source location for diagnostics on functions with
4892 // trailing return types missing 'auto'. Attempt to get the location
4893 // from the declared type; if invalid, fall back to the trailing
4894 // return type's location.
4895 SourceLocation Loc = D.getDeclSpec().getTypeSpecTypeLoc();
4896 SourceRange SR = D.getDeclSpec().getSourceRange();
4897 if (Loc.isInvalid()) {
4899 SR = D.getSourceRange();
4900 }
4901 S.Diag(Loc, diag::err_trailing_return_without_auto) << T << SR;
4902 D.setInvalidType(true);
4903 // FIXME: recover and fill decls in `TypeLoc`s.
4904 AreDeclaratorChunksValid = false;
4905 }
4906 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4907 if (T.isNull()) {
4908 // An error occurred parsing the trailing return type.
4909 T = Context.IntTy;
4910 D.setInvalidType(true);
4911 } else if (AutoType *Auto = T->getContainedAutoType()) {
4912 // If the trailing return type contains an `auto`, we may need to
4913 // invent a template parameter for it, for cases like
4914 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
4915 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
4916 if (D.getContext() == DeclaratorContext::Prototype)
4917 InventedParamInfo = &S.InventedParameterInfos.back();
4918 else if (D.getContext() == DeclaratorContext::LambdaExprParameter)
4919 InventedParamInfo = S.getCurLambda();
4920 if (InventedParamInfo) {
4921 std::tie(T, TInfo) = InventTemplateParameter(
4922 state, T, TInfo, Auto, *InventedParamInfo);
4923 }
4924 }
4925 } else {
4926 // This function type is not the type of the entity being declared,
4927 // so checking the 'auto' is not the responsibility of this chunk.
4928 }
4929 }
4930
4931 // C99 6.7.5.3p1: The return type may not be a function or array type.
4932 // For conversion functions, we'll diagnose this particular error later.
4933 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4934 (D.getName().getKind() !=
4936 unsigned diagID = diag::err_func_returning_array_function;
4937 // Last processing chunk in block context means this function chunk
4938 // represents the block.
4939 if (chunkIndex == 0 &&
4940 D.getContext() == DeclaratorContext::BlockLiteral)
4941 diagID = diag::err_block_returning_array_function;
4942 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4943 T = Context.IntTy;
4944 D.setInvalidType(true);
4945 AreDeclaratorChunksValid = false;
4946 }
4947
4948 // Do not allow returning half FP value.
4949 // FIXME: This really should be in BuildFunctionType.
4950 if (T->isHalfType()) {
4951 if (S.getLangOpts().OpenCL) {
4952 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
4953 S.getLangOpts())) {
4954 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4955 << T << 0 /*pointer hint*/;
4956 D.setInvalidType(true);
4957 }
4958 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
4960 S.Diag(D.getIdentifierLoc(),
4961 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4962 D.setInvalidType(true);
4963 }
4964 }
4965
4966 if (LangOpts.OpenCL) {
4967 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4968 // function.
4969 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4970 T->isPipeType()) {
4971 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4972 << T << 1 /*hint off*/;
4973 D.setInvalidType(true);
4974 }
4975 // OpenCL doesn't support variadic functions and blocks
4976 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4977 // We also allow here any toolchain reserved identifiers.
4978 if (FTI.isVariadic &&
4980 "__cl_clang_variadic_functions", S.getLangOpts()) &&
4981 !(D.getIdentifier() &&
4982 ((D.getIdentifier()->getName() == "printf" &&
4983 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
4984 D.getIdentifier()->getName().starts_with("__")))) {
4985 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4986 D.setInvalidType(true);
4987 }
4988 }
4989
4990 // Methods cannot return interface types. All ObjC objects are
4991 // passed by reference.
4992 if (T->isObjCObjectType()) {
4993 SourceLocation DiagLoc, FixitLoc;
4994 if (TInfo) {
4995 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
4996 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
4997 } else {
4998 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4999 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5000 }
5001 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5002 << 0 << T
5003 << FixItHint::CreateInsertion(FixitLoc, "*");
5004
5005 T = Context.getObjCObjectPointerType(T);
5006 if (TInfo) {
5007 TypeLocBuilder TLB;
5008 TLB.pushFullCopy(TInfo->getTypeLoc());
5010 TLoc.setStarLoc(FixitLoc);
5011 TInfo = TLB.getTypeSourceInfo(Context, T);
5012 } else {
5013 AreDeclaratorChunksValid = false;
5014 }
5015
5016 D.setInvalidType(true);
5017 }
5018
5019 // cv-qualifiers on return types are pointless except when the type is a
5020 // class type in C++.
5021 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5022 !(S.getLangOpts().CPlusPlus &&
5023 (T->isDependentType() || T->isRecordType()))) {
5024 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5025 D.getFunctionDefinitionKind() ==
5027 // [6.9.1/3] qualified void return is invalid on a C
5028 // function definition. Apparently ok on declarations and
5029 // in C++ though (!)
5030 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5031 } else
5032 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5033
5034 // C++2a [dcl.fct]p12:
5035 // A volatile-qualified return type is deprecated
5036 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5037 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5038 }
5039
5040 // Objective-C ARC ownership qualifiers are ignored on the function
5041 // return type (by type canonicalization). Complain if this attribute
5042 // was written here.
5043 if (T.getQualifiers().hasObjCLifetime()) {
5044 SourceLocation AttrLoc;
5045 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5046 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5047 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5048 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5049 AttrLoc = AL.getLoc();
5050 break;
5051 }
5052 }
5053 }
5054 if (AttrLoc.isInvalid()) {
5055 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5056 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5057 AttrLoc = AL.getLoc();
5058 break;
5059 }
5060 }
5061 }
5062
5063 if (AttrLoc.isValid()) {
5064 // The ownership attributes are almost always written via
5065 // the predefined
5066 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5067 if (AttrLoc.isMacroID())
5068 AttrLoc =
5070
5071 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5072 << T.getQualifiers().getObjCLifetime();
5073 }
5074 }
5075
5076 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5077 // C++ [dcl.fct]p6:
5078 // Types shall not be defined in return or parameter types.
5079 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5080 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5081 << Context.getTypeDeclType(Tag);
5082 }
5083
5084 // Exception specs are not allowed in typedefs. Complain, but add it
5085 // anyway.
5086 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5088 diag::err_exception_spec_in_typedef)
5089 << (D.getContext() == DeclaratorContext::AliasDecl ||
5090 D.getContext() == DeclaratorContext::AliasTemplate);
5091
5092 // If we see "T var();" or "T var(T());" at block scope, it is probably
5093 // an attempt to initialize a variable, not a function declaration.
5094 if (FTI.isAmbiguous)
5095 warnAboutAmbiguousFunction(S, D, DeclType, T);
5096
5098 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5099
5100 // OpenCL disallows functions without a prototype, but it doesn't enforce
5101 // strict prototypes as in C23 because it allows a function definition to
5102 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5103 if (!FTI.NumParams && !FTI.isVariadic &&
5104 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5105 // Simple void foo(), where the incoming T is the result type.
5106 T = Context.getFunctionNoProtoType(T, EI);
5107 } else {
5108 // We allow a zero-parameter variadic function in C if the
5109 // function is marked with the "overloadable" attribute. Scan
5110 // for this attribute now. We also allow it in C23 per WG14 N2975.
5111 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5112 if (LangOpts.C23)
5113 S.Diag(FTI.getEllipsisLoc(),
5114 diag::warn_c17_compat_ellipsis_only_parameter);
5115 else if (!D.getDeclarationAttributes().hasAttribute(
5116 ParsedAttr::AT_Overloadable) &&
5117 !D.getAttributes().hasAttribute(
5118 ParsedAttr::AT_Overloadable) &&
5119 !D.getDeclSpec().getAttributes().hasAttribute(
5120 ParsedAttr::AT_Overloadable))
5121 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5122 }
5123
5124 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5125 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5126 // definition.
5127 S.Diag(FTI.Params[0].IdentLoc,
5128 diag::err_ident_list_in_fn_declaration);
5129 D.setInvalidType(true);
5130 // Recover by creating a K&R-style function type, if possible.
5131 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5132 ? Context.getFunctionNoProtoType(T, EI)
5133 : Context.IntTy;
5134 AreDeclaratorChunksValid = false;
5135 break;
5136 }
5137
5139 EPI.ExtInfo = EI;
5140 EPI.Variadic = FTI.isVariadic;
5141 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5145 : 0);
5148 : RQ_RValue;
5149
5150 // Otherwise, we have a function with a parameter list that is
5151 // potentially variadic.
5153 ParamTys.reserve(FTI.NumParams);
5154
5156 ExtParameterInfos(FTI.NumParams);
5157 bool HasAnyInterestingExtParameterInfos = false;
5158
5159 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5160 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5161 QualType ParamTy = Param->getType();
5162 assert(!ParamTy.isNull() && "Couldn't parse type?");
5163
5164 // Look for 'void'. void is allowed only as a single parameter to a
5165 // function with no other parameters (C99 6.7.5.3p10). We record
5166 // int(void) as a FunctionProtoType with an empty parameter list.
5167 if (ParamTy->isVoidType()) {
5168 // If this is something like 'float(int, void)', reject it. 'void'
5169 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5170 // have parameters of incomplete type.
5171 if (FTI.NumParams != 1 || FTI.isVariadic) {
5172 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5173 ParamTy = Context.IntTy;
5174 Param->setType(ParamTy);
5175 } else if (FTI.Params[i].Ident) {
5176 // Reject, but continue to parse 'int(void abc)'.
5177 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5178 ParamTy = Context.IntTy;
5179 Param->setType(ParamTy);
5180 } else {
5181 // Reject, but continue to parse 'float(const void)'.
5182 if (ParamTy.hasQualifiers())
5183 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5184
5185 // Reject, but continue to parse 'float(this void)' as
5186 // 'float(void)'.
5187 if (Param->isExplicitObjectParameter()) {
5188 S.Diag(Param->getLocation(),
5189 diag::err_void_explicit_object_param);
5191 }
5192
5193 // Do not add 'void' to the list.
5194 break;
5195 }
5196 } else if (ParamTy->isHalfType()) {
5197 // Disallow half FP parameters.
5198 // FIXME: This really should be in BuildFunctionType.
5199 if (S.getLangOpts().OpenCL) {
5200 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5201 S.getLangOpts())) {
5202 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5203 << ParamTy << 0;
5204 D.setInvalidType();
5205 Param->setInvalidDecl();
5206 }
5207 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5209 S.Diag(Param->getLocation(),
5210 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5211 D.setInvalidType();
5212 }
5213 } else if (!FTI.hasPrototype) {
5214 if (Context.isPromotableIntegerType(ParamTy)) {
5215 ParamTy = Context.getPromotedIntegerType(ParamTy);
5216 Param->setKNRPromoted(true);
5217 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5218 if (BTy->getKind() == BuiltinType::Float) {
5219 ParamTy = Context.DoubleTy;
5220 Param->setKNRPromoted(true);
5221 }
5222 }
5223 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5224 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5225 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5226 << ParamTy << 1 /*hint off*/;
5227 D.setInvalidType();
5228 }
5229
5230 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5231 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5232 HasAnyInterestingExtParameterInfos = true;
5233 }
5234
5235 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5236 ExtParameterInfos[i] =
5237 ExtParameterInfos[i].withABI(attr->getABI());
5238 HasAnyInterestingExtParameterInfos = true;
5239 }
5240
5241 if (Param->hasAttr<PassObjectSizeAttr>()) {
5242 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5243 HasAnyInterestingExtParameterInfos = true;
5244 }
5245
5246 if (Param->hasAttr<NoEscapeAttr>()) {
5247 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5248 HasAnyInterestingExtParameterInfos = true;
5249 }
5250
5251 ParamTys.push_back(ParamTy);
5252 }
5253
5254 if (HasAnyInterestingExtParameterInfos) {
5255 EPI.ExtParameterInfos = ExtParameterInfos.data();
5256 checkExtParameterInfos(S, ParamTys, EPI,
5257 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5258 }
5259
5260 SmallVector<QualType, 4> Exceptions;
5261 SmallVector<ParsedType, 2> DynamicExceptions;
5262 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5263 Expr *NoexceptExpr = nullptr;
5264
5265 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5266 // FIXME: It's rather inefficient to have to split into two vectors
5267 // here.
5268 unsigned N = FTI.getNumExceptions();
5269 DynamicExceptions.reserve(N);
5270 DynamicExceptionRanges.reserve(N);
5271 for (unsigned I = 0; I != N; ++I) {
5272 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5273 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5274 }
5275 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5276 NoexceptExpr = FTI.NoexceptExpr;
5277 }
5278
5279 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
5281 DynamicExceptions,
5282 DynamicExceptionRanges,
5283 NoexceptExpr,
5284 Exceptions,
5285 EPI.ExceptionSpec);
5286
5287 // FIXME: Set address space from attrs for C++ mode here.
5288 // OpenCLCPlusPlus: A class member function has an address space.
5289 auto IsClassMember = [&]() {
5290 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5291 state.getDeclarator()
5292 .getCXXScopeSpec()
5293 .getScopeRep()
5294 ->getKind() == NestedNameSpecifier::TypeSpec) ||
5295 state.getDeclarator().getContext() ==
5297 state.getDeclarator().getContext() ==
5299 };
5300
5301 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5302 LangAS ASIdx = LangAS::Default;
5303 // Take address space attr if any and mark as invalid to avoid adding
5304 // them later while creating QualType.
5305 if (FTI.MethodQualifiers)
5307 LangAS ASIdxNew = attr.asOpenCLLangAS();
5308 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5309 attr.getLoc()))
5310 D.setInvalidType(true);
5311 else
5312 ASIdx = ASIdxNew;
5313 }
5314 // If a class member function's address space is not set, set it to
5315 // __generic.
5316 LangAS AS =
5318 : ASIdx);
5319 EPI.TypeQuals.addAddressSpace(AS);
5320 }
5321 T = Context.getFunctionType(T, ParamTys, EPI);
5322 }
5323 break;
5324 }
5326 // The scope spec must refer to a class, or be dependent.
5327 CXXScopeSpec &SS = DeclType.Mem.Scope();
5328 QualType ClsType;
5329
5330 // Handle pointer nullability.
5331 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5332 DeclType.EndLoc, DeclType.getAttrs(),
5333 state.getDeclarator().getAttributePool());
5334
5335 if (SS.isInvalid()) {
5336 // Avoid emitting extra errors if we already errored on the scope.
5337 D.setInvalidType(true);
5338 } else if (S.isDependentScopeSpecifier(SS) ||
5339 isa_and_nonnull<CXXRecordDecl>(S.computeDeclContext(SS))) {
5340 NestedNameSpecifier *NNS = SS.getScopeRep();
5341 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
5342 switch (NNS->getKind()) {
5344 ClsType = Context.getDependentNameType(
5345 ElaboratedTypeKeyword::None, NNSPrefix, NNS->getAsIdentifier());
5346 break;
5347
5352 llvm_unreachable("Nested-name-specifier must name a type");
5353
5356 const Type *NNSType = NNS->getAsType();
5357 ClsType = QualType(NNSType, 0);
5358 // Note: if the NNS has a prefix and ClsType is a nondependent
5359 // TemplateSpecializationType or a RecordType, then the NNS prefix is
5360 // NOT included in ClsType; hence we wrap ClsType into an
5361 // ElaboratedType. NOTE: in particular, no wrap occurs if ClsType
5362 // already is an Elaborated, DependentName, or
5363 // DependentTemplateSpecialization.
5364 if (isa<DependentTemplateSpecializationType>(NNSType)) {
5365 // FIXME: Rebuild DependentTemplateSpecializationType, adding the
5366 // Prefix.
5367 } else if (isa<TemplateSpecializationType, RecordType>(NNSType)) {
5368 // Either the dependent case (TemplateSpecializationType), or the
5369 // non-dependent one (RecordType).
5371 NNSPrefix, ClsType);
5372 }
5373 break;
5374 }
5375 } else {
5376 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
5377 diag::err_illegal_decl_mempointer_in_nonclass)
5378 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
5379 << DeclType.Mem.Scope().getRange();
5380 D.setInvalidType(true);
5381 }
5382
5383 if (!ClsType.isNull())
5384 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
5385 D.getIdentifier());
5386 else
5387 AreDeclaratorChunksValid = false;
5388
5389 if (T.isNull()) {
5390 T = Context.IntTy;
5391 D.setInvalidType(true);
5392 AreDeclaratorChunksValid = false;
5393 } else if (DeclType.Mem.TypeQuals) {
5394 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5395 }
5396 break;
5397 }
5398
5399 case DeclaratorChunk::Pipe: {
5400 T = S.BuildReadPipeType(T, DeclType.Loc);
5402 D.getMutableDeclSpec().getAttributes());
5403 break;
5404 }
5405 }
5406
5407 if (T.isNull()) {
5408 D.setInvalidType(true);
5409 T = Context.IntTy;
5410 AreDeclaratorChunksValid = false;
5411 }
5412
5413 // See if there are any attributes on this declarator chunk.
5414 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs(),
5415 S.CUDA().IdentifyTarget(D.getAttributes()));
5416
5417 if (DeclType.Kind != DeclaratorChunk::Paren) {
5418 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5419 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5420
5421 ExpectNoDerefChunk = state.didParseNoDeref();
5422 }
5423 }
5424
5425 if (ExpectNoDerefChunk)
5426 S.Diag(state.getDeclarator().getBeginLoc(),
5427 diag::warn_noderef_on_non_pointer_or_array);
5428
5429 // GNU warning -Wstrict-prototypes
5430 // Warn if a function declaration or definition is without a prototype.
5431 // This warning is issued for all kinds of unprototyped function
5432 // declarations (i.e. function type typedef, function pointer etc.)
5433 // C99 6.7.5.3p14:
5434 // The empty list in a function declarator that is not part of a definition
5435 // of that function specifies that no information about the number or types
5436 // of the parameters is supplied.
5437 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5438 // function declarations whose behavior changes in C23.
5439 if (!LangOpts.requiresStrictPrototypes()) {
5440 bool IsBlock = false;
5441 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5442 switch (DeclType.Kind) {
5444 IsBlock = true;
5445 break;
5447 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5448 // We suppress the warning when there's no LParen location, as this
5449 // indicates the declaration was an implicit declaration, which gets
5450 // warned about separately via -Wimplicit-function-declaration. We also
5451 // suppress the warning when we know the function has a prototype.
5452 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5453 FTI.getLParenLoc().isValid())
5454 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5455 << IsBlock
5456 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5457 IsBlock = false;
5458 break;
5459 }
5460 default:
5461 break;
5462 }
5463 }
5464 }
5465
5466 assert(!T.isNull() && "T must not be null after this point");
5467
5468 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5469 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5470 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5471
5472 // C++ 8.3.5p4:
5473 // A cv-qualifier-seq shall only be part of the function type
5474 // for a nonstatic member function, the function type to which a pointer
5475 // to member refers, or the top-level function type of a function typedef
5476 // declaration.
5477 //
5478 // Core issue 547 also allows cv-qualifiers on function types that are
5479 // top-level template type arguments.
5480 enum {
5481 NonMember,
5482 Member,
5483 ExplicitObjectMember,
5484 DeductionGuide
5485 } Kind = NonMember;
5487 Kind = DeductionGuide;
5488 else if (!D.getCXXScopeSpec().isSet()) {
5489 if ((D.getContext() == DeclaratorContext::Member ||
5490 D.getContext() == DeclaratorContext::LambdaExpr) &&
5491 !D.getDeclSpec().isFriendSpecified())
5492 Kind = Member;
5493 } else {
5494 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
5495 if (!DC || DC->isRecord())
5496 Kind = Member;
5497 }
5498
5499 if (Kind == Member) {
5500 unsigned I;
5501 if (D.isFunctionDeclarator(I)) {
5502 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5503 if (Chunk.Fun.NumParams) {
5504 auto *P = dyn_cast_or_null<ParmVarDecl>(Chunk.Fun.Params->Param);
5505 if (P && P->isExplicitObjectParameter())
5506 Kind = ExplicitObjectMember;
5507 }
5508 }
5509 }
5510
5511 // C++11 [dcl.fct]p6 (w/DR1417):
5512 // An attempt to specify a function type with a cv-qualifier-seq or a
5513 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5514 // - the function type for a non-static member function,
5515 // - the function type to which a pointer to member refers,
5516 // - the top-level function type of a function typedef declaration or
5517 // alias-declaration,
5518 // - the type-id in the default argument of a type-parameter, or
5519 // - the type-id of a template-argument for a type-parameter
5520 //
5521 // C++23 [dcl.fct]p6 (P0847R7)
5522 // ... A member-declarator with an explicit-object-parameter-declaration
5523 // shall not include a ref-qualifier or a cv-qualifier-seq and shall not be
5524 // declared static or virtual ...
5525 //
5526 // FIXME: Checking this here is insufficient. We accept-invalid on:
5527 //
5528 // template<typename T> struct S { void f(T); };
5529 // S<int() const> s;
5530 //
5531 // ... for instance.
5532 if (IsQualifiedFunction &&
5533 // Check for non-static member function and not and
5534 // explicit-object-parameter-declaration
5535 (Kind != Member || D.isExplicitObjectMemberFunction() ||
5536 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
5537 (D.getContext() == clang::DeclaratorContext::Member &&
5538 D.isStaticMember())) &&
5539 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5540 D.getContext() != DeclaratorContext::TemplateTypeArg) {
5542 SourceRange RemovalRange;
5543 unsigned I;
5544 if (D.isFunctionDeclarator(I)) {
5546 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5547 assert(Chunk.Kind == DeclaratorChunk::Function);
5548
5549 if (Chunk.Fun.hasRefQualifier())
5550 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5551
5552 if (Chunk.Fun.hasMethodTypeQualifiers())
5554 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5555 SourceLocation SL) { RemovalLocs.push_back(SL); });
5556
5557 if (!RemovalLocs.empty()) {
5558 llvm::sort(RemovalLocs,
5560 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5561 Loc = RemovalLocs.front();
5562 }
5563 }
5564
5565 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5566 << Kind << D.isFunctionDeclarator() << T
5568 << FixItHint::CreateRemoval(RemovalRange);
5569
5570 // Strip the cv-qualifiers and ref-qualifiers from the type.
5573 EPI.RefQualifier = RQ_None;
5574
5575 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5576 EPI);
5577 // Rebuild any parens around the identifier in the function type.
5578 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5579 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5580 break;
5581 T = S.BuildParenType(T);
5582 }
5583 }
5584 }
5585
5586 // Apply any undistributed attributes from the declaration or declarator.
5587 ParsedAttributesView NonSlidingAttrs;
5588 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5589 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5590 NonSlidingAttrs.addAtEnd(&AL);
5591 }
5592 }
5593 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5594 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5595
5596 // Diagnose any ignored type attributes.
5597 state.diagnoseIgnoredTypeAttrs(T);
5598
5599 // C++0x [dcl.constexpr]p9:
5600 // A constexpr specifier used in an object declaration declares the object
5601 // as const.
5602 if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr &&
5603 T->isObjectType())
5604 T.addConst();
5605
5606 // C++2a [dcl.fct]p4:
5607 // A parameter with volatile-qualified type is deprecated
5608 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5609 (D.getContext() == DeclaratorContext::Prototype ||
5611 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5612
5613 // If there was an ellipsis in the declarator, the declaration declares a
5614 // parameter pack whose type may be a pack expansion type.
5615 if (D.hasEllipsis()) {
5616 // C++0x [dcl.fct]p13:
5617 // A declarator-id or abstract-declarator containing an ellipsis shall
5618 // only be used in a parameter-declaration. Such a parameter-declaration
5619 // is a parameter pack (14.5.3). [...]
5620 switch (D.getContext()) {
5624 // C++0x [dcl.fct]p13:
5625 // [...] When it is part of a parameter-declaration-clause, the
5626 // parameter pack is a function parameter pack (14.5.3). The type T
5627 // of the declarator-id of the function parameter pack shall contain
5628 // a template parameter pack; each template parameter pack in T is
5629 // expanded by the function parameter pack.
5630 //
5631 // We represent function parameter packs as function parameters whose
5632 // type is a pack expansion.
5634 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5635 S.Diag(D.getEllipsisLoc(),
5636 diag::err_function_parameter_pack_without_parameter_packs)
5637 << T << D.getSourceRange();
5638 D.setEllipsisLoc(SourceLocation());
5639 } else {
5640 T = Context.getPackExpansionType(T, std::nullopt,
5641 /*ExpectPackInType=*/false);
5642 }
5643 break;
5645 // C++0x [temp.param]p15:
5646 // If a template-parameter is a [...] is a parameter-declaration that
5647 // declares a parameter pack (8.3.5), then the template-parameter is a
5648 // template parameter pack (14.5.3).
5649 //
5650 // Note: core issue 778 clarifies that, if there are any unexpanded
5651 // parameter packs in the type of the non-type template parameter, then
5652 // it expands those parameter packs.
5654 T = Context.getPackExpansionType(T, std::nullopt);
5655 else
5656 S.Diag(D.getEllipsisLoc(),
5657 LangOpts.CPlusPlus11
5658 ? diag::warn_cxx98_compat_variadic_templates
5659 : diag::ext_variadic_templates);
5660 break;
5661
5664 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5665 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
5686 // FIXME: We may want to allow parameter packs in block-literal contexts
5687 // in the future.
5688 S.Diag(D.getEllipsisLoc(),
5689 diag::err_ellipsis_in_declarator_not_parameter);
5690 D.setEllipsisLoc(SourceLocation());
5691 break;
5692 }
5693 }
5694
5695 assert(!T.isNull() && "T must not be null at the end of this function");
5696 if (!AreDeclaratorChunksValid)
5697 return Context.getTrivialTypeSourceInfo(T);
5698
5699 if (state.didParseHLSLParamMod() && !T->isConstantArrayType())
5701 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5702}
5703
5705 // Determine the type of the declarator. Not all forms of declarator
5706 // have a type.
5707
5708 TypeProcessingState state(*this, D);
5709
5710 TypeSourceInfo *ReturnTypeInfo = nullptr;
5711 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5712 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5713 inferARCWriteback(state, T);
5714
5715 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5716}
5717
5719 QualType &declSpecTy,
5720 Qualifiers::ObjCLifetime ownership) {
5721 if (declSpecTy->isObjCRetainableType() &&
5722 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5723 Qualifiers qs;
5724 qs.addObjCLifetime(ownership);
5725 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5726 }
5727}
5728
5729static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5730 Qualifiers::ObjCLifetime ownership,
5731 unsigned chunkIndex) {
5732 Sema &S = state.getSema();
5733 Declarator &D = state.getDeclarator();
5734
5735 // Look for an explicit lifetime attribute.
5736 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5737 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5738 return;
5739
5740 const char *attrStr = nullptr;
5741 switch (ownership) {
5742 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5743 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5744 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5745 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5746 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5747 }
5748
5749 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5750 Arg->Ident = &S.Context.Idents.get(attrStr);
5751 Arg->Loc = SourceLocation();
5752
5753 ArgsUnion Args(Arg);
5754
5755 // If there wasn't one, add one (with an invalid source location
5756 // so that we don't make an AttributedType for it).
5757 ParsedAttr *attr = D.getAttributePool().create(
5758 &S.Context.Idents.get("objc_ownership"), SourceLocation(),
5759 /*scope*/ nullptr, SourceLocation(),
5760 /*args*/ &Args, 1, ParsedAttr::Form::GNU());
5761 chunk.getAttrs().addAtEnd(attr);
5762 // TODO: mark whether we did this inference?
5763}
5764
5765/// Used for transferring ownership in casts resulting in l-values.
5766static void transferARCOwnership(TypeProcessingState &state,
5767 QualType &declSpecTy,
5768 Qualifiers::ObjCLifetime ownership) {
5769 Sema &S = state.getSema();
5770 Declarator &D = state.getDeclarator();
5771
5772 int inner = -1;
5773 bool hasIndirection = false;
5774 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5775 DeclaratorChunk &chunk = D.getTypeObject(i);
5776 switch (chunk.Kind) {
5778 // Ignore parens.
5779 break;
5780
5784 if (inner != -1)
5785 hasIndirection = true;
5786 inner = i;
5787 break;
5788
5790 if (inner != -1)
5791 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5792 return;
5793
5797 return;
5798 }
5799 }
5800
5801 if (inner == -1)
5802 return;
5803
5804 DeclaratorChunk &chunk = D.getTypeObject(inner);
5805 if (chunk.Kind == DeclaratorChunk::Pointer) {
5806 if (declSpecTy->isObjCRetainableType())
5807 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5808 if (declSpecTy->isObjCObjectType() && hasIndirection)
5809 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5810 } else {
5811 assert(chunk.Kind == DeclaratorChunk::Array ||
5813 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5814 }
5815}
5816
5818 TypeProcessingState state(*this, D);
5819
5820 TypeSourceInfo *ReturnTypeInfo = nullptr;
5821 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5822
5823 if (getLangOpts().ObjC) {
5825 if (ownership != Qualifiers::OCL_None)
5826 transferARCOwnership(state, declSpecTy, ownership);
5827 }
5828
5829 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5830}
5831
5833 TypeProcessingState &State) {
5834 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5835}
5836
5838 TypeProcessingState &State) {
5840 State.getSema().HLSL().TakeLocForHLSLAttribute(TL.getTypePtr());
5841 TL.setSourceRange(LocInfo.Range);
5843}
5844
5846 const ParsedAttributesView &Attrs) {
5847 for (const ParsedAttr &AL : Attrs) {
5848 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
5849 MTL.setAttrNameLoc(AL.getLoc());
5850 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
5851 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
5853 return;
5854 }
5855 }
5856
5857 llvm_unreachable("no matrix_type attribute found at the expected location!");
5858}
5859
5860static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5862 switch (Chunk.Kind) {
5867 llvm_unreachable("cannot be _Atomic qualified");
5868
5870 Loc = Chunk.Ptr.AtomicQualLoc;
5871 break;
5872
5876 // FIXME: Provide a source location for the _Atomic keyword.
5877 break;
5878 }
5879
5880 ATL.setKWLoc(Loc);
5882}
5883
5884namespace {
5885 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5886 Sema &SemaRef;
5887 ASTContext &Context;
5888 TypeProcessingState &State;
5889 const DeclSpec &DS;
5890
5891 public:
5892 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
5893 const DeclSpec &DS)
5894 : SemaRef(S), Context(Context), State(State), DS(DS) {}
5895
5896 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5897 Visit(TL.getModifiedLoc());
5898 fillAttributedTypeLoc(TL, State);
5899 }
5900 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
5901 Visit(TL.getWrappedLoc());
5902 }
5903 void VisitHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL) {
5904 Visit(TL.getWrappedLoc());
5906 }
5907 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5908 Visit(TL.getInnerLoc());
5909 TL.setExpansionLoc(
5910 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5911 }
5912 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5913 Visit(TL.getUnqualifiedLoc());
5914 }
5915 // Allow to fill pointee's type locations, e.g.,
5916 // int __attr * __attr * __attr *p;
5917 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
5918 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5920 }
5921 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5923 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5924 // addition field. What we have is good enough for display of location
5925 // of 'fixit' on interface name.
5926 TL.setNameEndLoc(DS.getEndLoc());
5927 }
5928 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5929 TypeSourceInfo *RepTInfo = nullptr;
5930 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5931 TL.copy(RepTInfo->getTypeLoc());
5932 }
5933 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5934 TypeSourceInfo *RepTInfo = nullptr;
5935 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5936 TL.copy(RepTInfo->getTypeLoc());
5937 }
5938 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5939 TypeSourceInfo *TInfo = nullptr;
5941
5942 // If we got no declarator info from previous Sema routines,
5943 // just fill with the typespec loc.
5944 if (!TInfo) {
5945 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5946 return;
5947 }
5948
5949 TypeLoc OldTL = TInfo->getTypeLoc();
5950 if (TInfo->getType()->getAs<ElaboratedType>()) {
5951 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5954 TL.copy(NamedTL);
5955 } else {
5958 }
5959
5960 }
5961 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5966 }
5967 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5972 assert(DS.getRepAsType());
5973 TypeSourceInfo *TInfo = nullptr;
5975 TL.setUnmodifiedTInfo(TInfo);
5976 }
5977 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5981 }
5982 void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
5985 }
5986 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5987 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
5990 assert(DS.getRepAsType());
5991 TypeSourceInfo *TInfo = nullptr;
5993 TL.setUnderlyingTInfo(TInfo);
5994 }
5995 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5996 // By default, use the source location of the type specifier.
5998 if (TL.needsExtraLocalData()) {
5999 // Set info for the written builtin specifiers.
6001 // Try to have a meaningful source location.
6002 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6004 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6006 }
6007 }
6008 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6009 if (DS.getTypeSpecType() == TST_typename) {
6010 TypeSourceInfo *TInfo = nullptr;
6012 if (TInfo)
6013 if (auto ETL = TInfo->getTypeLoc().getAs<ElaboratedTypeLoc>()) {
6014 TL.copy(ETL);
6015 return;
6016 }
6017 }
6018 const ElaboratedType *T = TL.getTypePtr();
6019 TL.setElaboratedKeywordLoc(T->getKeyword() != ElaboratedTypeKeyword::None
6020 ? DS.getTypeSpecTypeLoc()
6021 : SourceLocation());
6022 const CXXScopeSpec& SS = DS.getTypeSpecScope();
6023 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6024 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
6025 }
6026 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6027 assert(DS.getTypeSpecType() == TST_typename);
6028 TypeSourceInfo *TInfo = nullptr;
6030 assert(TInfo);
6032 }
6033 void VisitDependentTemplateSpecializationTypeLoc(
6035 assert(DS.getTypeSpecType() == TST_typename);
6036 TypeSourceInfo *TInfo = nullptr;
6038 assert(TInfo);
6039 TL.copy(
6041 }
6042 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6043 assert(DS.getTypeSpecType() == TST_auto ||
6050 if (!DS.isConstrainedAuto())
6051 return;
6052 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6053 if (!TemplateId)
6054 return;
6055
6060 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6061 TemplateId->RAngleLoc);
6062 if (TemplateId->NumArgs > 0) {
6063 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6064 TemplateId->NumArgs);
6065 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6066 }
6069 TemplateId->TemplateNameLoc);
6070
6071 NamedDecl *FoundDecl;
6072 if (auto TN = TemplateId->Template.get();
6073 UsingShadowDecl *USD = TN.getAsUsingShadowDecl())
6074 FoundDecl = cast<NamedDecl>(USD);
6075 else
6076 FoundDecl = cast_if_present<NamedDecl>(TN.getAsTemplateDecl());
6077
6078 auto *CR = ConceptReference::Create(
6079 Context, NNS, TemplateId->TemplateKWLoc, DNI, FoundDecl,
6080 /*NamedDecl=*/TL.getTypePtr()->getTypeConstraintConcept(),
6081 ASTTemplateArgumentListInfo::Create(Context, TemplateArgsInfo));
6082 TL.setConceptReference(CR);
6083 }
6084 void VisitTagTypeLoc(TagTypeLoc TL) {
6086 }
6087 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6088 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6089 // or an _Atomic qualifier.
6093
6094 TypeSourceInfo *TInfo = nullptr;
6096 assert(TInfo);
6098 } else {
6099 TL.setKWLoc(DS.getAtomicSpecLoc());
6100 // No parens, to indicate this was spelled as an _Atomic qualifier.
6102 Visit(TL.getValueLoc());
6103 }
6104 }
6105
6106 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6108
6109 TypeSourceInfo *TInfo = nullptr;
6112 }
6113
6114 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6116 }
6117
6118 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6120 }
6121
6122 void VisitTypeLoc(TypeLoc TL) {
6123 // FIXME: add other typespec types and change this to an assert.
6124 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6125 }
6126 };
6127
6128 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6129 ASTContext &Context;
6130 TypeProcessingState &State;
6131 const DeclaratorChunk &Chunk;
6132
6133 public:
6134 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6135 const DeclaratorChunk &Chunk)
6136 : Context(Context), State(State), Chunk(Chunk) {}
6137
6138 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6139 llvm_unreachable("qualified type locs not expected here!");
6140 }
6141 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6142 llvm_unreachable("decayed type locs not expected here!");
6143 }
6144 void VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6145 llvm_unreachable("array parameter type locs not expected here!");
6146 }
6147
6148 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6149 fillAttributedTypeLoc(TL, State);
6150 }
6151 void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
6152 // nothing
6153 }
6154 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6155 // nothing
6156 }
6157 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6158 // nothing
6159 }
6160 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6161 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6162 TL.setCaretLoc(Chunk.Loc);
6163 }
6164 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6165 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6166 TL.setStarLoc(Chunk.Loc);
6167 }
6168 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6169 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6170 TL.setStarLoc(Chunk.Loc);
6171 }
6172 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6173 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6174 const CXXScopeSpec& SS = Chunk.Mem.Scope();
6175 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
6176
6177 const Type* ClsTy = TL.getClass();
6178 QualType ClsQT = QualType(ClsTy, 0);
6179 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
6180 // Now copy source location info into the type loc component.
6181 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
6182 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
6184 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
6185 {
6188 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
6189 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
6190 }
6191 break;
6192
6195 if (isa<ElaboratedType>(ClsTy)) {
6198 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
6199 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
6200 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
6201 } else {
6202 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
6203 }
6204 break;
6205
6210 llvm_unreachable("Nested-name-specifier must name a type");
6211 }
6212
6213 // Finally fill in MemberPointerLocInfo fields.
6214 TL.setStarLoc(Chunk.Mem.StarLoc);
6215 TL.setClassTInfo(ClsTInfo);
6216 }
6217 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6218 assert(Chunk.Kind == DeclaratorChunk::Reference);
6219 // 'Amp' is misleading: this might have been originally
6220 /// spelled with AmpAmp.
6221 TL.setAmpLoc(Chunk.Loc);
6222 }
6223 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6224 assert(Chunk.Kind == DeclaratorChunk::Reference);
6225 assert(!Chunk.Ref.LValueRef);
6226 TL.setAmpAmpLoc(Chunk.Loc);
6227 }
6228 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6229 assert(Chunk.Kind == DeclaratorChunk::Array);
6230 TL.setLBracketLoc(Chunk.Loc);
6231 TL.setRBracketLoc(Chunk.EndLoc);
6232 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6233 }
6234 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6235 assert(Chunk.Kind == DeclaratorChunk::Function);
6236 TL.setLocalRangeBegin(Chunk.Loc);
6237 TL.setLocalRangeEnd(Chunk.EndLoc);
6238
6239 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6240 TL.setLParenLoc(FTI.getLParenLoc());
6241 TL.setRParenLoc(FTI.getRParenLoc());
6242 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6243 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6244 TL.setParam(tpi++, Param);
6245 }
6247 }
6248 void VisitParenTypeLoc(ParenTypeLoc TL) {
6249 assert(Chunk.Kind == DeclaratorChunk::Paren);
6250 TL.setLParenLoc(Chunk.Loc);
6251 TL.setRParenLoc(Chunk.EndLoc);
6252 }
6253 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6254 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6255 TL.setKWLoc(Chunk.Loc);
6256 }
6257 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6258 TL.setNameLoc(Chunk.Loc);
6259 }
6260 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6261 TL.setExpansionLoc(Chunk.Loc);
6262 }
6263 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6264 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6265 TL.setNameLoc(Chunk.Loc);
6266 }
6267 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6268 TL.setNameLoc(Chunk.Loc);
6269 }
6270 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6271 fillAtomicQualLoc(TL, Chunk);
6272 }
6273 void
6274 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6275 TL.setNameLoc(Chunk.Loc);
6276 }
6277 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6278 fillMatrixTypeLoc(TL, Chunk.getAttrs());
6279 }
6280
6281 void VisitTypeLoc(TypeLoc TL) {
6282 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6283 }
6284 };
6285} // end anonymous namespace
6286
6287static void
6289 const ParsedAttributesView &Attrs) {
6290 for (const ParsedAttr &AL : Attrs) {
6291 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6292 DASTL.setAttrNameLoc(AL.getLoc());
6293 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6295 return;
6296 }
6297 }
6298
6299 llvm_unreachable(
6300 "no address_space attribute found at the expected location!");
6301}
6302
6303/// Create and instantiate a TypeSourceInfo with type source information.
6304///
6305/// \param T QualType referring to the type as written in source code.
6306///
6307/// \param ReturnTypeInfo For declarators whose return type does not show
6308/// up in the normal place in the declaration specifiers (such as a C++
6309/// conversion function), this pointer will refer to a type source information
6310/// for that return type.
6311static TypeSourceInfo *
6312GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6313 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6314 Sema &S = State.getSema();
6315 Declarator &D = State.getDeclarator();
6316
6318 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6319
6320 // Handle parameter packs whose type is a pack expansion.
6321 if (isa<PackExpansionType>(T)) {
6322 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6323 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6324 }
6325
6326 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6327 // Microsoft property fields can have multiple sizeless array chunks
6328 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6329 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6330 D.getDeclSpec().getAttributes().hasMSPropertyAttr())
6331 continue;
6332
6333 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6334 // declarator chunk.
6335 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6336 fillAtomicQualLoc(ATL, D.getTypeObject(i));
6337 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6338 }
6339
6340 bool HasDesugaredTypeLoc = true;
6341 while (HasDesugaredTypeLoc) {
6342 switch (CurrTL.getTypeLocClass()) {
6343 case TypeLoc::MacroQualified: {
6344 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6345 TL.setExpansionLoc(
6346 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6347 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6348 break;
6349 }
6350
6351 case TypeLoc::Attributed: {
6352 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6353 fillAttributedTypeLoc(TL, State);
6354 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6355 break;
6356 }
6357
6358 case TypeLoc::Adjusted:
6359 case TypeLoc::BTFTagAttributed: {
6360 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6361 break;
6362 }
6363
6364 case TypeLoc::DependentAddressSpace: {
6365 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6366 fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
6367 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6368 break;
6369 }
6370
6371 default:
6372 HasDesugaredTypeLoc = false;
6373 break;
6374 }
6375 }
6376
6377 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6378 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6379 }
6380
6381 // If we have different source information for the return type, use
6382 // that. This really only applies to C++ conversion functions.
6383 if (ReturnTypeInfo) {
6384 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6385 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6386 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6387 } else {
6388 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6389 }
6390
6391 return TInfo;
6392}
6393
6394/// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6396 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6397 // and Sema during declaration parsing. Try deallocating/caching them when
6398 // it's appropriate, instead of allocating them and keeping them around.
6399 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(sizeof(LocInfoType),
6400 alignof(LocInfoType));
6401 new (LocT) LocInfoType(T, TInfo);
6402 assert(LocT->getTypeClass() != T->getTypeClass() &&
6403 "LocInfoType's TypeClass conflicts with an existing Type class");
6404 return ParsedType::make(QualType(LocT, 0));
6405}
6406
6408 const PrintingPolicy &Policy) const {
6409 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6410 " was used directly instead of getting the QualType through"
6411 " GetTypeFromParser");
6412}
6413
6415 // C99 6.7.6: Type names have no identifier. This is already validated by
6416 // the parser.
6417 assert(D.getIdentifier() == nullptr &&
6418 "Type name should have no identifier!");
6419
6421 QualType T = TInfo->getType();
6422 if (D.isInvalidType())
6423 return true;
6424
6425 // Make sure there are no unused decl attributes on the declarator.
6426 // We don't want to do this for ObjC parameters because we're going
6427 // to apply them to the actual parameter declaration.
6428 // Likewise, we don't want to do this for alias declarations, because
6429 // we are actually going to build a declaration from this eventually.
6430 if (D.getContext() != DeclaratorContext::ObjCParameter &&
6431 D.getContext() != DeclaratorContext::AliasDecl &&
6432 D.getContext() != DeclaratorContext::AliasTemplate)
6434
6435 if (getLangOpts().CPlusPlus) {
6436 // Check that there are no default arguments (C++ only).
6438 }
6439
6440 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
6441 const AutoType *AT = TL.getTypePtr();
6442 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
6443 }
6444 return CreateParsedType(T, TInfo);
6445}
6446
6447//===----------------------------------------------------------------------===//
6448// Type Attribute Processing
6449//===----------------------------------------------------------------------===//
6450
6451/// Build an AddressSpace index from a constant expression and diagnose any
6452/// errors related to invalid address_spaces. Returns true on successfully
6453/// building an AddressSpace index.
6454static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6455 const Expr *AddrSpace,
6456 SourceLocation AttrLoc) {
6457 if (!AddrSpace->isValueDependent()) {
6458 std::optional<llvm::APSInt> OptAddrSpace =
6459 AddrSpace->getIntegerConstantExpr(S.Context);
6460 if (!OptAddrSpace) {
6461 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6462 << "'address_space'" << AANT_ArgumentIntegerConstant
6463 << AddrSpace->getSourceRange();
6464 return false;
6465 }
6466 llvm::APSInt &addrSpace = *OptAddrSpace;
6467
6468 // Bounds checking.
6469 if (addrSpace.isSigned()) {
6470 if (addrSpace.isNegative()) {
6471 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6472 << AddrSpace->getSourceRange();
6473 return false;
6474 }
6475 addrSpace.setIsSigned(false);
6476 }
6477
6478 llvm::APSInt max(addrSpace.getBitWidth());
6479 max =
6481
6482 if (addrSpace > max) {
6483 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6484 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6485 return false;
6486 }
6487
6488 ASIdx =
6489 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6490 return true;
6491 }
6492
6493 // Default value for DependentAddressSpaceTypes
6494 ASIdx = LangAS::Default;
6495 return true;
6496}
6497
6499 SourceLocation AttrLoc) {
6500 if (!AddrSpace->isValueDependent()) {
6501 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6502 AttrLoc))
6503 return QualType();
6504
6505 return Context.getAddrSpaceQualType(T, ASIdx);
6506 }
6507
6508 // A check with similar intentions as checking if a type already has an
6509 // address space except for on a dependent types, basically if the
6510 // current type is already a DependentAddressSpaceType then its already
6511 // lined up to have another address space on it and we can't have
6512 // multiple address spaces on the one pointer indirection
6514 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6515 return QualType();
6516 }
6517
6518 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6519}
6520
6522 SourceLocation AttrLoc) {
6523 LangAS ASIdx;
6524 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6525 return QualType();
6526 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6527}
6528
6530 TypeProcessingState &State) {
6531 Sema &S = State.getSema();
6532
6533 // This attribute is only supported in C.
6534 // FIXME: we should implement checkCommonAttributeFeatures() in SemaAttr.cpp
6535 // such that it handles type attributes, and then call that from
6536 // processTypeAttrs() instead of one-off checks like this.
6537 if (!Attr.diagnoseLangOpts(S)) {
6538 Attr.setInvalid();
6539 return;
6540 }
6541
6542 // Check the number of attribute arguments.
6543 if (Attr.getNumArgs() != 1) {
6544 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6545 << Attr << 1;
6546 Attr.setInvalid();
6547 return;
6548 }
6549
6550 // Ensure the argument is a string.
6551 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6552 if (!StrLiteral) {
6553 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6555 Attr.setInvalid();
6556 return;
6557 }
6558
6559 ASTContext &Ctx = S.Context;
6560 StringRef BTFTypeTag = StrLiteral->getString();
6561 Type = State.getBTFTagAttributedType(
6562 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6563}
6564
6565/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6566/// specified type. The attribute contains 1 argument, the id of the address
6567/// space for the type.
6569 const ParsedAttr &Attr,
6570 TypeProcessingState &State) {
6571 Sema &S = State.getSema();
6572
6573 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6574 // qualified by an address-space qualifier."
6575 if (Type->isFunctionType()) {
6576 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6577 Attr.setInvalid();
6578 return;
6579 }
6580
6581 LangAS ASIdx;
6582 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6583
6584 // Check the attribute arguments.
6585 if (Attr.getNumArgs() != 1) {
6586 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6587 << 1;
6588 Attr.setInvalid();
6589 return;
6590 }
6591
6592 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6593 LangAS ASIdx;
6594 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6595 Attr.setInvalid();
6596 return;
6597 }
6598
6599 ASTContext &Ctx = S.Context;
6600 auto *ASAttr =
6601 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6602
6603 // If the expression is not value dependent (not templated), then we can
6604 // apply the address space qualifiers just to the equivalent type.
6605 // Otherwise, we make an AttributedType with the modified and equivalent
6606 // type the same, and wrap it in a DependentAddressSpaceType. When this
6607 // dependent type is resolved, the qualifier is added to the equivalent type
6608 // later.
6609 QualType T;
6610 if (!ASArgExpr->isValueDependent()) {
6611 QualType EquivType =
6612 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6613 if (EquivType.isNull()) {
6614 Attr.setInvalid();
6615 return;
6616 }
6617 T = State.getAttributedType(ASAttr, Type, EquivType);
6618 } else {
6619 T = State.getAttributedType(ASAttr, Type, Type);
6620 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6621 }
6622
6623 if (!T.isNull())
6624 Type = T;
6625 else
6626 Attr.setInvalid();
6627 } else {
6628 // The keyword-based type attributes imply which address space to use.
6629 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6630 : Attr.asOpenCLLangAS();
6631 if (S.getLangOpts().HLSL)
6632 ASIdx = Attr.asHLSLLangAS();
6633
6634 if (ASIdx == LangAS::Default)
6635 llvm_unreachable("Invalid address space");
6636
6637 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6638 Attr.getLoc())) {
6639 Attr.setInvalid();
6640 return;
6641 }
6642
6644 }
6645}
6646
6647/// handleObjCOwnershipTypeAttr - Process an objc_ownership
6648/// attribute on the specified type.
6649///
6650/// Returns 'true' if the attribute was handled.
6651static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6652 ParsedAttr &attr, QualType &type) {
6653 bool NonObjCPointer = false;
6654
6655 if (!type->isDependentType() && !type->isUndeducedType()) {
6656 if (const PointerType *ptr = type->getAs<PointerType>()) {
6657 QualType pointee = ptr->getPointeeType();
6658 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6659 return false;
6660 // It is important not to lose the source info that there was an attribute
6661 // applied to non-objc pointer. We will create an attributed type but
6662 // its type will be the same as the original type.
6663 NonObjCPointer = true;
6664 } else if (!type->isObjCRetainableType()) {
6665 return false;
6666 }
6667
6668 // Don't accept an ownership attribute in the declspec if it would
6669 // just be the return type of a block pointer.
6670 if (state.isProcessingDeclSpec()) {
6671 Declarator &D = state.getDeclarator();
6672 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
6673 /*onlyBlockPointers=*/true))
6674 return false;
6675 }
6676 }
6677
6678 Sema &S = state.getSema();
6679 SourceLocation AttrLoc = attr.getLoc();
6680 if (AttrLoc.isMacroID())
6681 AttrLoc =
6683
6684 if (!attr.isArgIdent(0)) {
6685 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6687 attr.setInvalid();
6688 return true;
6689 }
6690
6691 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6692 Qualifiers::ObjCLifetime lifetime;
6693 if (II->isStr("none"))
6695 else if (II->isStr("strong"))
6696 lifetime = Qualifiers::OCL_Strong;
6697 else if (II->isStr("weak"))
6698 lifetime = Qualifiers::OCL_Weak;
6699 else if (II->isStr("autoreleasing"))
6701 else {
6702 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6703 attr.setInvalid();
6704 return true;
6705 }
6706
6707 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6708 // outside of ARC mode.
6709 if (!S.getLangOpts().ObjCAutoRefCount &&
6710 lifetime != Qualifiers::OCL_Weak &&
6711 lifetime != Qualifiers::OCL_ExplicitNone) {
6712 return true;
6713 }
6714
6715 SplitQualType underlyingType = type.split();
6716
6717 // Check for redundant/conflicting ownership qualifiers.
6718 if (Qualifiers::ObjCLifetime previousLifetime
6719 = type.getQualifiers().getObjCLifetime()) {
6720 // If it's written directly, that's an error.
6722 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6723 << type;
6724 return true;
6725 }
6726
6727 // Otherwise, if the qualifiers actually conflict, pull sugar off
6728 // and remove the ObjCLifetime qualifiers.
6729 if (previousLifetime != lifetime) {
6730 // It's possible to have multiple local ObjCLifetime qualifiers. We
6731 // can't stop after we reach a type that is directly qualified.
6732 const Type *prevTy = nullptr;
6733 while (!prevTy || prevTy != underlyingType.Ty) {
6734 prevTy = underlyingType.Ty;
6735 underlyingType = underlyingType.getSingleStepDesugaredType();
6736 }
6737 underlyingType.Quals.removeObjCLifetime();
6738 }
6739 }
6740
6741 underlyingType.Quals.addObjCLifetime(lifetime);
6742
6743 if (NonObjCPointer) {
6744 StringRef name = attr.getAttrName()->getName();
6745 switch (lifetime) {
6748 break;
6749 case Qualifiers::OCL_Strong: name = "__strong"; break;
6750 case Qualifiers::OCL_Weak: name = "__weak"; break;
6751 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6752 }
6753 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6755 }
6756
6757 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6758 // because having both 'T' and '__unsafe_unretained T' exist in the type
6759 // system causes unfortunate widespread consistency problems. (For example,
6760 // they're not considered compatible types, and we mangle them identicially
6761 // as template arguments.) These problems are all individually fixable,
6762 // but it's easier to just not add the qualifier and instead sniff it out
6763 // in specific places using isObjCInertUnsafeUnretainedType().
6764 //
6765 // Doing this does means we miss some trivial consistency checks that
6766 // would've triggered in ARC, but that's better than trying to solve all
6767 // the coexistence problems with __unsafe_unretained.
6768 if (!S.getLangOpts().ObjCAutoRefCount &&
6769 lifetime == Qualifiers::OCL_ExplicitNone) {
6770 type = state.getAttributedType(
6771 createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
6772 type, type);
6773 return true;
6774 }
6775
6776 QualType origType = type;
6777 if (!NonObjCPointer)
6778 type = S.Context.getQualifiedType(underlyingType);
6779
6780 // If we have a valid source location for the attribute, use an
6781 // AttributedType instead.
6782 if (AttrLoc.isValid()) {
6783 type = state.getAttributedType(::new (S.Context)
6784 ObjCOwnershipAttr(S.Context, attr, II),
6785 origType, type);
6786 }
6787
6788 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6789 unsigned diagnostic, QualType type) {
6794 diagnostic, type, /*ignored*/ 0));
6795 } else {
6796 S.Diag(loc, diagnostic);
6797 }
6798 };
6799
6800 // Sometimes, __weak isn't allowed.
6801 if (lifetime == Qualifiers::OCL_Weak &&
6802 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6803
6804 // Use a specialized diagnostic if the runtime just doesn't support them.
6805 unsigned diagnostic =
6806 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6807 : diag::err_arc_weak_no_runtime);
6808
6809 // In any case, delay the diagnostic until we know what we're parsing.
6810 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6811
6812 attr.setInvalid();
6813 return true;
6814 }
6815
6816 // Forbid __weak for class objects marked as
6817 // objc_arc_weak_reference_unavailable
6818 if (lifetime == Qualifiers::OCL_Weak) {
6819 if (const ObjCObjectPointerType *ObjT =
6820 type->getAs<ObjCObjectPointerType>()) {
6821 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6822 if (Class->isArcWeakrefUnavailable()) {
6823 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6824 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6825 diag::note_class_declared);
6826 }
6827 }
6828 }
6829 }
6830
6831 return true;
6832}
6833
6834/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6835/// attribute on the specified type. Returns true to indicate that
6836/// the attribute was handled, false to indicate that the type does
6837/// not permit the attribute.
6838static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6839 QualType &type) {
6840 Sema &S = state.getSema();
6841
6842 // Delay if this isn't some kind of pointer.
6843 if (!type->isPointerType() &&
6844 !type->isObjCObjectPointerType() &&
6845 !type->isBlockPointerType())
6846 return false;
6847
6848 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
6849 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
6850 attr.setInvalid();
6851 return true;
6852 }
6853
6854 // Check the attribute arguments.
6855 if (!attr.isArgIdent(0)) {
6856 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
6858 attr.setInvalid();
6859 return true;
6860 }
6861 Qualifiers::GC GCAttr;
6862 if (attr.getNumArgs() > 1) {
6863 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
6864 << 1;
6865 attr.setInvalid();
6866 return true;
6867 }
6868
6869 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6870 if (II->isStr("weak"))
6871 GCAttr = Qualifiers::Weak;
6872 else if (II->isStr("strong"))
6873 GCAttr = Qualifiers::Strong;
6874 else {
6875 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
6876 << attr << II;
6877 attr.setInvalid();
6878 return true;
6879 }
6880
6881 QualType origType = type;
6882 type = S.Context.getObjCGCQualType(origType, GCAttr);
6883
6884 // Make an attributed type to preserve the source information.
6885 if (attr.getLoc().isValid())
6886 type = state.getAttributedType(
6887 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
6888
6889 return true;
6890}
6891
6892namespace {
6893 /// A helper class to unwrap a type down to a function for the
6894 /// purposes of applying attributes there.
6895 ///
6896 /// Use:
6897 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
6898 /// if (unwrapped.isFunctionType()) {
6899 /// const FunctionType *fn = unwrapped.get();
6900 /// // change fn somehow
6901 /// T = unwrapped.wrap(fn);
6902 /// }
6903 struct FunctionTypeUnwrapper {
6904 enum WrapKind {
6905 Desugar,
6906 Attributed,
6907 Parens,
6908 Array,
6909 Pointer,
6910 BlockPointer,
6911 Reference,
6912 MemberPointer,
6913 MacroQualified,
6914 };
6915
6916 QualType Original;
6917 const FunctionType *Fn;
6918 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
6919
6920 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
6921 while (true) {
6922 const Type *Ty = T.getTypePtr();
6923 if (isa<FunctionType>(Ty)) {
6924 Fn = cast<FunctionType>(Ty);
6925 return;
6926 } else if (isa<ParenType>(Ty)) {
6927 T = cast<ParenType>(Ty)->getInnerType();
6928 Stack.push_back(Parens);
6929 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
6930 isa<IncompleteArrayType>(Ty)) {
6931 T = cast<ArrayType>(Ty)->getElementType();
6932 Stack.push_back(Array);
6933 } else if (isa<PointerType>(Ty)) {
6934 T = cast<PointerType>(Ty)->getPointeeType();
6935 Stack.push_back(Pointer);
6936 } else if (isa<BlockPointerType>(Ty)) {
6937 T = cast<BlockPointerType>(Ty)->getPointeeType();
6938 Stack.push_back(BlockPointer);
6939 } else if (isa<MemberPointerType>(Ty)) {
6940 T = cast<MemberPointerType>(Ty)->getPointeeType();
6941 Stack.push_back(MemberPointer);
6942 } else if (isa<ReferenceType>(Ty)) {
6943 T = cast<ReferenceType>(Ty)->getPointeeType();
6944 Stack.push_back(Reference);
6945 } else if (isa<AttributedType>(Ty)) {
6946 T = cast<AttributedType>(Ty)->getEquivalentType();
6947 Stack.push_back(Attributed);
6948 } else if (isa<MacroQualifiedType>(Ty)) {
6949 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
6950 Stack.push_back(MacroQualified);
6951 } else {
6952 const Type *DTy = Ty->getUnqualifiedDesugaredType();
6953 if (Ty == DTy) {
6954 Fn = nullptr;
6955 return;
6956 }
6957
6958 T = QualType(DTy, 0);
6959 Stack.push_back(Desugar);
6960 }
6961 }
6962 }
6963
6964 bool isFunctionType() const { return (Fn != nullptr); }
6965 const FunctionType *get() const { return Fn; }
6966
6967 QualType wrap(Sema &S, const FunctionType *New) {
6968 // If T wasn't modified from the unwrapped type, do nothing.
6969 if (New == get()) return Original;
6970
6971 Fn = New;
6972 return wrap(S.Context, Original, 0);
6973 }
6974
6975 private:
6976 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
6977 if (I == Stack.size())
6978 return C.getQualifiedType(Fn, Old.getQualifiers());
6979
6980 // Build up the inner type, applying the qualifiers from the old
6981 // type to the new type.
6982 SplitQualType SplitOld = Old.split();
6983
6984 // As a special case, tail-recurse if there are no qualifiers.
6985 if (SplitOld.Quals.empty())
6986 return wrap(C, SplitOld.Ty, I);
6987 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
6988 }
6989
6990 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
6991 if (I == Stack.size()) return QualType(Fn, 0);
6992
6993 switch (static_cast<WrapKind>(Stack[I++])) {
6994 case Desugar:
6995 // This is the point at which we potentially lose source
6996 // information.
6997 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
6998
6999 case Attributed:
7000 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7001
7002 case Parens: {
7003 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7004 return C.getParenType(New);
7005 }
7006
7007 case MacroQualified:
7008 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7009
7010 case Array: {
7011 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7012 QualType New = wrap(C, CAT->getElementType(), I);
7013 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7014 CAT->getSizeModifier(),
7015 CAT->getIndexTypeCVRQualifiers());
7016 }
7017
7018 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7019 QualType New = wrap(C, VAT->getElementType(), I);
7020 return C.getVariableArrayType(
7021 New, VAT->getSizeExpr(), VAT->getSizeModifier(),
7022 VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
7023 }
7024
7025 const auto *IAT = cast<IncompleteArrayType>(Old);
7026 QualType New = wrap(C, IAT->getElementType(), I);
7027 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7028 IAT->getIndexTypeCVRQualifiers());
7029 }
7030
7031 case Pointer: {
7032 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7033 return C.getPointerType(New);
7034 }
7035
7036 case BlockPointer: {
7037 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7038 return C.getBlockPointerType(New);
7039 }
7040
7041 case MemberPointer: {
7042 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7043 QualType New = wrap(C, OldMPT->getPointeeType(), I);
7044 return C.getMemberPointerType(New, OldMPT->getClass());
7045 }
7046
7047 case Reference: {
7048 const ReferenceType *OldRef = cast<ReferenceType>(Old);
7049 QualType New = wrap(C, OldRef->getPointeeType(), I);
7050 if (isa<LValueReferenceType>(OldRef))
7051 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7052 else
7053 return C.getRValueReferenceType(New);
7054 }
7055 }
7056
7057 llvm_unreachable("unknown wrapping kind");
7058 }
7059 };
7060} // end anonymous namespace
7061
7062static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7063 ParsedAttr &PAttr, QualType &Type) {
7064 Sema &S = State.getSema();
7065
7066 Attr *A;
7067 switch (PAttr.getKind()) {
7068 default: llvm_unreachable("Unknown attribute kind");
7069 case ParsedAttr::AT_Ptr32:
7070 A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
7071 break;
7072 case ParsedAttr::AT_Ptr64:
7073 A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
7074 break;
7075 case ParsedAttr::AT_SPtr:
7076 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7077 break;
7078 case ParsedAttr::AT_UPtr:
7079 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7080 break;
7081 }
7082
7083 std::bitset<attr::LastAttr> Attrs;
7084 QualType Desugared = Type;
7085 for (;;) {
7086 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7087 Desugared = TT->desugar();
7088 continue;
7089 } else if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Desugared)) {
7090 Desugared = ET->desugar();
7091 continue;
7092 }
7093 const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7094 if (!AT)
7095 break;
7096 Attrs[AT->getAttrKind()] = true;
7097 Desugared = AT->getModifiedType();
7098 }
7099
7100 // You cannot specify duplicate type attributes, so if the attribute has
7101 // already been applied, flag it.
7102 attr::Kind NewAttrKind = A->getKind();
7103 if (Attrs[NewAttrKind]) {
7104 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7105 return true;
7106 }
7107 Attrs[NewAttrKind] = true;
7108
7109 // You cannot have both __sptr and __uptr on the same type, nor can you
7110 // have __ptr32 and __ptr64.
7111 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7112 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7113 << "'__ptr32'"
7114 << "'__ptr64'" << /*isRegularKeyword=*/0;
7115 return true;
7116 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7117 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7118 << "'__sptr'"
7119 << "'__uptr'" << /*isRegularKeyword=*/0;
7120 return true;
7121 }
7122
7123 // Check the raw (i.e., desugared) Canonical type to see if it
7124 // is a pointer type.
7125 if (!isa<PointerType>(Desugared)) {
7126 // Pointer type qualifiers can only operate on pointer types, but not
7127 // pointer-to-member types.
7129 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7130 else
7131 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7132 return true;
7133 }
7134
7135 // Add address space to type based on its attributes.
7136 LangAS ASIdx = LangAS::Default;
7137 uint64_t PtrWidth =
7139 if (PtrWidth == 32) {
7140 if (Attrs[attr::Ptr64])
7141 ASIdx = LangAS::ptr64;
7142 else if (Attrs[attr::UPtr])
7143 ASIdx = LangAS::ptr32_uptr;
7144 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7145 if (S.Context.getTargetInfo().getTriple().isOSzOS() || Attrs[attr::UPtr])
7146 ASIdx = LangAS::ptr32_uptr;
7147 else
7148 ASIdx = LangAS::ptr32_sptr;
7149 }
7150
7151 QualType Pointee = Type->getPointeeType();
7152 if (ASIdx != LangAS::Default)
7153 Pointee = S.Context.getAddrSpaceQualType(
7154 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7155 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
7156 return false;
7157}
7158
7159static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7160 QualType &QT, ParsedAttr &PAttr) {
7161 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7162
7163 Sema &S = State.getSema();
7164 Attr *A = createSimpleAttr<WebAssemblyFuncrefAttr>(S.Context, PAttr);
7165
7166 std::bitset<attr::LastAttr> Attrs;
7167 attr::Kind NewAttrKind = A->getKind();
7168 const auto *AT = dyn_cast<AttributedType>(QT);
7169 while (AT) {
7170 Attrs[AT->getAttrKind()] = true;
7171 AT = dyn_cast<AttributedType>(AT->getModifiedType());
7172 }
7173
7174 // You cannot specify duplicate type attributes, so if the attribute has
7175 // already been applied, flag it.
7176 if (Attrs[NewAttrKind]) {
7177 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7178 return true;
7179 }
7180
7181 // Add address space to type based on its attributes.
7183 QualType Pointee = QT->getPointeeType();
7184 Pointee = S.Context.getAddrSpaceQualType(
7185 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7186 QT = State.getAttributedType(A, QT, S.Context.getPointerType(Pointee));
7187 return false;
7188}
7189
7190static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL,
7191 QualType &QT, ParsedAttr &PAttr) {
7192 if (TAL == TAL_DeclName)
7193 return;
7194
7195 Sema &S = State.getSema();
7196 auto &D = State.getDeclarator();
7197
7198 // If the attribute appears in declaration specifiers
7199 // it should be handled as a declaration attribute,
7200 // unless it's associated with a type or a function
7201 // prototype (i.e. appears on a parameter or result type).
7202 if (State.isProcessingDeclSpec()) {
7203 if (!(D.isPrototypeContext() ||
7204 D.getContext() == DeclaratorContext::TypeName))
7205 return;
7206
7207 if (auto *chunk = D.getInnermostNonParenChunk()) {
7208 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7209 const_cast<DeclaratorChunk *>(chunk)->getAttrs());
7210 return;
7211 }
7212 }
7213
7214 StringRef Str;
7215 if (!S.checkStringLiteralArgumentAttr(PAttr, 0, Str)) {
7216 PAttr.setInvalid();
7217 return;
7218 }
7219
7220 // If the attribute as attached to a paren move it closer to
7221 // the declarator. This can happen in block declarations when
7222 // an attribute is placed before `^` i.e. `(__attribute__((...)) ^)`.
7223 //
7224 // Note that it's actually invalid to use GNU style attributes
7225 // in a block but such cases are currently handled gracefully
7226 // but the parser and behavior should be consistent between
7227 // cases when attribute appears before/after block's result
7228 // type and inside (^).
7229 if (TAL == TAL_DeclChunk) {
7230 auto chunkIdx = State.getCurrentChunkIndex();
7231 if (chunkIdx >= 1 &&
7232 D.getTypeObject(chunkIdx).Kind == DeclaratorChunk::Paren) {
7233 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7234 D.getTypeObject(chunkIdx - 1).getAttrs());
7235 return;
7236 }
7237 }
7238
7239 auto *A = ::new (S.Context) SwiftAttrAttr(S.Context, PAttr, Str);
7240 QT = State.getAttributedType(A, QT, QT);
7241 PAttr.setUsedAsTypeAttr();
7242}
7243
7244/// Rebuild an attributed type without the nullability attribute on it.
7246 QualType Type) {
7247 auto Attributed = dyn_cast<AttributedType>(Type.getTypePtr());
7248 if (!Attributed)
7249 return Type;
7250
7251 // Skip the nullability attribute; we're done.
7252 if (Attributed->getImmediateNullability())
7253 return Attributed->getModifiedType();
7254
7255 // Build the modified type.
7257 Ctx, Attributed->getModifiedType());
7258 assert(Modified.getTypePtr() != Attributed->getModifiedType().getTypePtr());
7259 return Ctx.getAttributedType(Attributed->getAttrKind(), Modified,
7260 Attributed->getEquivalentType(),
7261 Attributed->getAttr());
7262}
7263
7264/// Map a nullability attribute kind to a nullability kind.
7266 switch (kind) {
7267 case ParsedAttr::AT_TypeNonNull:
7269
7270 case ParsedAttr::AT_TypeNullable:
7272
7273 case ParsedAttr::AT_TypeNullableResult:
7275
7276 case ParsedAttr::AT_TypeNullUnspecified:
7278
7279 default:
7280 llvm_unreachable("not a nullability attribute kind");
7281 }
7282}
7283
7285 Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT,
7286 NullabilityKind Nullability, SourceLocation NullabilityLoc,
7287 bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting) {
7288 bool Implicit = (State == nullptr);
7289 if (!Implicit)
7290 recordNullabilitySeen(S, NullabilityLoc);
7291
7292 // Check for existing nullability attributes on the type.
7293 QualType Desugared = QT;
7294 while (auto *Attributed = dyn_cast<AttributedType>(Desugared.getTypePtr())) {
7295 // Check whether there is already a null
7296 if (auto ExistingNullability = Attributed->getImmediateNullability()) {
7297 // Duplicated nullability.
7298 if (Nullability == *ExistingNullability) {
7299 if (Implicit)
7300 break;
7301
7302 S.Diag(NullabilityLoc, diag::warn_nullability_duplicate)
7303 << DiagNullabilityKind(Nullability, IsContextSensitive)
7304 << FixItHint::CreateRemoval(NullabilityLoc);
7305
7306 break;
7307 }
7308
7309 if (!OverrideExisting) {
7310 // Conflicting nullability.
7311 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7312 << DiagNullabilityKind(Nullability, IsContextSensitive)
7313 << DiagNullabilityKind(*ExistingNullability, false);
7314 return true;
7315 }
7316
7317 // Rebuild the attributed type, dropping the existing nullability.
7319 }
7320
7321 Desugared = Attributed->getModifiedType();
7322 }
7323
7324 // If there is already a different nullability specifier, complain.
7325 // This (unlike the code above) looks through typedefs that might
7326 // have nullability specifiers on them, which means we cannot
7327 // provide a useful Fix-It.
7328 if (auto ExistingNullability = Desugared->getNullability()) {
7329 if (Nullability != *ExistingNullability && !Implicit) {
7330 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7331 << DiagNullabilityKind(Nullability, IsContextSensitive)
7332 << DiagNullabilityKind(*ExistingNullability, false);
7333
7334 // Try to find the typedef with the existing nullability specifier.
7335 if (auto TT = Desugared->getAs<TypedefType>()) {
7336 TypedefNameDecl *typedefDecl = TT->getDecl();
7337 QualType underlyingType = typedefDecl->getUnderlyingType();
7338 if (auto typedefNullability =
7339 AttributedType::stripOuterNullability(underlyingType)) {
7340 if (*typedefNullability == *ExistingNullability) {
7341 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7342 << DiagNullabilityKind(*ExistingNullability, false);
7343 }
7344 }
7345 }
7346
7347 return true;
7348 }
7349 }
7350
7351 // If this definitely isn't a pointer type, reject the specifier.
7352 if (!Desugared->canHaveNullability() &&
7353 !(AllowOnArrayType && Desugared->isArrayType())) {
7354 if (!Implicit)
7355 S.Diag(NullabilityLoc, diag::err_nullability_nonpointer)
7356 << DiagNullabilityKind(Nullability, IsContextSensitive) << QT;
7357
7358 return true;
7359 }
7360
7361 // For the context-sensitive keywords/Objective-C property
7362 // attributes, require that the type be a single-level pointer.
7363 if (IsContextSensitive) {
7364 // Make sure that the pointee isn't itself a pointer type.
7365 const Type *pointeeType = nullptr;
7366 if (Desugared->isArrayType())
7367 pointeeType = Desugared->getArrayElementTypeNoTypeQual();
7368 else if (Desugared->isAnyPointerType())
7369 pointeeType = Desugared->getPointeeType().getTypePtr();
7370
7371 if (pointeeType && (pointeeType->isAnyPointerType() ||
7372 pointeeType->isObjCObjectPointerType() ||
7373 pointeeType->isMemberPointerType())) {
7374 S.Diag(NullabilityLoc, diag::err_nullability_cs_multilevel)
7375 << DiagNullabilityKind(Nullability, true) << QT;
7376 S.Diag(NullabilityLoc, diag::note_nullability_type_specifier)
7377 << DiagNullabilityKind(Nullability, false) << QT
7378 << FixItHint::CreateReplacement(NullabilityLoc,
7379 getNullabilitySpelling(Nullability));
7380 return true;
7381 }
7382 }
7383
7384 // Form the attributed type.
7385 if (State) {
7386 assert(PAttr);
7387 Attr *A = createNullabilityAttr(S.Context, *PAttr, Nullability);
7388 QT = State->getAttributedType(A, QT, QT);
7389 } else {
7390 QT = S.Context.getAttributedType(Nullability, QT, QT);
7391 }
7392 return false;
7393}
7394
7395static bool CheckNullabilityTypeSpecifier(TypeProcessingState &State,
7397 bool AllowOnArrayType) {
7399 SourceLocation NullabilityLoc = Attr.getLoc();
7400 bool IsContextSensitive = Attr.isContextSensitiveKeywordAttribute();
7401
7402 return CheckNullabilityTypeSpecifier(State.getSema(), &State, &Attr, Type,
7403 Nullability, NullabilityLoc,
7404 IsContextSensitive, AllowOnArrayType,
7405 /*overrideExisting*/ false);
7406}
7407
7409 NullabilityKind Nullability,
7410 SourceLocation DiagLoc,
7411 bool AllowArrayTypes,
7412 bool OverrideExisting) {
7414 *this, nullptr, nullptr, Type, Nullability, DiagLoc,
7415 /*isContextSensitive*/ false, AllowArrayTypes, OverrideExisting);
7416}
7417
7418/// Check the application of the Objective-C '__kindof' qualifier to
7419/// the given type.
7420static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7421 ParsedAttr &attr) {
7422 Sema &S = state.getSema();
7423
7424 if (isa<ObjCTypeParamType>(type)) {
7425 // Build the attributed type to record where __kindof occurred.
7426 type = state.getAttributedType(
7427 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
7428 return false;
7429 }
7430
7431 // Find out if it's an Objective-C object or object pointer type;
7432 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7433 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7434 : type->getAs<ObjCObjectType>();
7435
7436 // If not, we can't apply __kindof.
7437 if (!objType) {
7438 // FIXME: Handle dependent types that aren't yet object types.
7439 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7440 << type;
7441 return true;
7442 }
7443
7444 // Rebuild the "equivalent" type, which pushes __kindof down into
7445 // the object type.
7446 // There is no need to apply kindof on an unqualified id type.
7447 QualType equivType = S.Context.getObjCObjectType(
7448 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7449 objType->getProtocols(),
7450 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7451
7452 // If we started with an object pointer type, rebuild it.
7453 if (ptrType) {
7454 equivType = S.Context.getObjCObjectPointerType(equivType);
7455 if (auto nullability = type->getNullability()) {
7456 // We create a nullability attribute from the __kindof attribute.
7457 // Make sure that will make sense.
7458 assert(attr.getAttributeSpellingListIndex() == 0 &&
7459 "multiple spellings for __kindof?");
7460 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7461 A->setImplicit(true);
7462 equivType = state.getAttributedType(A, equivType, equivType);
7463 }
7464 }
7465
7466 // Build the attributed type to record where __kindof occurred.
7467 type = state.getAttributedType(
7468 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
7469 return false;
7470}
7471
7472/// Distribute a nullability type attribute that cannot be applied to
7473/// the type specifier to a pointer, block pointer, or member pointer
7474/// declarator, complaining if necessary.
7475///
7476/// \returns true if the nullability annotation was distributed, false
7477/// otherwise.
7478static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7479 QualType type, ParsedAttr &attr) {
7480 Declarator &declarator = state.getDeclarator();
7481
7482 /// Attempt to move the attribute to the specified chunk.
7483 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7484 // If there is already a nullability attribute there, don't add
7485 // one.
7486 if (hasNullabilityAttr(chunk.getAttrs()))
7487 return false;
7488
7489 // Complain about the nullability qualifier being in the wrong
7490 // place.
7491 enum {
7492 PK_Pointer,
7493 PK_BlockPointer,
7494 PK_MemberPointer,
7495 PK_FunctionPointer,
7496 PK_MemberFunctionPointer,
7497 } pointerKind
7498 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7499 : PK_Pointer)
7500 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7501 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7502
7503 auto diag = state.getSema().Diag(attr.getLoc(),
7504 diag::warn_nullability_declspec)
7506 attr.isContextSensitiveKeywordAttribute())
7507 << type
7508 << static_cast<unsigned>(pointerKind);
7509
7510 // FIXME: MemberPointer chunks don't carry the location of the *.
7511 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7512 diag << FixItHint::CreateRemoval(attr.getLoc())
7514 state.getSema().getPreprocessor().getLocForEndOfToken(
7515 chunk.Loc),
7516 " " + attr.getAttrName()->getName().str() + " ");
7517 }
7518
7519 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7520 chunk.getAttrs());
7521 return true;
7522 };
7523
7524 // Move it to the outermost pointer, member pointer, or block
7525 // pointer declarator.
7526 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7527 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7528 switch (chunk.Kind) {
7532 return moveToChunk(chunk, false);
7533
7536 continue;
7537
7539 // Try to move past the return type to a function/block/member
7540 // function pointer.
7542 declarator, i,
7543 /*onlyBlockPointers=*/false)) {
7544 return moveToChunk(*dest, true);
7545 }
7546
7547 return false;
7548
7549 // Don't walk through these.
7552 return false;
7553 }
7554 }
7555
7556 return false;
7557}
7558
7560 assert(!Attr.isInvalid());
7561 switch (Attr.getKind()) {
7562 default:
7563 llvm_unreachable("not a calling convention attribute");
7564 case ParsedAttr::AT_CDecl:
7565 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7566 case ParsedAttr::AT_FastCall:
7567 return createSimpleAttr<FastCallAttr>(Ctx, Attr);
7568 case ParsedAttr::AT_StdCall:
7569 return createSimpleAttr<StdCallAttr>(Ctx, Attr);
7570 case ParsedAttr::AT_ThisCall:
7571 return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
7572 case ParsedAttr::AT_RegCall:
7573 return createSimpleAttr<RegCallAttr>(Ctx, Attr);
7574 case ParsedAttr::AT_Pascal:
7575 return createSimpleAttr<PascalAttr>(Ctx, Attr);
7576 case ParsedAttr::AT_SwiftCall:
7577 return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
7578 case ParsedAttr::AT_SwiftAsyncCall:
7579 return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr);
7580 case ParsedAttr::AT_VectorCall:
7581 return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
7582 case ParsedAttr::AT_AArch64VectorPcs:
7583 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
7584 case ParsedAttr::AT_AArch64SVEPcs:
7585 return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, Attr);
7586 case ParsedAttr::AT_ArmStreaming:
7587 return createSimpleAttr<ArmStreamingAttr>(Ctx, Attr);
7588 case ParsedAttr::AT_AMDGPUKernelCall:
7589 return createSimpleAttr<AMDGPUKernelCallAttr>(Ctx, Attr);
7590 case ParsedAttr::AT_Pcs: {
7591 // The attribute may have had a fixit applied where we treated an
7592 // identifier as a string literal. The contents of the string are valid,
7593 // but the form may not be.
7594 StringRef Str;
7595 if (Attr.isArgExpr(0))
7596 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7597 else
7598 Str = Attr.getArgAsIdent(0)->Ident->getName();
7599 PcsAttr::PCSType Type;
7600 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7601 llvm_unreachable("already validated the attribute");
7602 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7603 }
7604 case ParsedAttr::AT_IntelOclBicc:
7605 return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
7606 case ParsedAttr::AT_MSABI:
7607 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7608 case ParsedAttr::AT_SysVABI:
7609 return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
7610 case ParsedAttr::AT_PreserveMost:
7611 return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
7612 case ParsedAttr::AT_PreserveAll:
7613 return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
7614 case ParsedAttr::AT_M68kRTD:
7615 return createSimpleAttr<M68kRTDAttr>(Ctx, Attr);
7616 case ParsedAttr::AT_PreserveNone:
7617 return createSimpleAttr<PreserveNoneAttr>(Ctx, Attr);
7618 case ParsedAttr::AT_RISCVVectorCC:
7619 return createSimpleAttr<RISCVVectorCCAttr>(Ctx, Attr);
7620 }
7621 llvm_unreachable("unexpected attribute kind!");
7622}
7623
7624std::optional<FunctionEffectMode>
7625Sema::ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName) {
7626 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent())
7628
7629 std::optional<llvm::APSInt> ConditionValue =
7631 if (!ConditionValue) {
7632 // FIXME: err_attribute_argument_type doesn't quote the attribute
7633 // name but needs to; users are inconsistent.
7634 Diag(CondExpr->getExprLoc(), diag::err_attribute_argument_type)
7635 << AttributeName << AANT_ArgumentIntegerConstant
7636 << CondExpr->getSourceRange();
7637 return std::nullopt;
7638 }
7639 return !ConditionValue->isZero() ? FunctionEffectMode::True
7641}
7642
7643static bool
7644handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState,
7645 ParsedAttr &PAttr, QualType &QT,
7646 FunctionTypeUnwrapper &Unwrapped) {
7647 // Delay if this is not a function type.
7648 if (!Unwrapped.isFunctionType())
7649 return false;
7650
7651 Sema &S = TPState.getSema();
7652
7653 // Require FunctionProtoType.
7654 auto *FPT = Unwrapped.get()->getAs<FunctionProtoType>();
7655 if (FPT == nullptr) {
7656 S.Diag(PAttr.getLoc(), diag::err_func_with_effects_no_prototype)
7657 << PAttr.getAttrName()->getName();
7658 return true;
7659 }
7660
7661 // Parse the new attribute.
7662 // non/blocking or non/allocating? Or conditional (computed)?
7663 bool IsNonBlocking = PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7664 PAttr.getKind() == ParsedAttr::AT_Blocking;
7665
7667 Expr *CondExpr = nullptr; // only valid if dependent
7668
7669 if (PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7670 PAttr.getKind() == ParsedAttr::AT_NonAllocating) {
7671 if (!PAttr.checkAtMostNumArgs(S, 1)) {
7672 PAttr.setInvalid();
7673 return true;
7674 }
7675
7676 // Parse the condition, if any.
7677 if (PAttr.getNumArgs() == 1) {
7678 CondExpr = PAttr.getArgAsExpr(0);
7679 std::optional<FunctionEffectMode> MaybeMode =
7680 S.ActOnEffectExpression(CondExpr, PAttr.getAttrName()->getName());
7681 if (!MaybeMode) {
7682 PAttr.setInvalid();
7683 return true;
7684 }
7685 NewMode = *MaybeMode;
7686 if (NewMode != FunctionEffectMode::Dependent)
7687 CondExpr = nullptr;
7688 } else {
7689 NewMode = FunctionEffectMode::True;
7690 }
7691 } else {
7692 // This is the `blocking` or `allocating` attribute.
7693 if (S.CheckAttrNoArgs(PAttr)) {
7694 // The attribute has been marked invalid.
7695 return true;
7696 }
7697 NewMode = FunctionEffectMode::False;
7698 }
7699
7700 const FunctionEffect::Kind FEKind =
7701 (NewMode == FunctionEffectMode::False)
7702 ? (IsNonBlocking ? FunctionEffect::Kind::Blocking
7704 : (IsNonBlocking ? FunctionEffect::Kind::NonBlocking
7706 const FunctionEffectWithCondition NewEC{FunctionEffect(FEKind),
7707 EffectConditionExpr(CondExpr)};
7708
7709 if (S.diagnoseConflictingFunctionEffect(FPT->getFunctionEffects(), NewEC,
7710 PAttr.getLoc())) {
7711 PAttr.setInvalid();
7712 return true;
7713 }
7714
7715 // Add the effect to the FunctionProtoType.
7716 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7719 [[maybe_unused]] bool Success = FX.insert(NewEC, Errs);
7720 assert(Success && "effect conflicts should have been diagnosed above");
7722
7723 QualType NewType = S.Context.getFunctionType(FPT->getReturnType(),
7724 FPT->getParamTypes(), EPI);
7725 QT = Unwrapped.wrap(S, NewType->getAs<FunctionType>());
7726 return true;
7727}
7728
7729static bool checkMutualExclusion(TypeProcessingState &state,
7732 AttributeCommonInfo::Kind OtherKind) {
7733 auto OtherAttr = std::find_if(
7734 state.getCurrentAttributes().begin(), state.getCurrentAttributes().end(),
7735 [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
7736 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid())
7737 return false;
7738
7739 Sema &S = state.getSema();
7740 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
7741 << *OtherAttr << Attr
7742 << (OtherAttr->isRegularKeywordAttribute() ||
7744 S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute);
7745 Attr.setInvalid();
7746 return true;
7747}
7748
7751 ParsedAttr &Attr) {
7752 if (!Attr.getNumArgs()) {
7753 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
7754 Attr.setInvalid();
7755 return true;
7756 }
7757
7758 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
7759 StringRef StateName;
7760 SourceLocation LiteralLoc;
7761 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
7762 return true;
7763
7764 if (StateName != "sme_za_state") {
7765 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
7766 Attr.setInvalid();
7767 return true;
7768 }
7769
7770 if (EPI.AArch64SMEAttributes &
7772 S.Diag(Attr.getLoc(), diag::err_conflicting_attributes_arm_agnostic);
7773 Attr.setInvalid();
7774 return true;
7775 }
7776
7778 }
7779
7780 return false;
7781}
7782
7787 if (!Attr.getNumArgs()) {
7788 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
7789 Attr.setInvalid();
7790 return true;
7791 }
7792
7793 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
7794 StringRef StateName;
7795 SourceLocation LiteralLoc;
7796 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
7797 return true;
7798
7799 unsigned Shift;
7800 FunctionType::ArmStateValue ExistingState;
7801 if (StateName == "za") {
7804 } else if (StateName == "zt0") {
7807 } else {
7808 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
7809 Attr.setInvalid();
7810 return true;
7811 }
7812
7814 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_agnostic);
7815 Attr.setInvalid();
7816 return true;
7817 }
7818
7819 // __arm_in(S), __arm_out(S), __arm_inout(S) and __arm_preserves(S)
7820 // are all mutually exclusive for the same S, so check if there are
7821 // conflicting attributes.
7822 if (ExistingState != FunctionType::ARM_None && ExistingState != State) {
7823 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_state)
7824 << StateName;
7825 Attr.setInvalid();
7826 return true;
7827 }
7828
7830 (FunctionType::AArch64SMETypeAttributes)((State << Shift)));
7831 }
7832 return false;
7833}
7834
7835/// Process an individual function attribute. Returns true to
7836/// indicate that the attribute was handled, false if it wasn't.
7837static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7839 Sema &S = state.getSema();
7840
7841 FunctionTypeUnwrapper unwrapped(S, type);
7842
7843 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
7844 if (S.CheckAttrNoArgs(attr))
7845 return true;
7846
7847 // Delay if this is not a function type.
7848 if (!unwrapped.isFunctionType())
7849 return false;
7850
7851 // Otherwise we can process right away.
7852 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
7853 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7854 return true;
7855 }
7856
7857 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
7858 // Delay if this is not a function type.
7859 if (!unwrapped.isFunctionType())
7860 return false;
7861
7862 // Ignore if we don't have CMSE enabled.
7863 if (!S.getLangOpts().Cmse) {
7864 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
7865 attr.setInvalid();
7866 return true;
7867 }
7868
7869 // Otherwise we can process right away.
7871 unwrapped.get()->getExtInfo().withCmseNSCall(true);
7872 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7873 return true;
7874 }
7875
7876 // ns_returns_retained is not always a type attribute, but if we got
7877 // here, we're treating it as one right now.
7878 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
7879 if (attr.getNumArgs()) return true;
7880
7881 // Delay if this is not a function type.
7882 if (!unwrapped.isFunctionType())
7883 return false;
7884
7885 // Check whether the return type is reasonable.
7887 attr.getLoc(), unwrapped.get()->getReturnType()))
7888 return true;
7889
7890 // Only actually change the underlying type in ARC builds.
7891 QualType origType = type;
7892 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
7894 = unwrapped.get()->getExtInfo().withProducesResult(true);
7895 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7896 }
7897 type = state.getAttributedType(
7898 createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
7899 origType, type);
7900 return true;
7901 }
7902
7903 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
7905 return true;
7906
7907 // Delay if this is not a function type.
7908 if (!unwrapped.isFunctionType())
7909 return false;
7910
7912 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
7913 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7914 return true;
7915 }
7916
7917 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
7918 if (!S.getLangOpts().CFProtectionBranch) {
7919 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
7920 attr.setInvalid();
7921 return true;
7922 }
7923
7925 return true;
7926
7927 // If this is not a function type, warning will be asserted by subject
7928 // check.
7929 if (!unwrapped.isFunctionType())
7930 return true;
7931
7933 unwrapped.get()->getExtInfo().withNoCfCheck(true);
7934 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7935 return true;
7936 }
7937
7938 if (attr.getKind() == ParsedAttr::AT_Regparm) {
7939 unsigned value;
7940 if (S.CheckRegparmAttr(attr, value))
7941 return true;
7942
7943 // Delay if this is not a function type.
7944 if (!unwrapped.isFunctionType())
7945 return false;
7946
7947 // Diagnose regparm with fastcall.
7948 const FunctionType *fn = unwrapped.get();
7949 CallingConv CC = fn->getCallConv();
7950 if (CC == CC_X86FastCall) {
7951 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7952 << FunctionType::getNameForCallConv(CC) << "regparm"
7953 << attr.isRegularKeywordAttribute();
7954 attr.setInvalid();
7955 return true;
7956 }
7957
7959 unwrapped.get()->getExtInfo().withRegParm(value);
7960 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7961 return true;
7962 }
7963
7964 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
7965 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible ||
7966 attr.getKind() == ParsedAttr::AT_ArmPreserves ||
7967 attr.getKind() == ParsedAttr::AT_ArmIn ||
7968 attr.getKind() == ParsedAttr::AT_ArmOut ||
7969 attr.getKind() == ParsedAttr::AT_ArmInOut ||
7970 attr.getKind() == ParsedAttr::AT_ArmAgnostic) {
7971 if (S.CheckAttrTarget(attr))
7972 return true;
7973
7974 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
7975 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible)
7976 if (S.CheckAttrNoArgs(attr))
7977 return true;
7978
7979 if (!unwrapped.isFunctionType())
7980 return false;
7981
7982 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
7983 if (!FnTy) {
7984 // SME ACLE attributes are not supported on K&R-style unprototyped C
7985 // functions.
7986 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
7987 << attr << attr.isRegularKeywordAttribute()
7989 attr.setInvalid();
7990 return false;
7991 }
7992
7993 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
7994 switch (attr.getKind()) {
7995 case ParsedAttr::AT_ArmStreaming:
7996 if (checkMutualExclusion(state, EPI, attr,
7997 ParsedAttr::AT_ArmStreamingCompatible))
7998 return true;
8000 break;
8001 case ParsedAttr::AT_ArmStreamingCompatible:
8002 if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming))
8003 return true;
8005 break;
8006 case ParsedAttr::AT_ArmPreserves:
8008 return true;
8009 break;
8010 case ParsedAttr::AT_ArmIn:
8012 return true;
8013 break;
8014 case ParsedAttr::AT_ArmOut:
8016 return true;
8017 break;
8018 case ParsedAttr::AT_ArmInOut:
8020 return true;
8021 break;
8022 case ParsedAttr::AT_ArmAgnostic:
8023 if (handleArmAgnosticAttribute(S, EPI, attr))
8024 return true;
8025 break;
8026 default:
8027 llvm_unreachable("Unsupported attribute");
8028 }
8029
8030 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8031 FnTy->getParamTypes(), EPI);
8032 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8033 return true;
8034 }
8035
8036 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
8037 // Delay if this is not a function type.
8038 if (!unwrapped.isFunctionType())
8039 return false;
8040
8041 if (S.CheckAttrNoArgs(attr)) {
8042 attr.setInvalid();
8043 return true;
8044 }
8045
8046 // Otherwise we can process right away.
8047 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
8048
8049 // MSVC ignores nothrow if it is in conflict with an explicit exception
8050 // specification.
8051 if (Proto->hasExceptionSpec()) {
8052 switch (Proto->getExceptionSpecType()) {
8053 case EST_None:
8054 llvm_unreachable("This doesn't have an exception spec!");
8055
8056 case EST_DynamicNone:
8057 case EST_BasicNoexcept:
8058 case EST_NoexceptTrue:
8059 case EST_NoThrow:
8060 // Exception spec doesn't conflict with nothrow, so don't warn.
8061 [[fallthrough]];
8062 case EST_Unparsed:
8063 case EST_Uninstantiated:
8065 case EST_Unevaluated:
8066 // We don't have enough information to properly determine if there is a
8067 // conflict, so suppress the warning.
8068 break;
8069 case EST_Dynamic:
8070 case EST_MSAny:
8071 case EST_NoexceptFalse:
8072 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
8073 break;
8074 }
8075 return true;
8076 }
8077
8078 type = unwrapped.wrap(
8079 S, S.Context
8081 QualType{Proto, 0},
8083 ->getAs<FunctionType>());
8084 return true;
8085 }
8086
8087 if (attr.getKind() == ParsedAttr::AT_NonBlocking ||
8088 attr.getKind() == ParsedAttr::AT_NonAllocating ||
8089 attr.getKind() == ParsedAttr::AT_Blocking ||
8090 attr.getKind() == ParsedAttr::AT_Allocating) {
8091 return handleNonBlockingNonAllocatingTypeAttr(state, attr, type, unwrapped);
8092 }
8093
8094 // Delay if the type didn't work out to a function.
8095 if (!unwrapped.isFunctionType()) return false;
8096
8097 // Otherwise, a calling convention.
8098 CallingConv CC;
8099 if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/nullptr, CFT))
8100 return true;
8101
8102 const FunctionType *fn = unwrapped.get();
8103 CallingConv CCOld = fn->getCallConv();
8104 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
8105
8106 if (CCOld != CC) {
8107 // Error out on when there's already an attribute on the type
8108 // and the CCs don't match.
8110 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8113 << attr.isRegularKeywordAttribute();
8114 attr.setInvalid();
8115 return true;
8116 }
8117 }
8118
8119 // Diagnose use of variadic functions with calling conventions that
8120 // don't support them (e.g. because they're callee-cleanup).
8121 // We delay warning about this on unprototyped function declarations
8122 // until after redeclaration checking, just in case we pick up a
8123 // prototype that way. And apparently we also "delay" warning about
8124 // unprototyped function types in general, despite not necessarily having
8125 // much ability to diagnose it later.
8126 if (!supportsVariadicCall(CC)) {
8127 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
8128 if (FnP && FnP->isVariadic()) {
8129 // stdcall and fastcall are ignored with a warning for GCC and MS
8130 // compatibility.
8131 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
8132 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
8135
8136 attr.setInvalid();
8137 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
8139 }
8140 }
8141
8142 // Also diagnose fastcall with regparm.
8143 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
8144 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8146 << attr.isRegularKeywordAttribute();
8147 attr.setInvalid();
8148 return true;
8149 }
8150
8151 // Modify the CC from the wrapped function type, wrap it all back, and then
8152 // wrap the whole thing in an AttributedType as written. The modified type
8153 // might have a different CC if we ignored the attribute.
8155 if (CCOld == CC) {
8156 Equivalent = type;
8157 } else {
8158 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
8159 Equivalent =
8160 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8161 }
8162 type = state.getAttributedType(CCAttr, type, Equivalent);
8163 return true;
8164}
8165
8167 const AttributedType *AT;
8168
8169 // Stop if we'd be stripping off a typedef sugar node to reach the
8170 // AttributedType.
8171 while ((AT = T->getAs<AttributedType>()) &&
8172 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
8173 if (AT->isCallingConv())
8174 return true;
8175 T = AT->getModifiedType();
8176 }
8177 return false;
8178}
8179
8180void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
8181 bool IsCtorOrDtor, SourceLocation Loc) {
8182 FunctionTypeUnwrapper Unwrapped(*this, T);
8183 const FunctionType *FT = Unwrapped.get();
8184 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
8185 cast<FunctionProtoType>(FT)->isVariadic());
8186 CallingConv CurCC = FT->getCallConv();
8187 CallingConv ToCC =
8188 Context.getDefaultCallingConvention(IsVariadic, HasThisPointer);
8189
8190 if (CurCC == ToCC)
8191 return;
8192
8193 // MS compiler ignores explicit calling convention attributes on structors. We
8194 // should do the same.
8195 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
8196 // Issue a warning on ignored calling convention -- except of __stdcall.
8197 // Again, this is what MS compiler does.
8198 if (CurCC != CC_X86StdCall)
8199 Diag(Loc, diag::warn_cconv_unsupported)
8202 // Default adjustment.
8203 } else {
8204 // Only adjust types with the default convention. For example, on Windows
8205 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8206 // __thiscall type to __cdecl for static methods.
8207 CallingConv DefaultCC =
8208 Context.getDefaultCallingConvention(IsVariadic, !HasThisPointer);
8209
8210 if (CurCC != DefaultCC)
8211 return;
8212
8214 return;
8215 }
8216
8218 QualType Wrapped = Unwrapped.wrap(*this, FT);
8219 T = Context.getAdjustedType(T, Wrapped);
8220}
8221
8222/// HandleVectorSizeAttribute - this attribute is only applicable to integral
8223/// and float scalars, although arrays, pointers, and function return values are
8224/// allowed in conjunction with this construct. Aggregates with this attribute
8225/// are invalid, even if they are of the same size as a corresponding scalar.
8226/// The raw attribute should contain precisely 1 argument, the vector size for
8227/// the variable, measured in bytes. If curType and rawAttr are well formed,
8228/// this routine will return a new vector type.
8229static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8230 Sema &S) {
8231 // Check the attribute arguments.
8232 if (Attr.getNumArgs() != 1) {
8233 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8234 << 1;
8235 Attr.setInvalid();
8236 return;
8237 }
8238
8239 Expr *SizeExpr = Attr.getArgAsExpr(0);
8240 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
8241 if (!T.isNull())
8242 CurType = T;
8243 else
8244 Attr.setInvalid();
8245}
8246
8247/// Process the OpenCL-like ext_vector_type attribute when it occurs on
8248/// a type.
8250 Sema &S) {
8251 // check the attribute arguments.
8252 if (Attr.getNumArgs() != 1) {
8253 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8254 << 1;
8255 return;
8256 }
8257
8258 Expr *SizeExpr = Attr.getArgAsExpr(0);
8259 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
8260 if (!T.isNull())
8261 CurType = T;
8262}
8263
8264static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) {
8265 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8266 if (!BTy)
8267 return false;
8268
8269 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8270
8271 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8272 // now.
8273 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8274 Triple.getArch() == llvm::Triple::aarch64_32 ||
8275 Triple.getArch() == llvm::Triple::aarch64_be;
8276 if (VecKind == VectorKind::NeonPoly) {
8277 if (IsPolyUnsigned) {
8278 // AArch64 polynomial vectors are unsigned.
8279 return BTy->getKind() == BuiltinType::UChar ||
8280 BTy->getKind() == BuiltinType::UShort ||
8281 BTy->getKind() == BuiltinType::ULong ||
8282 BTy->getKind() == BuiltinType::ULongLong;
8283 } else {
8284 // AArch32 polynomial vectors are signed.
8285 return BTy->getKind() == BuiltinType::SChar ||
8286 BTy->getKind() == BuiltinType::Short ||
8287 BTy->getKind() == BuiltinType::LongLong;
8288 }
8289 }
8290
8291 // Non-polynomial vector types: the usual suspects are allowed, as well as
8292 // float64_t on AArch64.
8293 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8294 BTy->getKind() == BuiltinType::Double)
8295 return true;
8296
8297 return BTy->getKind() == BuiltinType::SChar ||
8298 BTy->getKind() == BuiltinType::UChar ||
8299 BTy->getKind() == BuiltinType::Short ||
8300 BTy->getKind() == BuiltinType::UShort ||
8301 BTy->getKind() == BuiltinType::Int ||
8302 BTy->getKind() == BuiltinType::UInt ||
8303 BTy->getKind() == BuiltinType::Long ||
8304 BTy->getKind() == BuiltinType::ULong ||
8305 BTy->getKind() == BuiltinType::LongLong ||
8306 BTy->getKind() == BuiltinType::ULongLong ||
8307 BTy->getKind() == BuiltinType::Float ||
8308 BTy->getKind() == BuiltinType::Half ||
8309 BTy->getKind() == BuiltinType::BFloat16;
8310}
8311
8313 llvm::APSInt &Result) {
8314 const auto *AttrExpr = Attr.getArgAsExpr(0);
8315 if (!AttrExpr->isTypeDependent()) {
8316 if (std::optional<llvm::APSInt> Res =
8317 AttrExpr->getIntegerConstantExpr(S.Context)) {
8318 Result = *Res;
8319 return true;
8320 }
8321 }
8322 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8323 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8324 Attr.setInvalid();
8325 return false;
8326}
8327
8328/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8329/// "neon_polyvector_type" attributes are used to create vector types that
8330/// are mangled according to ARM's ABI. Otherwise, these types are identical
8331/// to those created with the "vector_size" attribute. Unlike "vector_size"
8332/// the argument to these Neon attributes is the number of vector elements,
8333/// not the vector size in bytes. The vector width and element type must
8334/// match one of the standard Neon vector types.
8336 Sema &S, VectorKind VecKind) {
8337 bool IsTargetCUDAAndHostARM = false;
8338 if (S.getLangOpts().CUDAIsDevice) {
8339 const TargetInfo *AuxTI = S.getASTContext().getAuxTargetInfo();
8340 IsTargetCUDAAndHostARM =
8341 AuxTI && (AuxTI->getTriple().isAArch64() || AuxTI->getTriple().isARM());
8342 }
8343
8344 // Target must have NEON (or MVE, whose vectors are similar enough
8345 // not to need a separate attribute)
8346 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8347 VecKind == VectorKind::Neon &&
8348 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8349 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8350 << Attr << "'mve'";
8351 Attr.setInvalid();
8352 return;
8353 }
8354 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8355 VecKind == VectorKind::NeonPoly &&
8356 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8357 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8358 << Attr << "'mve'";
8359 Attr.setInvalid();
8360 return;
8361 }
8362
8363 // Check the attribute arguments.
8364 if (Attr.getNumArgs() != 1) {
8365 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8366 << Attr << 1;
8367 Attr.setInvalid();
8368 return;
8369 }
8370 // The number of elements must be an ICE.
8371 llvm::APSInt numEltsInt(32);
8372 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8373 return;
8374
8375 // Only certain element types are supported for Neon vectors.
8376 if (!isPermittedNeonBaseType(CurType, VecKind, S) &&
8377 !IsTargetCUDAAndHostARM) {
8378 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8379 Attr.setInvalid();
8380 return;
8381 }
8382
8383 // The total size of the vector must be 64 or 128 bits.
8384 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8385 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8386 unsigned vecSize = typeSize * numElts;
8387 if (vecSize != 64 && vecSize != 128) {
8388 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8389 Attr.setInvalid();
8390 return;
8391 }
8392
8393 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8394}
8395
8396/// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8397/// used to create fixed-length versions of sizeless SVE types defined by
8398/// the ACLE, such as svint32_t and svbool_t.
8400 Sema &S) {
8401 // Target must have SVE.
8402 if (!S.Context.getTargetInfo().hasFeature("sve")) {
8403 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8404 Attr.setInvalid();
8405 return;
8406 }
8407
8408 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8409 // if <bits>+ syntax is used.
8410 if (!S.getLangOpts().VScaleMin ||
8411 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8412 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8413 << Attr;
8414 Attr.setInvalid();
8415 return;
8416 }
8417
8418 // Check the attribute arguments.
8419 if (Attr.getNumArgs() != 1) {
8420 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8421 << Attr << 1;
8422 Attr.setInvalid();
8423 return;
8424 }
8425
8426 // The vector size must be an integer constant expression.
8427 llvm::APSInt SveVectorSizeInBits(32);
8428 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8429 return;
8430
8431 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8432
8433 // The attribute vector size must match -msve-vector-bits.
8434 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8435 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8436 << VecSize << S.getLangOpts().VScaleMin * 128;
8437 Attr.setInvalid();
8438 return;
8439 }
8440
8441 // Attribute can only be attached to a single SVE vector or predicate type.
8442 if (!CurType->isSveVLSBuiltinType()) {
8443 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8444 << Attr << CurType;
8445 Attr.setInvalid();
8446 return;
8447 }
8448
8449 const auto *BT = CurType->castAs<BuiltinType>();
8450
8451 QualType EltType = CurType->getSveEltType(S.Context);
8452 unsigned TypeSize = S.Context.getTypeSize(EltType);
8454 if (BT->getKind() == BuiltinType::SveBool) {
8455 // Predicates are represented as i8.
8456 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8458 } else
8459 VecSize /= TypeSize;
8460 CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8461}
8462
8463static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8464 QualType &CurType,
8465 ParsedAttr &Attr) {
8466 const VectorType *VT = dyn_cast<VectorType>(CurType);
8467 if (!VT || VT->getVectorKind() != VectorKind::Neon) {
8468 State.getSema().Diag(Attr.getLoc(),
8469 diag::err_attribute_arm_mve_polymorphism);
8470 Attr.setInvalid();
8471 return;
8472 }
8473
8474 CurType =
8475 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8476 State.getSema().Context, Attr),
8477 CurType, CurType);
8478}
8479
8480/// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8481/// used to create fixed-length versions of sizeless RVV types such as
8482/// vint8m1_t_t.
8484 ParsedAttr &Attr, Sema &S) {
8485 // Target must have vector extension.
8486 if (!S.Context.getTargetInfo().hasFeature("zve32x")) {
8487 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8488 << Attr << "'zve32x'";
8489 Attr.setInvalid();
8490 return;
8491 }
8492
8493 auto VScale = S.Context.getTargetInfo().getVScaleRange(S.getLangOpts());
8494 if (!VScale || !VScale->first || VScale->first != VScale->second) {
8495 S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported)
8496 << Attr;
8497 Attr.setInvalid();
8498 return;
8499 }
8500
8501 // Check the attribute arguments.
8502 if (Attr.getNumArgs() != 1) {
8503 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8504 << Attr << 1;
8505 Attr.setInvalid();
8506 return;
8507 }
8508
8509 // The vector size must be an integer constant expression.
8510 llvm::APSInt RVVVectorSizeInBits(32);
8511 if (!verifyValidIntegerConstantExpr(S, Attr, RVVVectorSizeInBits))
8512 return;
8513
8514 // Attribute can only be attached to a single RVV vector type.
8515 if (!CurType->isRVVVLSBuiltinType()) {
8516 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type)
8517 << Attr << CurType;
8518 Attr.setInvalid();
8519 return;
8520 }
8521
8522 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8523
8526 unsigned MinElts = Info.EC.getKnownMinValue();
8527
8529 unsigned ExpectedSize = VScale->first * MinElts;
8530 QualType EltType = CurType->getRVVEltType(S.Context);
8531 unsigned EltSize = S.Context.getTypeSize(EltType);
8532 unsigned NumElts;
8533 if (Info.ElementType == S.Context.BoolTy) {
8534 NumElts = VecSize / S.Context.getCharWidth();
8535 if (!NumElts) {
8536 NumElts = 1;
8537 switch (VecSize) {
8538 case 1:
8540 break;
8541 case 2:
8543 break;
8544 case 4:
8546 break;
8547 }
8548 } else
8550 } else {
8551 ExpectedSize *= EltSize;
8552 NumElts = VecSize / EltSize;
8553 }
8554
8555 // The attribute vector size must match -mrvv-vector-bits.
8556 if (VecSize != ExpectedSize) {
8557 S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size)
8558 << VecSize << ExpectedSize;
8559 Attr.setInvalid();
8560 return;
8561 }
8562
8563 CurType = S.Context.getVectorType(EltType, NumElts, VecKind);
8564}
8565
8566/// Handle OpenCL Access Qualifier Attribute.
8567static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8568 Sema &S) {
8569 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8570 if (!(CurType->isImageType() || CurType->isPipeType())) {
8571 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8572 Attr.setInvalid();
8573 return;
8574 }
8575
8576 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8577 QualType BaseTy = TypedefTy->desugar();
8578
8579 std::string PrevAccessQual;
8580 if (BaseTy->isPipeType()) {
8581 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8582 OpenCLAccessAttr *Attr =
8583 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8584 PrevAccessQual = Attr->getSpelling();
8585 } else {
8586 PrevAccessQual = "read_only";
8587 }
8588 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8589
8590 switch (ImgType->getKind()) {
8591 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8592 case BuiltinType::Id: \
8593 PrevAccessQual = #Access; \
8594 break;
8595 #include "clang/Basic/OpenCLImageTypes.def"
8596 default:
8597 llvm_unreachable("Unable to find corresponding image type.");
8598 }
8599 } else {
8600 llvm_unreachable("unexpected type");
8601 }
8602 StringRef AttrName = Attr.getAttrName()->getName();
8603 if (PrevAccessQual == AttrName.ltrim("_")) {
8604 // Duplicated qualifiers
8605 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8606 << AttrName << Attr.getRange();
8607 } else {
8608 // Contradicting qualifiers
8609 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8610 }
8611
8612 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8613 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8614 } else if (CurType->isPipeType()) {
8615 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8616 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8617 CurType = S.Context.getWritePipeType(ElemType);
8618 }
8619 }
8620}
8621
8622/// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8623static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8624 Sema &S) {
8625 if (!S.getLangOpts().MatrixTypes) {
8626 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8627 return;
8628 }
8629
8630 if (Attr.getNumArgs() != 2) {
8631 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8632 << Attr << 2;
8633 return;
8634 }
8635
8636 Expr *RowsExpr = Attr.getArgAsExpr(0);
8637 Expr *ColsExpr = Attr.getArgAsExpr(1);
8638 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8639 if (!T.isNull())
8640 CurType = T;
8641}
8642
8643static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8644 QualType &CurType, const ParsedAttr &PA) {
8645 Sema &S = State.getSema();
8646
8647 if (PA.getNumArgs() < 1) {
8648 S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
8649 return;
8650 }
8651
8652 // Make sure that there is a string literal as the annotation's first
8653 // argument.
8654 StringRef Str;
8655 if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
8656 return;
8657
8659 Args.reserve(PA.getNumArgs() - 1);
8660 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
8661 assert(!PA.isArgIdent(Idx));
8662 Args.push_back(PA.getArgAsExpr(Idx));
8663 }
8664 if (!S.ConstantFoldAttrArgs(PA, Args))
8665 return;
8666 auto *AnnotateTypeAttr =
8667 AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
8668 CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
8669}
8670
8671static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8672 QualType &CurType,
8673 ParsedAttr &Attr) {
8674 if (State.getDeclarator().isDeclarationOfFunction()) {
8675 CurType = State.getAttributedType(
8676 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8677 CurType, CurType);
8678 return;
8679 }
8680 State.getSema().Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
8683}
8684
8685static void HandleLifetimeCaptureByAttr(TypeProcessingState &State,
8686 QualType &CurType, ParsedAttr &PA) {
8687 if (State.getDeclarator().isDeclarationOfFunction()) {
8688 auto *Attr = State.getSema().ParseLifetimeCaptureByAttr(PA, "this");
8689 if (Attr)
8690 CurType = State.getAttributedType(Attr, CurType, CurType);
8691 }
8692}
8693
8694static void HandleHLSLParamModifierAttr(TypeProcessingState &State,
8695 QualType &CurType,
8696 const ParsedAttr &Attr, Sema &S) {
8697 // Don't apply this attribute to template dependent types. It is applied on
8698 // substitution during template instantiation. Also skip parsing this if we've
8699 // already modified the type based on an earlier attribute.
8700 if (CurType->isDependentType() || State.didParseHLSLParamMod())
8701 return;
8702 if (Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout ||
8703 Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out) {
8704 State.setParsedHLSLParamMod(true);
8705 }
8706}
8707
8708static void processTypeAttrs(TypeProcessingState &state, QualType &type,
8709 TypeAttrLocation TAL,
8710 const ParsedAttributesView &attrs,
8711 CUDAFunctionTarget CFT) {
8712
8713 state.setParsedNoDeref(false);
8714 if (attrs.empty())
8715 return;
8716
8717 // Scan through and apply attributes to this type where it makes sense. Some
8718 // attributes (such as __address_space__, __vector_size__, etc) apply to the
8719 // type, but others can be present in the type specifiers even though they
8720 // apply to the decl. Here we apply type attributes and ignore the rest.
8721
8722 // This loop modifies the list pretty frequently, but we still need to make
8723 // sure we visit every element once. Copy the attributes list, and iterate
8724 // over that.
8725 ParsedAttributesView AttrsCopy{attrs};
8726 for (ParsedAttr &attr : AttrsCopy) {
8727
8728 // Skip attributes that were marked to be invalid.
8729 if (attr.isInvalid())
8730 continue;
8731
8732 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) {
8733 // [[gnu::...]] attributes are treated as declaration attributes, so may
8734 // not appertain to a DeclaratorChunk. If we handle them as type
8735 // attributes, accept them in that position and diagnose the GCC
8736 // incompatibility.
8737 if (attr.isGNUScope()) {
8738 assert(attr.isStandardAttributeSyntax());
8739 bool IsTypeAttr = attr.isTypeAttr();
8740 if (TAL == TAL_DeclChunk) {
8741 state.getSema().Diag(attr.getLoc(),
8742 IsTypeAttr
8743 ? diag::warn_gcc_ignores_type_attr
8744 : diag::warn_cxx11_gnu_attribute_on_type)
8745 << attr;
8746 if (!IsTypeAttr)
8747 continue;
8748 }
8749 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
8750 !attr.isTypeAttr()) {
8751 // Otherwise, only consider type processing for a C++11 attribute if
8752 // - it has actually been applied to a type (decl-specifier-seq or
8753 // declarator chunk), or
8754 // - it is a type attribute, irrespective of where it was applied (so
8755 // that we can support the legacy behavior of some type attributes
8756 // that can be applied to the declaration name).
8757 continue;
8758 }
8759 }
8760
8761 // If this is an attribute we can handle, do so now,
8762 // otherwise, add it to the FnAttrs list for rechaining.
8763 switch (attr.getKind()) {
8764 default:
8765 // A [[]] attribute on a declarator chunk must appertain to a type.
8766 if ((attr.isStandardAttributeSyntax() ||
8767 attr.isRegularKeywordAttribute()) &&
8768 TAL == TAL_DeclChunk) {
8769 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
8770 << attr << attr.isRegularKeywordAttribute();
8771 attr.setUsedAsTypeAttr();
8772 }
8773 break;
8774
8776 if (attr.isStandardAttributeSyntax()) {
8777 state.getSema().Diag(attr.getLoc(),
8778 diag::warn_unknown_attribute_ignored)
8779 << attr << attr.getRange();
8780 // Mark the attribute as invalid so we don't emit the same diagnostic
8781 // multiple times.
8782 attr.setInvalid();
8783 }
8784 break;
8785
8787 break;
8788
8789 case ParsedAttr::AT_BTFTypeTag:
8791 attr.setUsedAsTypeAttr();
8792 break;
8793
8794 case ParsedAttr::AT_MayAlias:
8795 // FIXME: This attribute needs to actually be handled, but if we ignore
8796 // it it breaks large amounts of Linux software.
8797 attr.setUsedAsTypeAttr();
8798 break;
8799 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
8800 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
8801 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
8802 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
8803 case ParsedAttr::AT_OpenCLLocalAddressSpace:
8804 case ParsedAttr::AT_OpenCLConstantAddressSpace:
8805 case ParsedAttr::AT_OpenCLGenericAddressSpace:
8806 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
8807 case ParsedAttr::AT_AddressSpace:
8809 attr.setUsedAsTypeAttr();
8810 break;
8812 if (!handleObjCPointerTypeAttr(state, attr, type))
8814 attr.setUsedAsTypeAttr();
8815 break;
8816 case ParsedAttr::AT_VectorSize:
8817 HandleVectorSizeAttr(type, attr, state.getSema());
8818 attr.setUsedAsTypeAttr();
8819 break;
8820 case ParsedAttr::AT_ExtVectorType:
8821 HandleExtVectorTypeAttr(type, attr, state.getSema());
8822 attr.setUsedAsTypeAttr();
8823 break;
8824 case ParsedAttr::AT_NeonVectorType:
8826 attr.setUsedAsTypeAttr();
8827 break;
8828 case ParsedAttr::AT_NeonPolyVectorType:
8829 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8831 attr.setUsedAsTypeAttr();
8832 break;
8833 case ParsedAttr::AT_ArmSveVectorBits:
8834 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
8835 attr.setUsedAsTypeAttr();
8836 break;
8837 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
8839 attr.setUsedAsTypeAttr();
8840 break;
8841 }
8842 case ParsedAttr::AT_RISCVRVVVectorBits:
8843 HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema());
8844 attr.setUsedAsTypeAttr();
8845 break;
8846 case ParsedAttr::AT_OpenCLAccess:
8847 HandleOpenCLAccessAttr(type, attr, state.getSema());
8848 attr.setUsedAsTypeAttr();
8849 break;
8850 case ParsedAttr::AT_LifetimeBound:
8851 if (TAL == TAL_DeclChunk)
8853 break;
8854 case ParsedAttr::AT_LifetimeCaptureBy:
8855 if (TAL == TAL_DeclChunk)
8857 break;
8858
8859 case ParsedAttr::AT_NoDeref: {
8860 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
8861 // See https://github.com/llvm/llvm-project/issues/55790 for details.
8862 // For the time being, we simply emit a warning that the attribute is
8863 // ignored.
8864 if (attr.isStandardAttributeSyntax()) {
8865 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
8866 << attr;
8867 break;
8868 }
8869 ASTContext &Ctx = state.getSema().Context;
8870 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
8871 type, type);
8872 attr.setUsedAsTypeAttr();
8873 state.setParsedNoDeref(true);
8874 break;
8875 }
8876
8877 case ParsedAttr::AT_MatrixType:
8878 HandleMatrixTypeAttr(type, attr, state.getSema());
8879 attr.setUsedAsTypeAttr();
8880 break;
8881
8882 case ParsedAttr::AT_WebAssemblyFuncref: {
8884 attr.setUsedAsTypeAttr();
8885 break;
8886 }
8887
8888 case ParsedAttr::AT_HLSLParamModifier: {
8889 HandleHLSLParamModifierAttr(state, type, attr, state.getSema());
8890 attr.setUsedAsTypeAttr();
8891 break;
8892 }
8893
8894 case ParsedAttr::AT_SwiftAttr: {
8895 HandleSwiftAttr(state, TAL, type, attr);
8896 break;
8897 }
8898
8901 attr.setUsedAsTypeAttr();
8902 break;
8903
8904
8906 // Either add nullability here or try to distribute it. We
8907 // don't want to distribute the nullability specifier past any
8908 // dependent type, because that complicates the user model.
8909 if (type->canHaveNullability() || type->isDependentType() ||
8910 type->isArrayType() ||
8912 unsigned endIndex;
8913 if (TAL == TAL_DeclChunk)
8914 endIndex = state.getCurrentChunkIndex();
8915 else
8916 endIndex = state.getDeclarator().getNumTypeObjects();
8917 bool allowOnArrayType =
8918 state.getDeclarator().isPrototypeContext() &&
8919 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
8921 allowOnArrayType)) {
8922 attr.setInvalid();
8923 }
8924
8925 attr.setUsedAsTypeAttr();
8926 }
8927 break;
8928
8929 case ParsedAttr::AT_ObjCKindOf:
8930 // '__kindof' must be part of the decl-specifiers.
8931 switch (TAL) {
8932 case TAL_DeclSpec:
8933 break;
8934
8935 case TAL_DeclChunk:
8936 case TAL_DeclName:
8937 state.getSema().Diag(attr.getLoc(),
8938 diag::err_objc_kindof_wrong_position)
8939 << FixItHint::CreateRemoval(attr.getLoc())
8941 state.getDeclarator().getDeclSpec().getBeginLoc(),
8942 "__kindof ");
8943 break;
8944 }
8945
8946 // Apply it regardless.
8947 if (checkObjCKindOfType(state, type, attr))
8948 attr.setInvalid();
8949 break;
8950
8951 case ParsedAttr::AT_NoThrow:
8952 // Exception Specifications aren't generally supported in C mode throughout
8953 // clang, so revert to attribute-based handling for C.
8954 if (!state.getSema().getLangOpts().CPlusPlus)
8955 break;
8956 [[fallthrough]];
8958 attr.setUsedAsTypeAttr();
8959
8960 // Attributes with standard syntax have strict rules for what they
8961 // appertain to and hence should not use the "distribution" logic below.
8962 if (attr.isStandardAttributeSyntax() ||
8963 attr.isRegularKeywordAttribute()) {
8964 if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
8965 diagnoseBadTypeAttribute(state.getSema(), attr, type);
8966 attr.setInvalid();
8967 }
8968 break;
8969 }
8970
8971 // Never process function type attributes as part of the
8972 // declaration-specifiers.
8973 if (TAL == TAL_DeclSpec)
8975
8976 // Otherwise, handle the possible delays.
8977 else if (!handleFunctionTypeAttr(state, attr, type, CFT))
8979 break;
8980 case ParsedAttr::AT_AcquireHandle: {
8981 if (!type->isFunctionType())
8982 return;
8983
8984 if (attr.getNumArgs() != 1) {
8985 state.getSema().Diag(attr.getLoc(),
8986 diag::err_attribute_wrong_number_arguments)
8987 << attr << 1;
8988 attr.setInvalid();
8989 return;
8990 }
8991
8992 StringRef HandleType;
8993 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
8994 return;
8995 type = state.getAttributedType(
8996 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
8997 type, type);
8998 attr.setUsedAsTypeAttr();
8999 break;
9000 }
9001 case ParsedAttr::AT_AnnotateType: {
9003 attr.setUsedAsTypeAttr();
9004 break;
9005 }
9006 case ParsedAttr::AT_HLSLResourceClass:
9007 case ParsedAttr::AT_HLSLROV:
9008 case ParsedAttr::AT_HLSLRawBuffer:
9009 case ParsedAttr::AT_HLSLContainedType: {
9010 // Only collect HLSL resource type attributes that are in
9011 // decl-specifier-seq; do not collect attributes on declarations or those
9012 // that get to slide after declaration name.
9013 if (TAL == TAL_DeclSpec &&
9014 state.getSema().HLSL().handleResourceTypeAttr(type, attr))
9015 attr.setUsedAsTypeAttr();
9016 break;
9017 }
9018 }
9019
9020 // Handle attributes that are defined in a macro. We do not want this to be
9021 // applied to ObjC builtin attributes.
9022 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
9023 !type.getQualifiers().hasObjCLifetime() &&
9024 !type.getQualifiers().hasObjCGCAttr() &&
9025 attr.getKind() != ParsedAttr::AT_ObjCGC &&
9026 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
9027 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
9028 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
9029 state.setExpansionLocForMacroQualifiedType(
9030 cast<MacroQualifiedType>(type.getTypePtr()),
9031 attr.getMacroExpansionLoc());
9032 }
9033 }
9034}
9035
9037 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
9038 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9039 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
9040 auto *Def = Var->getDefinition();
9041 if (!Def) {
9042 SourceLocation PointOfInstantiation = E->getExprLoc();
9043 runWithSufficientStackSpace(PointOfInstantiation, [&] {
9044 InstantiateVariableDefinition(PointOfInstantiation, Var);
9045 });
9046 Def = Var->getDefinition();
9047
9048 // If we don't already have a point of instantiation, and we managed
9049 // to instantiate a definition, this is the point of instantiation.
9050 // Otherwise, we don't request an end-of-TU instantiation, so this is
9051 // not a point of instantiation.
9052 // FIXME: Is this really the right behavior?
9053 if (Var->getPointOfInstantiation().isInvalid() && Def) {
9054 assert(Var->getTemplateSpecializationKind() ==
9056 "explicit instantiation with no point of instantiation");
9057 Var->setTemplateSpecializationKind(
9058 Var->getTemplateSpecializationKind(), PointOfInstantiation);
9059 }
9060 }
9061
9062 // Update the type to the definition's type both here and within the
9063 // expression.
9064 if (Def) {
9065 DRE->setDecl(Def);
9066 QualType T = Def->getType();
9067 DRE->setType(T);
9068 // FIXME: Update the type on all intervening expressions.
9069 E->setType(T);
9070 }
9071
9072 // We still go on to try to complete the type independently, as it
9073 // may also require instantiations or diagnostics if it remains
9074 // incomplete.
9075 }
9076 }
9077 }
9078 if (const auto CastE = dyn_cast<ExplicitCastExpr>(E)) {
9079 QualType DestType = CastE->getTypeAsWritten();
9080 if (const auto *IAT = Context.getAsIncompleteArrayType(DestType)) {
9081 // C++20 [expr.static.cast]p.4: ... If T is array of unknown bound,
9082 // this direct-initialization defines the type of the expression
9083 // as U[1]
9085 IAT->getElementType(),
9086 llvm::APInt(Context.getTypeSize(Context.getSizeType()), 1),
9087 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal,
9088 /*IndexTypeQuals=*/0);
9089 E->setType(ResultType);
9090 }
9091 }
9092}
9093
9095 // Incomplete array types may be completed by the initializer attached to
9096 // their definitions. For static data members of class templates and for
9097 // variable templates, we need to instantiate the definition to get this
9098 // initializer and complete the type.
9101
9102 // FIXME: Are there other cases which require instantiating something other
9103 // than the type to complete the type of an expression?
9104
9105 return E->getType();
9106}
9107
9109 TypeDiagnoser &Diagnoser) {
9111 Diagnoser);
9112}
9113
9114bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9115 BoundTypeDiagnoser<> Diagnoser(DiagID);
9117}
9118
9120 CompleteTypeKind Kind,
9121 TypeDiagnoser &Diagnoser) {
9122 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
9123 return true;
9124 if (const TagType *Tag = T->getAs<TagType>()) {
9125 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
9126 Tag->getDecl()->setCompleteDefinitionRequired();
9128 }
9129 }
9130 return false;
9131}
9132
9135 if (!Suggested)
9136 return false;
9137
9138 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9139 // and isolate from other C++ specific checks.
9141 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
9143 false /*StrictTypeSpelling*/, true /*Complain*/,
9144 true /*ErrorOnTagTypeMismatch*/);
9145 return Ctx.IsEquivalent(D, Suggested);
9146}
9147
9149 AcceptableKind Kind, bool OnlyNeedComplete) {
9150 // Easy case: if we don't have modules, all declarations are visible.
9151 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9152 return true;
9153
9154 // If this definition was instantiated from a template, map back to the
9155 // pattern from which it was instantiated.
9156 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
9157 // We're in the middle of defining it; this definition should be treated
9158 // as visible.
9159 return true;
9160 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9161 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9162 RD = Pattern;
9163 D = RD->getDefinition();
9164 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
9165 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9166 ED = Pattern;
9167 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9168 // If the enum has a fixed underlying type, it may have been forward
9169 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9170 // the enum and assign it the underlying type of `int`. Since we're only
9171 // looking for a complete type (not a definition), any visible declaration
9172 // of it will do.
9173 *Suggested = nullptr;
9174 for (auto *Redecl : ED->redecls()) {
9175 if (isAcceptable(Redecl, Kind))
9176 return true;
9177 if (Redecl->isThisDeclarationADefinition() ||
9178 (Redecl->isCanonicalDecl() && !*Suggested))
9179 *Suggested = Redecl;
9180 }
9181
9182 return false;
9183 }
9184 D = ED->getDefinition();
9185 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
9186 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9187 FD = Pattern;
9188 D = FD->getDefinition();
9189 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
9190 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9191 VD = Pattern;
9192 D = VD->getDefinition();
9193 }
9194
9195 assert(D && "missing definition for pattern of instantiated definition");
9196
9197 *Suggested = D;
9198
9199 auto DefinitionIsAcceptable = [&] {
9200 // The (primary) definition might be in a visible module.
9201 if (isAcceptable(D, Kind))
9202 return true;
9203
9204 // A visible module might have a merged definition instead.
9207 if (CodeSynthesisContexts.empty() &&
9208 !getLangOpts().ModulesLocalVisibility) {
9209 // Cache the fact that this definition is implicitly visible because
9210 // there is a visible merged definition.
9212 }
9213 return true;
9214 }
9215
9216 return false;
9217 };
9218
9219 if (DefinitionIsAcceptable())
9220 return true;
9221
9222 // The external source may have additional definitions of this entity that are
9223 // visible, so complete the redeclaration chain now and ask again.
9224 if (auto *Source = Context.getExternalSource()) {
9225 Source->CompleteRedeclChain(D);
9226 return DefinitionIsAcceptable();
9227 }
9228
9229 return false;
9230}
9231
9232/// Determine whether there is any declaration of \p D that was ever a
9233/// definition (perhaps before module merging) and is currently visible.
9234/// \param D The definition of the entity.
9235/// \param Suggested Filled in with the declaration that should be made visible
9236/// in order to provide a definition of this entity.
9237/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9238/// not defined. This only matters for enums with a fixed underlying
9239/// type, since in all other cases, a type is complete if and only if it
9240/// is defined.
9242 bool OnlyNeedComplete) {
9244 OnlyNeedComplete);
9245}
9246
9247/// Determine whether there is any declaration of \p D that was ever a
9248/// definition (perhaps before module merging) and is currently
9249/// reachable.
9250/// \param D The definition of the entity.
9251/// \param Suggested Filled in with the declaration that should be made
9252/// reachable
9253/// in order to provide a definition of this entity.
9254/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9255/// not defined. This only matters for enums with a fixed underlying
9256/// type, since in all other cases, a type is complete if and only if it
9257/// is defined.
9259 bool OnlyNeedComplete) {
9261 OnlyNeedComplete);
9262}
9263
9264/// Locks in the inheritance model for the given class and all of its bases.
9267 if (!RD->hasAttr<MSInheritanceAttr>()) {
9269 bool BestCase = false;
9272 BestCase = true;
9273 IM = RD->calculateInheritanceModel();
9274 break;
9277 break;
9280 break;
9283 break;
9284 }
9285
9288 : RD->getSourceRange();
9289 RD->addAttr(MSInheritanceAttr::CreateImplicit(
9290 S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
9292 }
9293}
9294
9295bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9296 CompleteTypeKind Kind,
9297 TypeDiagnoser *Diagnoser) {
9298 // FIXME: Add this assertion to make sure we always get instantiation points.
9299 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9300 // FIXME: Add this assertion to help us flush out problems with
9301 // checking for dependent types and type-dependent expressions.
9302 //
9303 // assert(!T->isDependentType() &&
9304 // "Can't ask whether a dependent type is complete");
9305
9306 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
9307 if (!MPTy->getClass()->isDependentType()) {
9308 if (getLangOpts().CompleteMemberPointers &&
9309 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
9310 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind,
9311 diag::err_memptr_incomplete))
9312 return true;
9313
9314 // We lock in the inheritance model once somebody has asked us to ensure
9315 // that a pointer-to-member type is complete.
9317 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
9318 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
9319 }
9320 }
9321 }
9322
9323 NamedDecl *Def = nullptr;
9325 bool Incomplete = (T->isIncompleteType(&Def) ||
9327
9328 // Check that any necessary explicit specializations are visible. For an
9329 // enum, we just need the declaration, so don't check this.
9330 if (Def && !isa<EnumDecl>(Def))
9332
9333 // If we have a complete type, we're done.
9334 if (!Incomplete) {
9335 NamedDecl *Suggested = nullptr;
9336 if (Def &&
9337 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
9338 // If the user is going to see an error here, recover by making the
9339 // definition visible.
9340 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9341 if (Diagnoser && Suggested)
9343 /*Recover*/ TreatAsComplete);
9344 return !TreatAsComplete;
9345 } else if (Def && !TemplateInstCallbacks.empty()) {
9346 CodeSynthesisContext TempInst;
9347 TempInst.Kind = CodeSynthesisContext::Memoization;
9348 TempInst.Template = Def;
9349 TempInst.Entity = Def;
9350 TempInst.PointOfInstantiation = Loc;
9351 atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
9352 atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
9353 }
9354
9355 return false;
9356 }
9357
9358 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
9359 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
9360
9361 // Give the external source a chance to provide a definition of the type.
9362 // This is kept separate from completing the redeclaration chain so that
9363 // external sources such as LLDB can avoid synthesizing a type definition
9364 // unless it's actually needed.
9365 if (Tag || IFace) {
9366 // Avoid diagnosing invalid decls as incomplete.
9367 if (Def->isInvalidDecl())
9368 return true;
9369
9370 // Give the external AST source a chance to complete the type.
9371 if (auto *Source = Context.getExternalSource()) {
9372 if (Tag && Tag->hasExternalLexicalStorage())
9373 Source->CompleteType(Tag);
9374 if (IFace && IFace->hasExternalLexicalStorage())
9375 Source->CompleteType(IFace);
9376 // If the external source completed the type, go through the motions
9377 // again to ensure we're allowed to use the completed type.
9378 if (!T->isIncompleteType())
9379 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9380 }
9381 }
9382
9383 // If we have a class template specialization or a class member of a
9384 // class template specialization, or an array with known size of such,
9385 // try to instantiate it.
9386 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
9387 bool Instantiated = false;
9388 bool Diagnosed = false;
9389 if (RD->isDependentContext()) {
9390 // Don't try to instantiate a dependent class (eg, a member template of
9391 // an instantiated class template specialization).
9392 // FIXME: Can this ever happen?
9393 } else if (auto *ClassTemplateSpec =
9394 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
9395 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9398 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9399 /*Complain=*/Diagnoser);
9400 });
9401 Instantiated = true;
9402 }
9403 } else {
9405 if (!RD->isBeingDefined() && Pattern) {
9406 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9407 assert(MSI && "Missing member specialization information?");
9408 // This record was instantiated from a class within a template.
9409 if (MSI->getTemplateSpecializationKind() !=
9412 Diagnosed = InstantiateClass(Loc, RD, Pattern,
9415 /*Complain=*/Diagnoser);
9416 });
9417 Instantiated = true;
9418 }
9419 }
9420 }
9421
9422 if (Instantiated) {
9423 // Instantiate* might have already complained that the template is not
9424 // defined, if we asked it to.
9425 if (Diagnoser && Diagnosed)
9426 return true;
9427 // If we instantiated a definition, check that it's usable, even if
9428 // instantiation produced an error, so that repeated calls to this
9429 // function give consistent answers.
9430 if (!T->isIncompleteType())
9431 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9432 }
9433 }
9434
9435 // FIXME: If we didn't instantiate a definition because of an explicit
9436 // specialization declaration, check that it's visible.
9437
9438 if (!Diagnoser)
9439 return true;
9440
9441 Diagnoser->diagnose(*this, Loc, T);
9442
9443 // If the type was a forward declaration of a class/struct/union
9444 // type, produce a note.
9445 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9446 Diag(Tag->getLocation(),
9447 Tag->isBeingDefined() ? diag::note_type_being_defined
9448 : diag::note_forward_declaration)
9449 << Context.getTagDeclType(Tag);
9450
9451 // If the Objective-C class was a forward declaration, produce a note.
9452 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9453 Diag(IFace->getLocation(), diag::note_forward_class);
9454
9455 // If we have external information that we can use to suggest a fix,
9456 // produce a note.
9457 if (ExternalSource)
9458 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9459
9460 return true;
9461}
9462
9464 CompleteTypeKind Kind, unsigned DiagID) {
9465 BoundTypeDiagnoser<> Diagnoser(DiagID);
9466 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9467}
9468
9469/// Get diagnostic %select index for tag kind for
9470/// literal type diagnostic message.
9471/// WARNING: Indexes apply to particular diagnostics only!
9472///
9473/// \returns diagnostic %select index.
9475 switch (Tag) {
9477 return 0;
9479 return 1;
9480 case TagTypeKind::Class:
9481 return 2;
9482 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9483 }
9484}
9485
9487 TypeDiagnoser &Diagnoser) {
9488 assert(!T->isDependentType() && "type should not be dependent");
9489
9491 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9493 return false;
9494
9495 Diagnoser.diagnose(*this, Loc, T);
9496
9497 if (T->isVariableArrayType())
9498 return true;
9499
9500 const RecordType *RT = ElemType->getAs<RecordType>();
9501 if (!RT)
9502 return true;
9503
9504 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
9505
9506 // A partially-defined class type can't be a literal type, because a literal
9507 // class type must have a trivial destructor (which can't be checked until
9508 // the class definition is complete).
9509 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9510 return true;
9511
9512 // [expr.prim.lambda]p3:
9513 // This class type is [not] a literal type.
9514 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9515 Diag(RD->getLocation(), diag::note_non_literal_lambda);
9516 return true;
9517 }
9518
9519 // If the class has virtual base classes, then it's not an aggregate, and
9520 // cannot have any constexpr constructors or a trivial default constructor,
9521 // so is non-literal. This is better to diagnose than the resulting absence
9522 // of constexpr constructors.
9523 if (RD->getNumVBases()) {
9524 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9526 for (const auto &I : RD->vbases())
9527 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9528 << I.getSourceRange();
9529 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9531 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9532 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9533 for (const auto &I : RD->bases()) {
9534 if (!I.getType()->isLiteralType(Context)) {
9535 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9536 << RD << I.getType() << I.getSourceRange();
9537 return true;
9538 }
9539 }
9540 for (const auto *I : RD->fields()) {
9541 if (!I->getType()->isLiteralType(Context) ||
9542 I->getType().isVolatileQualified()) {
9543 Diag(I->getLocation(), diag::note_non_literal_field)
9544 << RD << I << I->getType()
9545 << I->getType().isVolatileQualified();
9546 return true;
9547 }
9548 }
9549 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
9550 : !RD->hasTrivialDestructor()) {
9551 // All fields and bases are of literal types, so have trivial or constexpr
9552 // destructors. If this class's destructor is non-trivial / non-constexpr,
9553 // it must be user-declared.
9554 CXXDestructorDecl *Dtor = RD->getDestructor();
9555 assert(Dtor && "class has literal fields and bases but no dtor?");
9556 if (!Dtor)
9557 return true;
9558
9559 if (getLangOpts().CPlusPlus20) {
9560 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
9561 << RD;
9562 } else {
9563 Diag(Dtor->getLocation(), Dtor->isUserProvided()
9564 ? diag::note_non_literal_user_provided_dtor
9565 : diag::note_non_literal_nontrivial_dtor)
9566 << RD;
9567 if (!Dtor->isUserProvided())
9570 /*Diagnose*/ true);
9571 }
9572 }
9573
9574 return true;
9575}
9576
9578 BoundTypeDiagnoser<> Diagnoser(DiagID);
9579 return RequireLiteralType(Loc, T, Diagnoser);
9580}
9581
9583 const CXXScopeSpec &SS, QualType T,
9584 TagDecl *OwnedTagDecl) {
9585 if (T.isNull())
9586 return T;
9588 Keyword, SS.isValid() ? SS.getScopeRep() : nullptr, T, OwnedTagDecl);
9589}
9590
9592 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9593
9595 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
9596 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
9597
9598 if (!E->isTypeDependent()) {
9599 QualType T = E->getType();
9600 if (const TagType *TT = T->getAs<TagType>())
9601 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
9602 }
9603 return Context.getTypeOfExprType(E, Kind);
9604}
9605
9606static void
9609 // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl.
9610 auto *CountDecl = cast<DeclRefExpr>(E)->getDecl();
9611 Decls.push_back(TypeCoupledDeclRefInfo(CountDecl, /*IsDref*/ false));
9612}
9613
9615 Expr *CountExpr,
9616 bool CountInBytes,
9617 bool OrNull) {
9618 assert(WrappedTy->isIncompleteArrayType() || WrappedTy->isPointerType());
9619
9621 BuildTypeCoupledDecls(CountExpr, Decls);
9622 /// When the resulting expression is invalid, we still create the AST using
9623 /// the original count expression for the sake of AST dump.
9624 return Context.getCountAttributedType(WrappedTy, CountExpr, CountInBytes,
9625 OrNull, Decls);
9626}
9627
9628/// getDecltypeForExpr - Given an expr, will return the decltype for
9629/// that expression, according to the rules in C++11
9630/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
9632
9633 Expr *IDExpr = E;
9634 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
9635 IDExpr = ImplCastExpr->getSubExpr();
9636
9637 if (auto *PackExpr = dyn_cast<PackIndexingExpr>(E)) {
9639 IDExpr = PackExpr->getPackIdExpression();
9640 else
9641 IDExpr = PackExpr->getSelectedExpr();
9642 }
9643
9644 if (E->isTypeDependent())
9645 return Context.DependentTy;
9646
9647 // C++11 [dcl.type.simple]p4:
9648 // The type denoted by decltype(e) is defined as follows:
9649
9650 // C++20:
9651 // - if E is an unparenthesized id-expression naming a non-type
9652 // template-parameter (13.2), decltype(E) is the type of the
9653 // template-parameter after performing any necessary type deduction
9654 // Note that this does not pick up the implicit 'const' for a template
9655 // parameter object. This rule makes no difference before C++20 so we apply
9656 // it unconditionally.
9657 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
9658 return SNTTPE->getParameterType(Context);
9659
9660 // - if e is an unparenthesized id-expression or an unparenthesized class
9661 // member access (5.2.5), decltype(e) is the type of the entity named
9662 // by e. If there is no such entity, or if e names a set of overloaded
9663 // functions, the program is ill-formed;
9664 //
9665 // We apply the same rules for Objective-C ivar and property references.
9666 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
9667 const ValueDecl *VD = DRE->getDecl();
9668 QualType T = VD->getType();
9669 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
9670 }
9671 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
9672 if (const auto *VD = ME->getMemberDecl())
9673 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
9674 return VD->getType();
9675 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
9676 return IR->getDecl()->getType();
9677 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
9678 if (PR->isExplicitProperty())
9679 return PR->getExplicitProperty()->getType();
9680 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
9681 return PE->getType();
9682 }
9683
9684 // C++11 [expr.lambda.prim]p18:
9685 // Every occurrence of decltype((x)) where x is a possibly
9686 // parenthesized id-expression that names an entity of automatic
9687 // storage duration is treated as if x were transformed into an
9688 // access to a corresponding data member of the closure type that
9689 // would have been declared if x were an odr-use of the denoted
9690 // entity.
9691 if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
9692 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
9693 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9694 QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
9695 if (!T.isNull())
9697 }
9698 }
9699 }
9700
9702}
9703
9705 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9706
9707 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
9709 // The expression operand for decltype is in an unevaluated expression
9710 // context, so side effects could result in unintended consequences.
9711 // Exclude instantiation-dependent expressions, because 'decltype' is often
9712 // used to build SFINAE gadgets.
9713 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
9714 }
9716}
9717
9720 SourceLocation EllipsisLoc) {
9721 if (!IndexExpr)
9722 return QualType();
9723
9724 // Diagnose unexpanded packs but continue to improve recovery.
9725 if (!Pattern->containsUnexpandedParameterPack())
9726 Diag(Loc, diag::err_expected_name_of_pack) << Pattern;
9727
9728 QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc, EllipsisLoc);
9729
9730 if (!Type.isNull())
9731 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::warn_cxx23_pack_indexing
9732 : diag::ext_pack_indexing);
9733 return Type;
9734}
9735
9738 SourceLocation EllipsisLoc,
9739 bool FullySubstituted,
9740 ArrayRef<QualType> Expansions) {
9741
9742 std::optional<int64_t> Index;
9743 if (FullySubstituted && !IndexExpr->isValueDependent() &&
9744 !IndexExpr->isTypeDependent()) {
9745 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
9747 IndexExpr, Context.getSizeType(), Value, CCEK_ArrayBound);
9748 if (!Res.isUsable())
9749 return QualType();
9750 Index = Value.getExtValue();
9751 IndexExpr = Res.get();
9752 }
9753
9754 if (FullySubstituted && Index) {
9755 if (*Index < 0 || *Index >= int64_t(Expansions.size())) {
9756 Diag(IndexExpr->getBeginLoc(), diag::err_pack_index_out_of_bound)
9757 << *Index << Pattern << Expansions.size();
9758 return QualType();
9759 }
9760 }
9761
9762 return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted,
9763 Expansions, Index.value_or(-1));
9764}
9765
9768 assert(BaseType->isEnumeralType());
9769 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
9770 assert(ED && "EnumType has no EnumDecl");
9771
9772 S.DiagnoseUseOfDecl(ED, Loc);
9773
9774 QualType Underlying = ED->getIntegerType();
9775 assert(!Underlying.isNull());
9776
9777 return Underlying;
9778}
9779
9782 if (!BaseType->isEnumeralType()) {
9783 Diag(Loc, diag::err_only_enums_have_underlying_types);
9784 return QualType();
9785 }
9786
9787 // The enum could be incomplete if we're parsing its definition or
9788 // recovering from an error.
9789 NamedDecl *FwdDecl = nullptr;
9790 if (BaseType->isIncompleteType(&FwdDecl)) {
9791 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
9792 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
9793 return QualType();
9794 }
9795
9796 return GetEnumUnderlyingType(*this, BaseType, Loc);
9797}
9798
9800 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
9803 : BaseType;
9804
9805 return Pointer.isNull() ? QualType() : Pointer;
9806}
9807
9809 // We don't want block pointers or ObjectiveC's id type.
9810 if (!BaseType->isAnyPointerType() || BaseType->isObjCIdType())
9811 return BaseType;
9812
9813 return BaseType->getPointeeType();
9814}
9815
9817 QualType Underlying = BaseType.getNonReferenceType();
9818 if (Underlying->isArrayType())
9819 return Context.getDecayedType(Underlying);
9820
9821 if (Underlying->isFunctionType())
9822 return BuiltinAddPointer(BaseType, Loc);
9823
9824 SplitQualType Split = Underlying.getSplitUnqualifiedType();
9825 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
9826 // in the same group of qualifiers as 'const' and 'volatile', we're extending
9827 // '__decay(T)' so that it removes all qualifiers.
9828 Split.Quals.removeCVRQualifiers();
9829 return Context.getQualifiedType(Split);
9830}
9831
9834 assert(LangOpts.CPlusPlus);
9836 BaseType.isReferenceable()
9837 ? BuildReferenceType(BaseType,
9838 UKind == UnaryTransformType::AddLvalueReference,
9840 : BaseType;
9841 return Reference.isNull() ? QualType() : Reference;
9842}
9843
9846 if (UKind == UnaryTransformType::RemoveAllExtents)
9847 return Context.getBaseElementType(BaseType);
9848
9849 if (const auto *AT = Context.getAsArrayType(BaseType))
9850 return AT->getElementType();
9851
9852 return BaseType;
9853}
9854
9857 assert(LangOpts.CPlusPlus);
9858 QualType T = BaseType.getNonReferenceType();
9859 if (UKind == UTTKind::RemoveCVRef &&
9860 (T.isConstQualified() || T.isVolatileQualified())) {
9861 Qualifiers Quals;
9862 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
9863 Quals.removeConst();
9864 Quals.removeVolatile();
9865 T = Context.getQualifiedType(Unqual, Quals);
9866 }
9867 return T;
9868}
9869
9872 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
9873 BaseType->isFunctionType())
9874 return BaseType;
9875
9876 Qualifiers Quals;
9877 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
9878
9879 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
9880 Quals.removeConst();
9881 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
9882 Quals.removeVolatile();
9883 if (UKind == UTTKind::RemoveRestrict)
9884 Quals.removeRestrict();
9885
9886 return Context.getQualifiedType(Unqual, Quals);
9887}
9888
9890 bool IsMakeSigned,
9892 if (BaseType->isEnumeralType()) {
9893 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
9894 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
9895 unsigned int Bits = BitInt->getNumBits();
9896 if (Bits > 1)
9897 return S.Context.getBitIntType(!IsMakeSigned, Bits);
9898
9899 S.Diag(Loc, diag::err_make_signed_integral_only)
9900 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
9901 return QualType();
9902 }
9903 if (Underlying->isBooleanType()) {
9904 S.Diag(Loc, diag::err_make_signed_integral_only)
9905 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
9906 << Underlying;
9907 return QualType();
9908 }
9909 }
9910
9911 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
9912 std::array<CanQualType *, 6> AllSignedIntegers = {
9915 ArrayRef<CanQualType *> AvailableSignedIntegers(
9916 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
9917 std::array<CanQualType *, 6> AllUnsignedIntegers = {
9921 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
9922 AllUnsignedIntegers.size() -
9923 Int128Unsupported);
9924 ArrayRef<CanQualType *> *Consider =
9925 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
9926
9927 uint64_t BaseSize = S.Context.getTypeSize(BaseType);
9928 auto *Result =
9929 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
9930 return BaseSize == S.Context.getTypeSize(T->getTypePtr());
9931 });
9932
9933 assert(Result != Consider->end());
9934 return QualType((*Result)->getTypePtr(), 0);
9935}
9936
9939 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
9940 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
9941 BaseType->isBooleanType() ||
9942 (BaseType->isBitIntType() &&
9943 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
9944 Diag(Loc, diag::err_make_signed_integral_only)
9945 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
9946 return QualType();
9947 }
9948
9949 bool IsNonIntIntegral =
9950 BaseType->isChar16Type() || BaseType->isChar32Type() ||
9951 BaseType->isWideCharType() || BaseType->isEnumeralType();
9952
9953 QualType Underlying =
9954 IsNonIntIntegral
9955 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
9956 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
9958 if (Underlying.isNull())
9959 return Underlying;
9960 return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
9961}
9962
9965 if (BaseType->isDependentType())
9966 return Context.getUnaryTransformType(BaseType, BaseType, UKind);
9968 switch (UKind) {
9969 case UnaryTransformType::EnumUnderlyingType: {
9971 break;
9972 }
9973 case UnaryTransformType::AddPointer: {
9974 Result = BuiltinAddPointer(BaseType, Loc);
9975 break;
9976 }
9977 case UnaryTransformType::RemovePointer: {
9978 Result = BuiltinRemovePointer(BaseType, Loc);
9979 break;
9980 }
9981 case UnaryTransformType::Decay: {
9982 Result = BuiltinDecay(BaseType, Loc);
9983 break;
9984 }
9985 case UnaryTransformType::AddLvalueReference:
9986 case UnaryTransformType::AddRvalueReference: {
9987 Result = BuiltinAddReference(BaseType, UKind, Loc);
9988 break;
9989 }
9990 case UnaryTransformType::RemoveAllExtents:
9991 case UnaryTransformType::RemoveExtent: {
9992 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
9993 break;
9994 }
9995 case UnaryTransformType::RemoveCVRef:
9996 case UnaryTransformType::RemoveReference: {
9997 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
9998 break;
9999 }
10000 case UnaryTransformType::RemoveConst:
10001 case UnaryTransformType::RemoveCV:
10002 case UnaryTransformType::RemoveRestrict:
10003 case UnaryTransformType::RemoveVolatile: {
10004 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
10005 break;
10006 }
10007 case UnaryTransformType::MakeSigned:
10008 case UnaryTransformType::MakeUnsigned: {
10009 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
10010 break;
10011 }
10012 }
10013
10014 return !Result.isNull()
10015 ? Context.getUnaryTransformType(BaseType, Result, UKind)
10016 : Result;
10017}
10018
10021 // FIXME: It isn't entirely clear whether incomplete atomic types
10022 // are allowed or not; for simplicity, ban them for the moment.
10023 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
10024 return QualType();
10025
10026 int DisallowedKind = -1;
10027 if (T->isArrayType())
10028 DisallowedKind = 1;
10029 else if (T->isFunctionType())
10030 DisallowedKind = 2;
10031 else if (T->isReferenceType())
10032 DisallowedKind = 3;
10033 else if (T->isAtomicType())
10034 DisallowedKind = 4;
10035 else if (T.hasQualifiers())
10036 DisallowedKind = 5;
10037 else if (T->isSizelessType())
10038 DisallowedKind = 6;
10039 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus)
10040 // Some other non-trivially-copyable type (probably a C++ class)
10041 DisallowedKind = 7;
10042 else if (T->isBitIntType())
10043 DisallowedKind = 8;
10044 else if (getLangOpts().C23 && T->isUndeducedAutoType())
10045 // _Atomic auto is prohibited in C23
10046 DisallowedKind = 9;
10047
10048 if (DisallowedKind != -1) {
10049 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
10050 return QualType();
10051 }
10052
10053 // FIXME: Do we need any handling for ARC here?
10054 }
10055
10056 // Build the pointer type.
10057 return Context.getAtomicType(T);
10058}
Defines the clang::ASTContext interface.
StringRef P
const Decl * D
Expr * E
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Defines the clang::Preprocessor interface.
static QualType getUnderlyingType(const SubRegion *R)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
This file declares semantic analysis for HLSL constructs.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S, VectorKind VecKind)
HandleNeonVectorTypeAttr - The "neon_vector_type" and "neon_polyvector_type" attributes are used to c...
Definition: SemaType.cpp:8335
static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType)
Definition: SemaType.cpp:1796
static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S)
Definition: SemaType.cpp:8264
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:496
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:754
#define MS_TYPE_ATTRS_CASELIST
Definition: SemaType.cpp:170
#define CALLING_CONV_ATTRS_CASELIST
Definition: SemaType.cpp:125
static void emitNullabilityConsistencyWarning(Sema &S, SimplePointerKind PointerKind, SourceLocation PointerLoc, SourceLocation PointerEndLoc)
Definition: SemaType.cpp:4052
static void fixItNullability(Sema &S, DiagBuilderT &Diag, SourceLocation PointerLoc, NullabilityKind Nullability)
Creates a fix-it to insert a C-style nullability keyword at pointerLoc, taking into account whitespac...
Definition: SemaType.cpp:4017
static ExprResult checkArraySize(Sema &S, Expr *&ArraySize, llvm::APSInt &SizeVal, unsigned VLADiag, bool VLAIsError)
Check whether the specified array bound can be evaluated using the relevant language rules.
Definition: SemaType.cpp:1978
static Attr * createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, NullabilityKind NK)
Definition: SemaType.cpp:4191
static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
HandleVectorSizeAttribute - this attribute is only applicable to integral and float scalars,...
Definition: SemaType.cpp:8229
static void inferARCWriteback(TypeProcessingState &state, QualType &declSpecType)
Given that this is the declaration of a parameter under ARC, attempt to infer attributes and such for...
Definition: SemaType.cpp:2775
static TypeSourceInfo * GetTypeSourceInfoForDeclarator(TypeProcessingState &State, QualType T, TypeSourceInfo *ReturnTypeInfo)
Create and instantiate a TypeSourceInfo with type source information.
Definition: SemaType.cpp:6312
static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, const Expr *AddrSpace, SourceLocation AttrLoc)
Build an AddressSpace index from a constant expression and diagnose any errors related to invalid add...
Definition: SemaType.cpp:6454
static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr, TypeProcessingState &State)
Definition: SemaType.cpp:6529
static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, Qualifiers::ObjCLifetime ownership, unsigned chunkIndex)
Definition: SemaType.cpp:5729
static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
handleObjCGCTypeAttr - Process the attribute((objc_gc)) type attribute on the specified type.
Definition: SemaType.cpp:6838
static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk)
Definition: SemaType.cpp:5860
static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
Process the OpenCL-like ext_vector_type attribute when it occurs on a type.
Definition: SemaType.cpp:8249
static void HandleHLSLParamModifierAttr(TypeProcessingState &State, QualType &CurType, const ParsedAttr &Attr, Sema &S)
Definition: SemaType.cpp:8694
static void HandleLifetimeBoundAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &Attr)
Definition: SemaType.cpp:8671
static bool handleArmStateAttribute(Sema &S, FunctionProtoType::ExtProtoInfo &EPI, ParsedAttr &Attr, FunctionType::ArmStateValue State)
Definition: SemaType.cpp:7783
static bool handleArmAgnosticAttribute(Sema &S, FunctionProtoType::ExtProtoInfo &EPI, ParsedAttr &Attr)
Definition: SemaType.cpp:7749
static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType, CUDAFunctionTarget CFT)
A function type attribute was written in the decl spec.
Definition: SemaType.cpp:664
static bool handleObjCPointerTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
Definition: SemaType.cpp:411
static QualType inferARCLifetimeForPointee(Sema &S, QualType type, SourceLocation loc, bool isReference)
Given that we're building a pointer or reference to the given.
Definition: SemaType.cpp:1680
static bool handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState, ParsedAttr &PAttr, QualType &QT, FunctionTypeUnwrapper &Unwrapped)
Definition: SemaType.cpp:7644
static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType, bool IsMakeSigned, SourceLocation Loc)
Definition: SemaType.cpp:9889
static bool CheckNullabilityTypeSpecifier(Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT, NullabilityKind Nullability, SourceLocation NullabilityLoc, bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting)
Definition: SemaType.cpp:7284
#define OBJC_POINTER_TYPE_ATTRS_CASELIST
Definition: SemaType.cpp:120
static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, QualType type)
diagnoseBadTypeAttribute - Diagnoses a type attribute which doesn't apply to the given type.
Definition: SemaType.cpp:80
static PointerDeclaratorKind classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, PointerWrappingDeclaratorKind &wrappingKind)
Classify the given declarator, whose type-specified is type, based on what kind of pointer it refers ...
Definition: SemaType.cpp:3848
static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr, llvm::APSInt &Result)
Definition: SemaType.cpp:8312
static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL, QualType &QT, ParsedAttr &PAttr)
Definition: SemaType.cpp:7190
static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
Definition: SemaType.cpp:7062
static bool shouldHaveNullability(QualType T)
Definition: SemaType.cpp:4231
static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &Attr)
Definition: SemaType.cpp:8463
static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, DeclaratorChunk &DeclType, QualType RT)
Produce an appropriate diagnostic for an ambiguity between a function declarator and a C++ direct-ini...
Definition: SemaType.cpp:3451
static void distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType)
Distribute an objc_gc type attribute that was written on the declarator.
Definition: SemaType.cpp:552
static FileID getNullabilityCompletenessCheckFileID(Sema &S, SourceLocation loc)
Definition: SemaType.cpp:3977
static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, Sema &S)
HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is used to create fixed-length v...
Definition: SemaType.cpp:8399
#define FUNCTION_TYPE_ATTRS_CASELIST
Definition: SemaType.cpp:149
static void HandleLifetimeCaptureByAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &PA)
Definition: SemaType.cpp:8685
static bool distributeNullabilityTypeAttr(TypeProcessingState &state, QualType type, ParsedAttr &attr)
Distribute a nullability type attribute that cannot be applied to the type specifier to a pointer,...
Definition: SemaType.cpp:7478
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:713
static void fillHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL, TypeProcessingState &State)
Definition: SemaType.cpp:5837
static bool isDependentOrGNUAutoType(QualType T)
Definition: SemaType.cpp:1573
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:613
static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type.
Definition: SemaType.cpp:8623
static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State, QualType &QT, ParsedAttr &PAttr)
Definition: SemaType.cpp:7159
static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex)
Returns true if any of the declarator chunks before endIndex include a level of indirection: array,...
Definition: SemaType.cpp:4156
static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
Handle OpenCL Access Qualifier Attribute.
Definition: SemaType.cpp:8567
static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind)
Map a nullability attribute kind to a nullability kind.
Definition: SemaType.cpp:7265
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:644
#define NULLABILITY_TYPE_ATTRS_CASELIST
Definition: SemaType.cpp:177
static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, TypeSourceInfo *&ReturnTypeInfo)
Definition: SemaType.cpp:3104
static void checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, SourceLocation pointerLoc, SourceLocation pointerEndLoc=SourceLocation())
Complains about missing nullability if the file containing pointerLoc has other uses of nullability (...
Definition: SemaType.cpp:4086
static void transferARCOwnership(TypeProcessingState &state, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership)
Used for transferring ownership in casts resulting in l-values.
Definition: SemaType.cpp:5766
static std::string getPrintableNameForEntity(DeclarationName Entity)
Definition: SemaType.cpp:1566
static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy)
Definition: SemaType.cpp:1731
static QualType rebuildAttributedTypeWithoutNullability(ASTContext &Ctx, QualType Type)
Rebuild an attributed type without the nullability attribute on it.
Definition: SemaType.cpp:7245
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:428
static OpenCLAccessAttr::Spelling getImageAccess(const ParsedAttributesView &Attrs)
Definition: SemaType.cpp:868
static void fillMatrixTypeLoc(MatrixTypeLoc MTL, const ParsedAttributesView &Attrs)
Definition: SemaType.cpp:5845
static UnaryTransformType::UTTKind TSTToUnaryTransformType(DeclSpec::TST SwitchTST)
Definition: SemaType.cpp:876
static void HandleRISCVRVVVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, Sema &S)
HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is used to create fixed-leng...
Definition: SemaType.cpp:8483
static void HandleAddressSpaceTypeAttribute(QualType &Type, const ParsedAttr &Attr, TypeProcessingState &State)
HandleAddressSpaceTypeAttribute - Process an address_space attribute on the specified type.
Definition: SemaType.cpp:6568
static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, QualifiedFunctionKind QFK)
Check whether the type T is a qualified function type, and if it is, diagnose that it cannot be conta...
Definition: SemaType.cpp:1770
static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, QualType Result)
Return true if this is omitted block return type.
Definition: SemaType.cpp:838
static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld, LangAS ASNew, SourceLocation AttrLoc)
Definition: SemaType.cpp:4213
static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T)
Produce an appropriate diagnostic for a declarator with top-level parentheses.
Definition: SemaType.cpp:3548
static QualType ConvertDeclSpecToType(TypeProcessingState &state)
Convert the specified declspec to the appropriate type object.
Definition: SemaType.cpp:893
static std::pair< QualType, TypeSourceInfo * > InventTemplateParameter(TypeProcessingState &state, QualType T, TypeSourceInfo *TrailingTSI, AutoType *Auto, InventedTemplateParameterInfo &Info)
Definition: SemaType.cpp:2993
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:684
static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, unsigned &TypeQuals, QualType TypeSoFar, unsigned RemoveTQs, unsigned DiagID)
Definition: SemaType.cpp:810
static CallingConv getCCForDeclaratorChunk(Sema &S, Declarator &D, const ParsedAttributesView &AttrList, const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex)
Helper for figuring out the default CC for a function declarator type.
Definition: SemaType.cpp:3667
static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for literal type diagnostic message.
Definition: SemaType.cpp:9474
static void recordNullabilitySeen(Sema &S, SourceLocation loc)
Marks that a nullability feature has been used in the file containing loc.
Definition: SemaType.cpp:4127
static bool CheckBitIntElementType(Sema &S, SourceLocation AttrLoc, const BitIntType *BIT, bool ForMatrixType=false)
Definition: SemaType.cpp:2316
static void checkExtParameterInfos(Sema &S, ArrayRef< QualType > paramTypes, const FunctionProtoType::ExtProtoInfo &EPI, llvm::function_ref< SourceLocation(unsigned)> getParamLoc)
Check the extended parameter information.
Definition: SemaType.cpp:2569
static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type, CUDAFunctionTarget CFT)
Process an individual function attribute.
Definition: SemaType.cpp:7837
static void transferARCOwnershipToDeclSpec(Sema &S, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership)
Definition: SemaType.cpp:5718
static void BuildTypeCoupledDecls(Expr *E, llvm::SmallVectorImpl< TypeCoupledDeclRefInfo > &Decls)
Definition: SemaType.cpp:9607
static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD)
Locks in the inheritance model for the given class and all of its bases.
Definition: SemaType.cpp:9265
static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, ParsedAttr &attr)
Check the application of the Objective-C '__kindof' qualifier to the given type.
Definition: SemaType.cpp:7420
static bool hasNullabilityAttr(const ParsedAttributesView &attrs)
Check whether there is a nullability attribute of any kind in the given attribute list.
Definition: SemaType.cpp:3801
static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
handleObjCOwnershipTypeAttr - Process an objc_ownership attribute on the specified type.
Definition: SemaType.cpp:6651
static void moveAttrFromListToList(ParsedAttr &attr, ParsedAttributesView &fromList, ParsedAttributesView &toList)
Definition: SemaType.cpp:377
static void HandleAnnotateTypeAttr(TypeProcessingState &State, QualType &CurType, const ParsedAttr &PA)
Definition: SemaType.cpp:8643
static void fillAttributedTypeLoc(AttributedTypeLoc TL, TypeProcessingState &State)
Definition: SemaType.cpp:5832
static void fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, const ParsedAttributesView &Attrs)
Definition: SemaType.cpp:6288
TypeAttrLocation
The location of a type attribute.
Definition: SemaType.cpp:385
@ TAL_DeclChunk
The attribute is part of a DeclaratorChunk.
Definition: SemaType.cpp:389
@ TAL_DeclSpec
The attribute is in the decl-specifier-seq.
Definition: SemaType.cpp:387
@ TAL_DeclName
The attribute is immediately after the declaration's name.
Definition: SemaType.cpp:391
static bool isOmittedBlockReturnType(const Declarator &D)
isOmittedBlockReturnType - Return true if this declarator is missing a return type because this is a ...
Definition: SemaType.cpp:63
static TypeSourceInfo * GetFullTypeForDeclarator(TypeProcessingState &state, QualType declSpecType, TypeSourceInfo *TInfo)
Definition: SemaType.cpp:4241
TypeDiagSelector
Definition: SemaType.cpp:55
@ TDS_ObjCObjOrBlock
Definition: SemaType.cpp:58
@ TDS_Function
Definition: SemaType.cpp:56
@ TDS_Pointer
Definition: SemaType.cpp:57
static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType, SourceLocation Loc)
Definition: SemaType.cpp:9766
static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk)
Definition: SemaType.cpp:4180
static AttrT * createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL)
Definition: SemaType.cpp:4186
static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, Declarator &D, unsigned FunctionChunkIndex)
Definition: SemaType.cpp:2922
static void processTypeAttrs(TypeProcessingState &state, QualType &type, TypeAttrLocation TAL, const ParsedAttributesView &attrs, CUDAFunctionTarget CFT=CUDAFunctionTarget::HostDevice)
Definition: SemaType.cpp:8708
static bool checkMutualExclusion(TypeProcessingState &state, const FunctionProtoType::ExtProtoInfo &EPI, ParsedAttr &Attr, AttributeCommonInfo::Kind OtherKind)
Definition: SemaType.cpp:7729
static Attr * getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr)
Definition: SemaType.cpp:7559
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__DEVICE__ int max(int __a, int __b)
__device__ int
virtual void HandleTagDeclRequiredDefinition(const TagDecl *D)
This callback is invoked the first time each TagDecl is required to be complete.
Definition: ASTConsumer.h:77
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:113
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
CanQualType AccumTy
Definition: ASTContext.h:1173
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
QualType getParenType(QualType NamedType) const
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
CanQualType LongTy
Definition: ASTContext.h:1169
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
CanQualType Int128Ty
Definition: ASTContext.h:1169
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, ConceptDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1173
CanQualType FloatTy
Definition: ASTContext.h:1172
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2716
CanQualType DoubleTy
Definition: ASTContext.h:1172
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CanQualType LongDoubleTy
Definition: ASTContext.h:1172
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
CanQualType Char16Ty
Definition: ASTContext.h:1167
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2921
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1188
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
IdentifierTable & Idents
Definition: ASTContext.h:680
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
CanQualType Ibm128Ty
Definition: ASTContext.h:1172
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType BoolTy
Definition: ASTContext.h:1161
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:800
CanQualType Float128Ty
Definition: ASTContext.h:1172
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType ShortFractTy
Definition: ASTContext.h:1176
QualType getCorrespondingSaturatedType(QualType Ty) const
CanQualType CharTy
Definition: ASTContext.h:1162
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
Definition: ASTContext.h:1169
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
CanQualType Float16Ty
Definition: ASTContext.h:1186
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2289
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType SignedCharTy
Definition: ASTContext.h:1169
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
Definition: ASTContext.h:1528
CanQualType OverloadTy
Definition: ASTContext.h:1188
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2482
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1171
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
CanQualType UnsignedShortTy
Definition: ASTContext.h:1170
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, int Index=-1) const
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
CanQualType ShortTy
Definition: ASTContext.h:1169
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Definition: ASTContext.h:1176
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
CanQualType LongAccumTy
Definition: ASTContext.h:1174
CanQualType Char32Ty
Definition: ASTContext.h:1168
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
CanQualType LongFractTy
Definition: ASTContext.h:1176
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1185
QualType getCorrespondingUnsignedType(QualType T) const
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1274
CanQualType LongLongTy
Definition: ASTContext.h:1169
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
CanQualType WCharTy
Definition: ASTContext.h:1163
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
Definition: ASTContext.h:1166
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
CanQualType HalfTy
Definition: ASTContext.h:1184
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2486
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Wrapper for source info for array parameter types.
Definition: TypeLoc.h:1648
Wrapper for source info for arrays.
Definition: TypeLoc.h:1592
void setLBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1598
void setRBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1606
void setSizeExpr(Expr *Size)
Definition: TypeLoc.h:1618
TypeLoc getValueLoc() const
Definition: TypeLoc.h:2641
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2653
void setParensRange(SourceRange Range)
Definition: TypeLoc.h:2677
Attr - This represents one attribute.
Definition: Attr.h:43
attr::Kind getKind() const
Definition: Attr.h:89
const char * getSpelling() const
void setImplicit(bool I)
Definition: Attr.h:103
Combines information about the source-code form of an attribute, including its syntax and spelling.
bool isContextSensitiveKeywordAttribute() const
SourceLocation getLoc() const
const IdentifierInfo * getAttrName() const
Type source information for an attributed type.
Definition: TypeLoc.h:875
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:889
void setAttr(const Attr *A)
Definition: TypeLoc.h:901
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:6132
QualType getModifiedType() const
Definition: Type.h:6162
bool isCallingConv() const
Definition: Type.cpp:4206
static std::optional< NullabilityKind > stripOuterNullability(QualType &T)
Strip off the top-level nullability annotation on the given type, if it's there.
Definition: Type.cpp:4943
Kind getAttrKind() const
Definition: Type.h:6156
bool hasExplicitTemplateArgs() const
Definition: TypeLoc.h:2272
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition: TypeLoc.h:2238
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:2288
ConceptDecl * getNamedConcept() const
Definition: TypeLoc.h:2262
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:2281
void setConceptReference(ConceptReference *CR)
Definition: TypeLoc.h:2232
NamedDecl * getFoundDecl() const
Definition: TypeLoc.h:2256
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:2299
unsigned getNumArgs() const
Definition: TypeLoc.h:2295
DeclarationNameInfo getConceptNameInfo() const
Definition: TypeLoc.h:2268
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2226
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6561
bool isDecltypeAuto() const
Definition: Type.h:6584
ConceptDecl * getTypeConstraintConcept() const
Definition: Type.h:6576
Type source information for an btf_tag attributed type.
Definition: TypeLoc.h:925
TypeLoc getWrappedLoc() const
Definition: TypeLoc.h:927
Comparison function object.
A fixed int type of a specified bitwidth.
Definition: Type.h:7819
unsigned getNumBits() const
Definition: Type.h:7831
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1345
void setCaretLoc(SourceLocation Loc)
Definition: TypeLoc.h:1351
Pointer to a block type.
Definition: Type.h:3408
Wrapper for source info for builtin types.
Definition: TypeLoc.h:565
TypeSpecifierWidth getWrittenWidthSpec() const
Definition: TypeLoc.h:629
bool needsExtraLocalData() const
Definition: TypeLoc.h:594
void setBuiltinLoc(SourceLocation Loc)
Definition: TypeLoc.h:571
WrittenBuiltinSpecs & getWrittenBuiltinSpecs()
Definition: TypeLoc.h:587
TypeSpecifierSign getWrittenSignSpec() const
Definition: TypeLoc.h:613
void expandBuiltinRange(SourceRange Range)
Definition: TypeLoc.h:575
This class is used for builtin types like 'int'.
Definition: Type.h:3034
Kind getKind() const
Definition: Type.h:3082
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isAggregate() const
Determine whether this class is an aggregate (C++ [dcl.init.aggr]), which is a class with no user-dec...
Definition: DeclCXX.h:1155
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1252
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1378
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1970
base_class_range bases()
Definition: DeclCXX.h:620
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1030
bool hasConstexprNonCopyMoveConstructor() const
Determine whether this class has at least one constexpr constructor other than the copy or move const...
Definition: DeclCXX.h:1267
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition: DeclCXX.cpp:602
bool hasNonLiteralTypeFieldsOrBases() const
Determine whether this class has a non-literal or/ volatile type non-static data member or base class...
Definition: DeclCXX.h:1420
CXXRecordDecl * getMostRecentNonInjectedDecl()
Definition: DeclCXX.h:550
base_class_range vbases()
Definition: DeclCXX.h:637
bool hasUserProvidedDefaultConstructor() const
Whether this class has a user-provided default constructor per C++11.
Definition: DeclCXX.h:798
bool hasDefinition() const
Definition: DeclCXX.h:572
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:1198
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2069
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:635
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:149
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
Represents a canonical, potentially-qualified type.
Definition: CanonicalType.h:66
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Declaration of a C++20 concept.
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:87
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
TypeLoc getNextTypeLoc() const
Definition: TypeLoc.h:417
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:205
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:245
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:4261
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1293
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool isRecord() const
Definition: DeclBase.h:2169
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:2664
bool isFunctionOrMethod() const
Definition: DeclBase.h:2141
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
const WrittenBuiltinSpecs & getWrittenBuiltinSpecs() const
Definition: DeclSpec.h:885
bool isTypeSpecPipe() const
Definition: DeclSpec.h:543
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:309
SourceLocation getTypeSpecSignLoc() const
Definition: DeclSpec.h:581
static const TST TST_typename
Definition: DeclSpec.h:306
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:576
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:691
static const TST TST_char8
Definition: DeclSpec.h:282
static const TST TST_BFloat16
Definition: DeclSpec.h:289
Expr * getPackIndexingExpr() const
Definition: DeclSpec.h:560
TST getTypeSpecType() const
Definition: DeclSpec.h:537
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:575
bool isTypeSpecSat() const
Definition: DeclSpec.h:544
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:574
static const TST TST_auto_type
Definition: DeclSpec.h:319
static const TST TST_interface
Definition: DeclSpec.h:304
static const TST TST_double
Definition: DeclSpec.h:291
static const TST TST_typeofExpr
Definition: DeclSpec.h:308
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:616
TemplateIdAnnotation * getRepAsTemplateId() const
Definition: DeclSpec.h:566
static const TST TST_union
Definition: DeclSpec.h:302
static const TST TST_typename_pack_indexing
Definition: DeclSpec.h:313
static const TST TST_char
Definition: DeclSpec.h:280
static const TST TST_bool
Definition: DeclSpec.h:297
static const TST TST_char16
Definition: DeclSpec.h:283
static const TST TST_unknown_anytype
Definition: DeclSpec.h:320
TSC getTypeSpecComplex() const
Definition: DeclSpec.h:533
static const TST TST_int
Definition: DeclSpec.h:285
ParsedType getRepAsType() const
Definition: DeclSpec.h:547
static const TST TST_accum
Definition: DeclSpec.h:293
static const TST TST_half
Definition: DeclSpec.h:288
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:873
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:623
bool isTypeAltiVecPixel() const
Definition: DeclSpec.h:539
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:626
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:617
static const TST TST_ibm128
Definition: DeclSpec.h:296
Expr * getRepAsExpr() const
Definition: DeclSpec.h:555
static const TST TST_enum
Definition: DeclSpec.h:301
static const TST TST_float128
Definition: DeclSpec.h:295
static const TST TST_decltype
Definition: DeclSpec.h:311
SourceRange getTypeSpecWidthRange() const
Definition: DeclSpec.h:579
SourceLocation getTypeSpecTypeNameLoc() const
Definition: DeclSpec.h:586
SourceLocation getTypeSpecWidthLoc() const
Definition: DeclSpec.h:578
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:618
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:310
static const TST TST_class
Definition: DeclSpec.h:305
static const TST TST_decimal64
Definition: DeclSpec.h:299
bool isTypeAltiVecBool() const
Definition: DeclSpec.h:540
bool isConstrainedAuto() const
Definition: DeclSpec.h:545
static const TST TST_wchar
Definition: DeclSpec.h:281
SourceLocation getTypeSpecComplexLoc() const
Definition: DeclSpec.h:580
static const TST TST_void
Definition: DeclSpec.h:279
bool isTypeAltiVecVector() const
Definition: DeclSpec.h:538
static const TST TST_bitint
Definition: DeclSpec.h:287
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:558
static const TST TST_float
Definition: DeclSpec.h:290
static const TST TST_atomic
Definition: DeclSpec.h:321
static const TST TST_fract
Definition: DeclSpec.h:294
Decl * getRepAsDecl() const
Definition: DeclSpec.h:551
static const TST TST_float16
Definition: DeclSpec.h:292
static bool isTransformTypeTrait(TST T)
Definition: DeclSpec.h:474
static const TST TST_unspecified
Definition: DeclSpec.h:278
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:620
TypeSpecifierSign getTypeSpecSign() const
Definition: DeclSpec.h:534
CXXScopeSpec & getTypeSpecScope()
Definition: DeclSpec.h:571
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:582
static const TST TST_decltype_auto
Definition: DeclSpec.h:312
static const TST TST_error
Definition: DeclSpec.h:328
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition: DeclSpec.cpp:453
static const TST TST_decimal32
Definition: DeclSpec.h:298
TypeSpecifierWidth getTypeSpecWidth() const
Definition: DeclSpec.h:530
static const TST TST_char32
Definition: DeclSpec.h:284
static const TST TST_decimal128
Definition: DeclSpec.h:300
bool isTypeSpecOwned() const
Definition: DeclSpec.h:541
SourceLocation getTypeSpecSatLoc() const
Definition: DeclSpec.h:584
SourceRange getTypeofParensRange() const
Definition: DeclSpec.h:592
static const TST TST_int128
Definition: DeclSpec.h:286
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:619
static const TST TST_typeofType
Definition: DeclSpec.h:307
static const TST TST_auto
Definition: DeclSpec.h:318
static const TST TST_struct
Definition: DeclSpec.h:303
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:438
bool isModulePrivate() const
Whether this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:645
T * getAttr() const
Definition: DeclBase.h:576
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:520
void addAttr(Attr *A)
Definition: DeclBase.cpp:1010
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:151
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
void setImplicit(bool I=true)
Definition: DeclBase.h:597
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
AttrVec & getAttrs()
Definition: DeclBase.h:527
bool hasAttr() const
Definition: DeclBase.h:580
Kind getKind() const
Definition: DeclBase.h:445
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:430
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:859
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2459
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2401
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2050
void AddInnermostTypeInfo(const DeclaratorChunk &TI)
Add a new innermost chunk to this declarator.
Definition: DeclSpec.h:2392
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2686
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2339
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2716
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2397
const ParsedAttributesView & getDeclarationAttributes() const
Definition: DeclSpec.h:2689
DeclaratorContext getContext() const
Definition: DeclSpec.h:2075
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2086
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2057
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2490
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2118
void setDecltypeLoc(SourceLocation Loc)
Definition: TypeLoc.h:2115
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6527
void setAttrNameLoc(SourceLocation loc)
Definition: TypeLoc.h:1804
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:1825
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3920
void copy(DependentNameTypeLoc Loc)
Definition: TypeLoc.h:2465
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2454
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2434
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2443
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1923
void copy(DependentTemplateSpecializationTypeLoc Loc)
Definition: TypeLoc.h:2579
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1895
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:939
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:713
Wrap a function effect's condition expression in another struct so that FunctionProtoType's TrailingO...
Definition: Type.h:4828
void copy(ElaboratedTypeLoc Loc)
Definition: TypeLoc.h:2412
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2354
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2392
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2368
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6948
Represents an enum.
Definition: Decl.h:3861
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4021
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6103
This represents one expression.
Definition: Expr.h:110
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3097
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3093
bool isPRValue() const
Definition: Expr.h:278
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3594
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:276
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isInvalid() const
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
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:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
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:101
A SourceLocation and its associated SourceManager.
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2338
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:5044
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition: Type.cpp:5286
Represents an abstract function effect, using just an enumeration describing its kind.
Definition: Type.h:4721
Kind
Identifies the particular effect.
Definition: Type.h:4724
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4908
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5107
Qualifiers getMethodQuals() const
Definition: Type.h:5502
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5484
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5371
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5367
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: Type.h:5510
Wrapper for source info for functions.
Definition: TypeLoc.h:1459
unsigned getNumParams() const
Definition: TypeLoc.h:1531
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1479
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1495
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1538
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1503
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1487
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1517
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4432
ExtInfo withNoCfCheck(bool noCfCheck) const
Definition: Type.h:4534
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4547
CallingConv getCC() const
Definition: Type.h:4494
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4513
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4506
bool getProducesResult() const
Definition: Type.h:4481
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:4527
ExtInfo withCmseNSCall(bool cmseNSCall) const
Definition: Type.h:4520
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:4541
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: Type.h:4360
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4660
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3537
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4618
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4614
CallingConv getCallConv() const
Definition: Type.h:4659
QualType getReturnType() const
Definition: Type.h:4648
bool getHasRegParm() const
Definition: Type.h:4650
AArch64SMETypeAttributes
The AArch64 SME ACLE (Arm C/C++ Language Extensions) define a number of function type attributes that...
Definition: Type.h:4585
@ SME_PStateSMEnabledMask
Definition: Type.h:4587
@ SME_PStateSMCompatibleMask
Definition: Type.h:4588
@ SME_AgnosticZAStateMask
Definition: Type.h:4598
Type source information for HLSL attributed resource type.
Definition: TypeLoc.h:952
void setContainedTypeSourceInfo(TypeSourceInfo *TSI) const
Definition: TypeLoc.h:959
void setSourceRange(const SourceRange &R)
Definition: TypeLoc.h:963
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
void setAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1429
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3483
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:721
bool isImplicitIntAllowed() const
Returns true if implicit int is supported at all.
Definition: LangOptions.h:738
bool isImplicitIntRequired() const
Returns true if implicit int is part of the language requirements.
Definition: LangOptions.h:735
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
Holds a QualType and a TypeSourceInfo* that came out of a declarator parsing.
Definition: LocInfoType.h:28
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
Definition: SemaType.cpp:6407
Represents the results of name lookup.
Definition: Lookup.h:46
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1192
void setExpansionLoc(SourceLocation Loc)
Definition: TypeLoc.h:1202
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:5770
void setAttrRowOperand(Expr *e)
Definition: TypeLoc.h:1958
void setAttrColumnOperand(Expr *e)
Definition: TypeLoc.h:1964
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:1973
void setAttrNameLoc(SourceLocation loc)
Definition: TypeLoc.h:1952
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:4217
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1363
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1369
void setClassTInfo(TypeSourceInfo *TI)
Definition: TypeLoc.h:1381
const Type * getClass() const
Definition: TypeLoc.h:1373
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
QualType getPointeeType() const
Definition: Type.h:3535
const Type * getClass() const
Definition: Type.h:3549
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:620
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:642
This represents a decl that may have a name.
Definition: Decl.h:253
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
A C++ nested-name-specifier augmented with source location information.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
SourceLocation getLocalBeginLoc() const
Retrieve the location of the beginning of this component of the nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
Wrapper for source info for ObjC interfaces.
Definition: TypeLoc.h:1122
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1132
void setNameEndLoc(SourceLocation Loc)
Definition: TypeLoc.h:1144
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7529
Wraps an ObjCPointerType with source location information.
Definition: TypeLoc.h:1401
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1407
Represents a pointer to an Objective C object.
Definition: Type.h:7585
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7622
Represents a class type in Objective C.
Definition: Type.h:7331
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(QualType P)
Definition: Ownership.h:60
OpenCL supported extensions and optional core features.
Definition: OpenCLOptions.h:69
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
bool isSupported(llvm::StringRef Ext, const LangOptions &LO) const
void setEllipsisLoc(SourceLocation Loc)
Definition: TypeLoc.h:2143
A parameter attribute which changes the argument-passing ABI rule for the parameter.
Definition: Attr.h:236
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1234
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1230
Represents a parameter to a function.
Definition: Decl.h:1725
bool isExplicitObjectParameter() const
Definition: Decl.h:1813
void setKNRPromoted(bool promoted)
Definition: Decl.h:1809
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition: Decl.h:1817
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
void setInvalid(bool b=true) const
Definition: ParsedAttr.h:360
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition: ParsedAttr.h:386
bool isArgIdent(unsigned Arg) const
Definition: ParsedAttr.h:400
Expr * getArgAsExpr(unsigned Arg) const
Definition: ParsedAttr.h:398
AttributeCommonInfo::Kind getKind() const
Definition: ParsedAttr.h:625
void setUsedAsTypeAttr(bool Used=true)
Definition: ParsedAttr.h:375
bool checkAtMostNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at most as many args as Num.
Definition: ParsedAttr.cpp:306
void addAtEnd(ParsedAttr *newAttr)
Definition: ParsedAttr.h:846
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:916
void remove(ParsedAttr *ToBeRemoved)
Definition: ParsedAttr.h:851
void takeOneFrom(ParsedAttributes &Other, ParsedAttr *PA)
Definition: ParsedAttr.h:973
TypeLoc getValueLoc() const
Definition: TypeLoc.h:2700
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2705
PipeType - OpenCL20.
Definition: Type.h:7785
Wrapper for source info for pointers.
Definition: TypeLoc.h:1332
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1338
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceLocation getPragmaAssumeNonNullLoc() const
The location of the currently-active #pragma clang assume_nonnull begin.
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8020
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8025
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7936
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7976
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
bool isReferenceable() const
Definition: Type.h:7944
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:8139
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1081
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:7957
SplitQualType getSplitUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8037
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:8057
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7982
Wrapper of type source information for a type with non-trivial direct qualifiers.
Definition: TypeLoc.h:289
UnqualTypeLoc getUnqualifiedLoc() const
Definition: TypeLoc.h:293
The collection of all-type qualifiers we support.
Definition: Type.h:324
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:488
void addAddressSpace(LangAS space)
Definition: Type.h:590
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
void removeObjCLifetime()
Definition: Type.h:544
void addCVRUQualifiers(unsigned mask)
Definition: Type.h:499
bool hasRestrict() const
Definition: Type.h:470
void removeConst()
Definition: Type.h:452
void removeRestrict()
Definition: Type.h:472
static Qualifiers fromCVRMask(unsigned CVR)
Definition: Type.h:428
@ MaxAddressSpace
The maximum supported address space number.
Definition: Type.h:366
bool empty() const
Definition: Type.h:640
void setUnaligned(bool flag)
Definition: Type.h:505
void removeVolatile()
Definition: Type.h:462
std::string getAsString() const
void addObjCLifetime(ObjCLifetime type)
Definition: Type.h:545
void setAmpAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1443
Represents a struct/union/class.
Definition: Decl.h:4162
field_range fields() const
Definition: Decl.h:4368
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
RecordDecl * getDecl() const
Definition: Type.h:6087
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
QualType getPointeeType() const
Definition: Type.h:3457
bool isSpelledAsLValue() const
Definition: Type.h:3452
bool isFunctionDeclarationScope() const
isFunctionDeclarationScope - Return true if this scope is a function prototype scope.
Definition: Scope.h:466
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
QualType ProcessResourceTypeAttributes(QualType Wrapped)
Definition: SemaHLSL.cpp:1042
QualType getInoutParameterType(QualType Ty)
Definition: SemaHLSL.cpp:2477
bool isCFError(RecordDecl *D)
Definition: SemaObjC.cpp:1465
IdentifierInfo * getNSErrorIdent()
Retrieve the identifier "NSError".
Definition: SemaObjC.cpp:1269
bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type)
Definition: SemaObjC.cpp:1798
bool isInOpenMPTaskUntiedContext() const
Return true if currently in OpenMP task with untied clause context.
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:997
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7229
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
Definition: SemaType.cpp:9258
QualType BuildParenType(QualType T)
Build a paren type including T.
Definition: SemaType.cpp:1675
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6395
bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs (unless they are value dependent ...
Definition: SemaAttr.cpp:499
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13134
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:732
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
Definition: SemaType.cpp:9133
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
Definition: SemaType.cpp:2031
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:7844
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8990
QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc)
BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression is uninstantiated.
Definition: SemaType.cpp:6498
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement)
Completely replace the auto in TypeWithAuto by Replacement.
@ NTCUC_FunctionReturn
Definition: Sema.h:3628
QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc)
Definition: SemaType.cpp:2327
SemaOpenMP & OpenMP()
Definition: Sema.h:1126
std::optional< FunctionEffectMode > ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName)
Try to parse the conditional expression attached to an effect attribute (e.g.
Definition: SemaType.cpp:7625
SemaCUDA & CUDA()
Definition: Sema.h:1071
CompleteTypeKind
Definition: Sema.h:14580
@ AcceptSizeless
Relax the normal rules for complete types so that they include sizeless built-in types.
class clang::Sema::DelayedDiagnostics DelayedDiagnostics
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17152
QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc)
Build an ext-vector type.
Definition: SemaType.cpp:2393
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3436
bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def)
ASTContext & Context
Definition: Sema.h:909
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:2633
SemaObjC & ObjC()
Definition: Sema.h:1111
@ AllowFold
Definition: Sema.h:7245
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
ASTContext & getASTContext() const
Definition: Sema.h:532
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD=nullptr, CUDAFunctionTarget CFT=CUDAFunctionTarget::InvalidTarget)
Check validaty of calling convention attribute attr.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9486
QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull)
Definition: SemaType.cpp:9614
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc)
Build a bit-precise integer type.
Definition: SemaType.cpp:1940
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1589
QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
Definition: SemaType.cpp:9855
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1581
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain=true)
bool CheckFunctionReturnType(QualType T, SourceLocation Loc)
Definition: SemaType.cpp:2528
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:82
@ UPPC_TypeConstraint
A type constraint.
Definition: Sema.h:13960
const LangOptions & getLangOpts() const
Definition: Sema.h:525
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
Definition: SemaType.cpp:9108
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, QualType ConstrainedType, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
Preprocessor & PP
Definition: Sema.h:908
QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc)
Definition: SemaType.cpp:9780
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:907
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2406
SemaHLSL & HLSL()
Definition: Sema.h:1076
IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, unsigned Index)
Invent a new identifier for parameters of abbreviated templates.
Definition: Sema.cpp:116
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition: Sema.h:1411
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition: Sema.h:6029
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition: Sema.h:13186
AcceptableKind
Definition: Sema.h:8978
void completeExprArrayBound(Expr *E)
Definition: SemaType.cpp:9036
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9582
bool hasExplicitCallingConv(QualType T)
Definition: SemaType.cpp:8166
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:14562
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:940
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:1857
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:2144
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1044
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:1121
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
Definition: SemaType.cpp:9816
IdentifierInfo * getNullabilityKeyword(NullabilityKind nullability)
Retrieve the keyword associated.
Definition: SemaType.cpp:3774
@ TAH_IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition: Sema.h:5877
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7777
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1291
bool isAcceptable(const NamedDecl *D, AcceptableKind Kind)
Determine whether a declaration is acceptable (visible/reachable).
Definition: Sema.h:15003
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
Definition: SemaType.cpp:9631
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20971
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9241
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13490
SourceManager & getSourceManager() const
Definition: Sema.h:530
QualType BuiltinAddReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
Definition: SemaType.cpp:9832
bool hasVisibleMergedDefinition(const NamedDecl *Def)
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Definition: SemaType.cpp:9736
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
@ NTCUK_Destruct
Definition: Sema.h:3654
@ NTCUK_Copy
Definition: Sema.h:3655
QualType BuildAtomicType(QualType T, SourceLocation Loc)
Definition: SemaType.cpp:10019
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)
Definition: SemaType.cpp:6414
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:216
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14945
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration,...
QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a pointer type.
Definition: SemaType.cpp:1805
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc)
Definition: SemaType.cpp:9799
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:10002
ASTConsumer & Consumer
Definition: Sema.h:910
bool CheckImplicitNullabilityTypeSpecifier(QualType &Type, NullabilityKind Nullability, SourceLocation DiagLoc, bool AllowArrayTypes, bool OverrideExisting)
Check whether a nullability type specifier can be added to the given type through some means not writ...
Definition: SemaType.cpp:7408
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
bool CheckDistantExceptionSpec(QualType T)
CheckDistantExceptionSpec - Check if the given type is a pointer or pointer to member to a function w...
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:9704
QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind, SourceLocation Loc)
Definition: SemaType.cpp:9963
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5704
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:5817
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9119
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
Definition: SemaExpr.cpp:19263
QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind, SourceLocation Loc)
Definition: SemaType.cpp:9844
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
Definition: SemaType.cpp:9094
QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind, SourceLocation Loc)
Definition: SemaType.cpp:9870
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:912
DiagnosticsEngine & Diags
Definition: Sema.h:911
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:526
QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc)
Definition: SemaType.cpp:9808
QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity)
Build an array type.
Definition: SemaType.cpp:2048
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc)
Definition: SemaType.cpp:1784
QualType BuildReadPipeType(QualType T, SourceLocation Loc)
Build a Read-only Pipe type.
Definition: SemaType.cpp:1932
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
Definition: SemaType.cpp:2871
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition: Sema.h:1406
llvm::BumpPtrAllocator BumpAlloc
Definition: Sema.h:858
QualType BuildWritePipeType(QualType T, SourceLocation Loc)
Build a Write-only Pipe type.
Definition: SemaType.cpp:1936
QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc)
Definition: SemaType.cpp:9718
QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind)
Definition: SemaType.cpp:9591
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:564
QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc)
Definition: SemaType.cpp:2447
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1963
bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, AcceptableKind Kind, bool OnlyNeedComplete=false)
Definition: SemaType.cpp:9148
QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind, SourceLocation Loc)
Definition: SemaType.cpp:9937
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
Definition: SemaType.cpp:8180
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2751
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
Definition: SemaDecl.cpp:13356
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TAH_IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity)
Build a member pointer type T Class::*.
Definition: SemaType.cpp:2682
QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a block pointer type.
Definition: SemaType.cpp:2734
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:333
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3578
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:3711
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3681
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4745
TagKind getTagKind() const
Definition: Decl.h:3773
Wrapper for source info for tag types.
Definition: TypeLoc.h:730
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Exposes information about the current target.
Definition: TargetInfo.h:220
virtual bool hasBitIntType() const
Determine whether the _BitInt type is supported on this target.
Definition: TargetInfo.h:676
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
virtual size_t getMaxBitIntWidth() const
Definition: TargetInfo.h:682
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:478
virtual bool allowHalfArgsAndReturns() const
Whether half args and returns are supported.
Definition: TargetInfo.h:700
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:665
virtual bool hasFloat16Type() const
Determine whether the _Float16 type is supported on this target.
Definition: TargetInfo.h:706
bool isVLASupported() const
Whether target supports variable-length arrays.
Definition: TargetInfo.h:1594
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:718
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:703
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:709
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1493
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts) const
Returns target-specific min and max values VScale_Range.
Definition: TargetInfo.h:1026
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:1706
void copy(TemplateSpecializationTypeLoc Loc)
Definition: TypeLoc.h:1740
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition: Type.h:3226
const Type * getTypeForDecl() const
Definition: Decl.h:3409
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition: TypeLoc.h:338
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition: TypeLoc.h:170
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:206
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:164
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition: TypeLoc.cpp:749
void * getOpaqueData() const
Get the pointer where source information is stored.
Definition: TypeLoc.h:142
void copy(TypeLoc other)
Copies the other type loc into this one.
Definition: TypeLoc.cpp:168
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition: TypeLoc.h:200
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
void setUnmodifiedTInfo(TypeSourceInfo *TI) const
Definition: TypeLoc.h:2092
A container of type source information.
Definition: Type.h:7907
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7918
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1828
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2511
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2441
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isBlockPointerType() const
Definition: Type.h:8205
bool isVoidType() const
Definition: Type.h:8515
bool isBooleanType() const
Definition: Type.h:8643
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition: Type.cpp:2624
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2937
bool isIncompleteArrayType() const
Definition: Type.h:8271
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2105
bool isUndeducedAutoType() const
Definition: Type.h:8350
bool isConstantArrayType() const
Definition: Type.h:8267
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2386
bool isArrayType() const
Definition: Type.h:8263
bool isPointerType() const
Definition: Type.h:8191
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8555
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
bool isReferenceType() const
Definition: Type.h:8209
bool isEnumeralType() const
Definition: Type.h:8295
bool isVariableArrayType() const
Definition: Type.h:8275
bool isSizelessBuiltinType() const
Definition: Type.cpp:2475
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2554
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:460
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool canHaveNullability(bool ResultIfUnknown=true) const
Determine whether the given type can have a nullability specifier applied to it, i....
Definition: Type.cpp:4776
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2593
bool isImageType() const
Definition: Type.h:8418
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
bool isPipeType() const
Definition: Type.h:8425
bool isBitIntType() const
Definition: Type.h:8429
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8287
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isChar16Type() const
Definition: Type.cpp:2145
bool isHalfType() const
Definition: Type.h:8519
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2045
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2361
QualType getCanonicalTypeInternal() const
Definition: Type.h:2989
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2501
bool isMemberPointerType() const
Definition: Type.h:8245
bool isAtomicType() const
Definition: Type.h:8346
bool isFunctionProtoType() const
Definition: Type.h:2535
bool isObjCIdType() const
Definition: Type.h:8366
bool isChar32Type() const
Definition: Type.cpp:2151
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isObjCObjectType() const
Definition: Type.h:8337
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8649
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2446
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8187
bool isObjCObjectPointerType() const
Definition: Type.h:8333
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition: Type.cpp:2606
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
bool isWideCharType() const
Definition: Type.cpp:2132
bool isAnyPointerType() const
Definition: Type.h:8199
TypeClass getTypeClass() const
Definition: Type.h:2341
bool isSamplerT() const
Definition: Type.h:8398
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:638
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition: Type.cpp:4997
bool isRecordType() const
Definition: Type.h:8291
bool isObjCRetainableType() const
Definition: Type.cpp:5028
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4763
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3528
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3427
Wrapper for source info for typedefs.
Definition: TypeLoc.h:693
void setParensRange(SourceRange range)
Definition: TypeLoc.h:2051
void setTypeofLoc(SourceLocation Loc)
Definition: TypeLoc.h:2027
void setParensRange(SourceRange Range)
Definition: TypeLoc.h:2195
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2171
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition: TypeLoc.h:2183
Wrapper of type source information for a type with no direct qualifiers.
Definition: TypeLoc.h:263
TypeLocClass getTypeLocClass() const
Definition: TypeLoc.h:272
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3343
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:882
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1872
Represents a GCC generic vector type.
Definition: Type.h:4034
VectorKind getVectorKind() const
Definition: Type.h:4054
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
Defines the clang::TargetInfo interface.
const internal::VariadicDynCastAllOfMatcher< Decl, TypedefDecl > typedefDecl
Matches typedef declarations.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
const internal::VariadicDynCastAllOfMatcher< Decl, RecordDecl > recordDecl
Matches class, struct, and union declarations.
The JSON file list parser is used to communicate input to InstallAPI.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_auto_type
Definition: Specifiers.h:94
@ TST_auto
Definition: Specifiers.h:92
@ TST_unspecified
Definition: Specifiers.h:56
@ TST_typename
Definition: Specifiers.h:84
@ TST_decltype_auto
Definition: Specifiers.h:93
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus26
Definition: LangStandard.h:61
@ CPlusPlus17
Definition: LangStandard.h:58
@ ExpectedParameterOrImplicitObjectParameter
Definition: ParsedAttr.h:1104
@ ExpectedFunctionWithProtoType
Definition: ParsedAttr.h:1101
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
@ GNUAutoType
__auto_type (GNU extension)
@ DecltypeAuto
decltype(auto)
llvm::StringRef getParameterABISpelling(ParameterABI kind)
FunctionEffectMode
Used with attributes/effects with a boolean condition, e.g. nonblocking.
Definition: Sema.h:455
LLVM_READONLY bool isAsciiIdentifierContinue(unsigned char c)
Definition: CharInfo.h:61
CUDAFunctionTarget
Definition: Cuda.h:145
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:336
@ Nullable
Values of this type can be null.
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
@ NonNull
Values of this type can never be null.
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1768
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1771
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1774
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:113
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
TypeOfKind
The kind of 'typeof' expression we're after.
Definition: Type.h:910
@ AANT_ArgumentIntegerConstant
Definition: ParsedAttr.h:1079
@ AANT_ArgumentString
Definition: ParsedAttr.h:1080
DeclaratorContext
Definition: DeclSpec.h:1853
@ Result
The result type of a method or function.
llvm::StringRef getNullabilitySpelling(NullabilityKind kind, bool isContextSensitive=false)
Retrieve the spelling of the given nullability kind.
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: Type.h:3574
@ SwiftAsyncContext
This parameter (which must have pointer type) uses the special Swift asynchronous context-pointer ABI...
@ SwiftErrorResult
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
@ Ordinary
This parameter uses ordinary ABI rules for its type.
@ SwiftIndirectResult
This parameter (which must have pointer type) is a Swift indirect result parameter.
@ SwiftContext
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment.
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:307
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
static bool isBlockPointer(Expr *Arg)
Definition: SemaOpenCL.cpp:99
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6876
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
@ Union
The "union" keyword.
@ Enum
The "enum" keyword.
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition: CharInfo.h:108
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1488
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
const FunctionProtoType * T
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition: Specifiers.h:398
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Success
Template argument deduction was successful.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_Swift
Definition: Specifiers.h:293
@ CC_OpenCLKernel
Definition: Specifiers.h:292
@ CC_SwiftAsync
Definition: Specifiers.h:294
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86FastCall
Definition: Specifiers.h:281
VectorKind
Definition: Type.h:3993
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ Neon
is ARM Neon vector
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ NeonPoly
is ARM Neon polynomial vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:86
@ None
The alignment was not explicit in code.
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6851
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Parens
New-expression has a C++98 paren-delimited initializer.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
@ Implicit
An implicit conversion.
#define false
Definition: stdbool.h:26
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
unsigned isStar
True if this dimension was [*]. In this case, NumElts is null.
Definition: DeclSpec.h:1316
unsigned TypeQuals
The type qualifiers for the array: const/volatile/restrict/__unaligned/_Atomic.
Definition: DeclSpec.h:1308
unsigned hasStatic
True if this dimension included the 'static' keyword.
Definition: DeclSpec.h:1312
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition: DeclSpec.h:1321
unsigned TypeQuals
For now, sema will catch these as invalid.
Definition: DeclSpec.h:1605
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition: DeclSpec.h:1368
SourceLocation getTrailingReturnTypeLoc() const
Get the trailing-return-type location for this function declarator.
Definition: DeclSpec.h:1595
SourceLocation getLParenLoc() const
Definition: DeclSpec.h:1510
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition: DeclSpec.h:1586
TypeAndRange * Exceptions
Pointer to a new[]'d array of TypeAndRange objects that contain the types in the function's dynamic e...
Definition: DeclSpec.h:1440
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1428
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition: DeclSpec.h:1589
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition: DeclSpec.h:1377
SourceLocation getExceptionSpecLocBeg() const
Definition: DeclSpec.h:1516
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition: DeclSpec.h:1431
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition: DeclSpec.h:1529
SourceLocation getRParenLoc() const
Definition: DeclSpec.h:1514
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:1512
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1403
unsigned getNumExceptions() const
Get the number of dynamic exception specifications.
Definition: DeclSpec.h:1572
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition: DeclSpec.h:1561
unsigned isAmbiguous
Can this declaration be a constructor-style initializer?
Definition: DeclSpec.h:1372
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1362
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition: DeclSpec.h:1554
SourceRange getExceptionSpecRange() const
Definition: DeclSpec.h:1524
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition: DeclSpec.h:1567
Expr * NoexceptExpr
Pointer to the expression in the noexcept-specifier of this function, if it has one.
Definition: DeclSpec.h:1444
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
Definition: DeclSpec.h:1614
SourceLocation StarLoc
Location of the '*' token.
Definition: DeclSpec.h:1616
const IdentifierInfo * Ident
Definition: DeclSpec.h:1334
SourceLocation RestrictQualLoc
The location of the restrict-qualifier, if any.
Definition: DeclSpec.h:1283
SourceLocation ConstQualLoc
The location of the const-qualifier, if any.
Definition: DeclSpec.h:1277
SourceLocation VolatileQualLoc
The location of the volatile-qualifier, if any.
Definition: DeclSpec.h:1280
SourceLocation UnalignedQualLoc
The location of the __unaligned-qualifier, if any.
Definition: DeclSpec.h:1289
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/unaligned/atomic.
Definition: DeclSpec.h:1274
SourceLocation AtomicQualLoc
The location of the _Atomic-qualifier, if any.
Definition: DeclSpec.h:1286
bool LValueRef
True if this is an lvalue reference, false if it's an rvalue reference.
Definition: DeclSpec.h:1299
bool HasRestrict
The type qualifier: restrict. [GNU] C++ extension.
Definition: DeclSpec.h:1297
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1251
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1663
enum clang::DeclaratorChunk::@224 Kind
SourceLocation EndLoc
EndLoc - If valid, the place where this chunck ends.
Definition: DeclSpec.h:1261
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:158
ReferenceTypeInfo Ref
Definition: DeclSpec.h:1640
BlockPointerTypeInfo Cls
Definition: DeclSpec.h:1643
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1644
ArrayTypeInfo Arr
Definition: DeclSpec.h:1641
SourceLocation Loc
Loc - The place where this type was defined.
Definition: DeclSpec.h:1259
FunctionTypeInfo Fun
Definition: DeclSpec.h:1642
PointerTypeInfo Ptr
Definition: DeclSpec.h:1639
Describes whether we've seen any nullability information for the given file.
Definition: Sema.h:240
SourceLocation PointerEndLoc
The end location for the first pointer declarator in the file.
Definition: Sema.h:247
SourceLocation PointerLoc
The first pointer declarator (of any pointer kind) in the file that does not have a corresponding nul...
Definition: Sema.h:243
bool SawTypeNullability
Whether we saw any type nullability annotations in the given file.
Definition: Sema.h:253
uint8_t PointerKind
Which kind of pointer declarator we saw.
Definition: Sema.h:250
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition: Type.h:4845
Holds information about the various types of exception specification.
Definition: Type.h:5164
Extra information about a function prototype.
Definition: Type.h:5192
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5199
FunctionEffectsRef FunctionEffects
Definition: Type.h:5202
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5200
void setArmSMEAttribute(AArch64SMETypeAttributes Kind, bool Enable=true)
Definition: Type.h:5228
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5193
TypeSourceInfo * ContainedTyInfo
Definition: TypeLoc.h:945
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:103
SourceLocation Loc
Definition: ParsedAttr.h:104
IdentifierInfo * Ident
Definition: ParsedAttr.h:105
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition: DeclSpec.h:2899
unsigned AutoTemplateParameterDepth
If this is a generic lambda or abbreviated function template, use this as the depth of each 'auto' pa...
Definition: DeclSpec.h:2890
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
@ Memoization
Added for Template instantiation observation.
Definition: Sema.h:12764
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7858
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:862
SplitQualType getSingleStepDesugaredType() const
Definition: Type.h:7929
const Type * Ty
The locally-unqualified type.
Definition: Type.h:864
Qualifiers Quals
The local qualifiers.
Definition: Type.h:867
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.