Thanks to visit codestin.com
Credit goes to clang.llvm.org

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