clang 19.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/Type.h"
24#include "clang/AST/TypeLoc.h"
31#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Lookup.h"
36#include "clang/Sema/SemaCUDA.h"
38#include "clang/Sema/Template.h"
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/ADT/STLForwardCompat.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/SmallString.h"
44#include "llvm/ADT/StringExtras.h"
45#include "llvm/IR/DerivedTypes.h"
46#include "llvm/Support/Casting.h"
47#include "llvm/Support/ErrorHandling.h"
48#include <bitset>
49#include <optional>
50
51using namespace clang;
52
57};
58
59/// isOmittedBlockReturnType - Return true if this declarator is missing a
60/// return type because this is a omitted return type on a block literal.
61static bool isOmittedBlockReturnType(const Declarator &D) {
62 if (D.getContext() != DeclaratorContext::BlockLiteral ||
64 return false;
65
66 if (D.getNumTypeObjects() == 0)
67 return true; // ^{ ... }
68
69 if (D.getNumTypeObjects() == 1 &&
71 return true; // ^(int X, float Y) { ... }
72
73 return false;
74}
75
76/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
77/// doesn't apply to the given type.
78static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
79 QualType type) {
80 TypeDiagSelector WhichType;
81 bool useExpansionLoc = true;
82 switch (attr.getKind()) {
83 case ParsedAttr::AT_ObjCGC:
84 WhichType = TDS_Pointer;
85 break;
86 case ParsedAttr::AT_ObjCOwnership:
87 WhichType = TDS_ObjCObjOrBlock;
88 break;
89 default:
90 // Assume everything else was a function attribute.
91 WhichType = TDS_Function;
92 useExpansionLoc = false;
93 break;
94 }
95
96 SourceLocation loc = attr.getLoc();
97 StringRef name = attr.getAttrName()->getName();
98
99 // The GC attributes are usually written with macros; special-case them.
100 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
101 : nullptr;
102 if (useExpansionLoc && loc.isMacroID() && II) {
103 if (II->isStr("strong")) {
104 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
105 } else if (II->isStr("weak")) {
106 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
107 }
108 }
109
110 S.Diag(loc, attr.isRegularKeywordAttribute()
111 ? diag::err_type_attribute_wrong_type
112 : diag::warn_type_attribute_wrong_type)
113 << name << WhichType << type;
114}
115
116// objc_gc applies to Objective-C pointers or, otherwise, to the
117// smallest available pointer type (i.e. 'void*' in 'void**').
118#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
119 case ParsedAttr::AT_ObjCGC: \
120 case ParsedAttr::AT_ObjCOwnership
121
122// Calling convention attributes.
123#define CALLING_CONV_ATTRS_CASELIST \
124 case ParsedAttr::AT_CDecl: \
125 case ParsedAttr::AT_FastCall: \
126 case ParsedAttr::AT_StdCall: \
127 case ParsedAttr::AT_ThisCall: \
128 case ParsedAttr::AT_RegCall: \
129 case ParsedAttr::AT_Pascal: \
130 case ParsedAttr::AT_SwiftCall: \
131 case ParsedAttr::AT_SwiftAsyncCall: \
132 case ParsedAttr::AT_VectorCall: \
133 case ParsedAttr::AT_AArch64VectorPcs: \
134 case ParsedAttr::AT_AArch64SVEPcs: \
135 case ParsedAttr::AT_AMDGPUKernelCall: \
136 case ParsedAttr::AT_MSABI: \
137 case ParsedAttr::AT_SysVABI: \
138 case ParsedAttr::AT_Pcs: \
139 case ParsedAttr::AT_IntelOclBicc: \
140 case ParsedAttr::AT_PreserveMost: \
141 case ParsedAttr::AT_PreserveAll: \
142 case ParsedAttr::AT_M68kRTD: \
143 case ParsedAttr::AT_PreserveNone: \
144 case ParsedAttr::AT_RISCVVectorCC
145
146// Function type attributes.
147#define FUNCTION_TYPE_ATTRS_CASELIST \
148 case ParsedAttr::AT_NSReturnsRetained: \
149 case ParsedAttr::AT_NoReturn: \
150 case ParsedAttr::AT_Regparm: \
151 case ParsedAttr::AT_CmseNSCall: \
152 case ParsedAttr::AT_ArmStreaming: \
153 case ParsedAttr::AT_ArmStreamingCompatible: \
154 case ParsedAttr::AT_ArmPreserves: \
155 case ParsedAttr::AT_ArmIn: \
156 case ParsedAttr::AT_ArmOut: \
157 case ParsedAttr::AT_ArmInOut: \
158 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
159 case ParsedAttr::AT_AnyX86NoCfCheck: \
160 CALLING_CONV_ATTRS_CASELIST
161
162// Microsoft-specific type qualifiers.
163#define MS_TYPE_ATTRS_CASELIST \
164 case ParsedAttr::AT_Ptr32: \
165 case ParsedAttr::AT_Ptr64: \
166 case ParsedAttr::AT_SPtr: \
167 case ParsedAttr::AT_UPtr
168
169// Nullability qualifiers.
170#define NULLABILITY_TYPE_ATTRS_CASELIST \
171 case ParsedAttr::AT_TypeNonNull: \
172 case ParsedAttr::AT_TypeNullable: \
173 case ParsedAttr::AT_TypeNullableResult: \
174 case ParsedAttr::AT_TypeNullUnspecified
175
176namespace {
177 /// An object which stores processing state for the entire
178 /// GetTypeForDeclarator process.
179 class TypeProcessingState {
180 Sema &sema;
181
182 /// The declarator being processed.
183 Declarator &declarator;
184
185 /// The index of the declarator chunk we're currently processing.
186 /// May be the total number of valid chunks, indicating the
187 /// DeclSpec.
188 unsigned chunkIndex;
189
190 /// The original set of attributes on the DeclSpec.
192
193 /// A list of attributes to diagnose the uselessness of when the
194 /// processing is complete.
195 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
196
197 /// Attributes corresponding to AttributedTypeLocs that we have not yet
198 /// populated.
199 // FIXME: The two-phase mechanism by which we construct Types and fill
200 // their TypeLocs makes it hard to correctly assign these. We keep the
201 // attributes in creation order as an attempt to make them line up
202 // properly.
203 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
204 SmallVector<TypeAttrPair, 8> AttrsForTypes;
205 bool AttrsForTypesSorted = true;
206
207 /// MacroQualifiedTypes mapping to macro expansion locations that will be
208 /// stored in a MacroQualifiedTypeLoc.
209 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
210
211 /// Flag to indicate we parsed a noderef attribute. This is used for
212 /// validating that noderef was used on a pointer or array.
213 bool parsedNoDeref;
214
215 public:
216 TypeProcessingState(Sema &sema, Declarator &declarator)
217 : sema(sema), declarator(declarator),
218 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {}
219
220 Sema &getSema() const {
221 return sema;
222 }
223
224 Declarator &getDeclarator() const {
225 return declarator;
226 }
227
228 bool isProcessingDeclSpec() const {
229 return chunkIndex == declarator.getNumTypeObjects();
230 }
231
232 unsigned getCurrentChunkIndex() const {
233 return chunkIndex;
234 }
235
236 void setCurrentChunkIndex(unsigned idx) {
237 assert(idx <= declarator.getNumTypeObjects());
238 chunkIndex = idx;
239 }
240
241 ParsedAttributesView &getCurrentAttributes() const {
242 if (isProcessingDeclSpec())
243 return getMutableDeclSpec().getAttributes();
244 return declarator.getTypeObject(chunkIndex).getAttrs();
245 }
246
247 /// Save the current set of attributes on the DeclSpec.
248 void saveDeclSpecAttrs() {
249 // Don't try to save them multiple times.
250 if (!savedAttrs.empty())
251 return;
252
253 DeclSpec &spec = getMutableDeclSpec();
254 llvm::append_range(savedAttrs,
255 llvm::make_pointer_range(spec.getAttributes()));
256 }
257
258 /// Record that we had nowhere to put the given type attribute.
259 /// We will diagnose such attributes later.
260 void addIgnoredTypeAttr(ParsedAttr &attr) {
261 ignoredTypeAttrs.push_back(&attr);
262 }
263
264 /// Diagnose all the ignored type attributes, given that the
265 /// declarator worked out to the given type.
266 void diagnoseIgnoredTypeAttrs(QualType type) const {
267 for (auto *Attr : ignoredTypeAttrs)
268 diagnoseBadTypeAttribute(getSema(), *Attr, type);
269 }
270
271 /// Get an attributed type for the given attribute, and remember the Attr
272 /// object so that we can attach it to the AttributedTypeLoc.
273 QualType getAttributedType(Attr *A, QualType ModifiedType,
274 QualType EquivType) {
275 QualType T =
276 sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
277 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
278 AttrsForTypesSorted = false;
279 return T;
280 }
281
282 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
283 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
284 QualType WrappedType) {
285 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
286 }
287
288 /// Completely replace the \c auto in \p TypeWithAuto by
289 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
290 /// necessary.
291 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
292 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
293 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
294 // Attributed type still should be an attributed type after replacement.
295 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
296 for (TypeAttrPair &A : AttrsForTypes) {
297 if (A.first == AttrTy)
298 A.first = NewAttrTy;
299 }
300 AttrsForTypesSorted = false;
301 }
302 return T;
303 }
304
305 /// Extract and remove the Attr* for a given attributed type.
306 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
307 if (!AttrsForTypesSorted) {
308 llvm::stable_sort(AttrsForTypes, llvm::less_first());
309 AttrsForTypesSorted = true;
310 }
311
312 // FIXME: This is quadratic if we have lots of reuses of the same
313 // attributed type.
314 for (auto It = std::partition_point(
315 AttrsForTypes.begin(), AttrsForTypes.end(),
316 [=](const TypeAttrPair &A) { return A.first < AT; });
317 It != AttrsForTypes.end() && It->first == AT; ++It) {
318 if (It->second) {
319 const Attr *Result = It->second;
320 It->second = nullptr;
321 return Result;
322 }
323 }
324
325 llvm_unreachable("no Attr* for AttributedType*");
326 }
327
329 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
330 auto FoundLoc = LocsForMacros.find(MQT);
331 assert(FoundLoc != LocsForMacros.end() &&
332 "Unable to find macro expansion location for MacroQualifedType");
333 return FoundLoc->second;
334 }
335
336 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
337 SourceLocation Loc) {
338 LocsForMacros[MQT] = Loc;
339 }
340
341 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
342
343 bool didParseNoDeref() const { return parsedNoDeref; }
344
345 ~TypeProcessingState() {
346 if (savedAttrs.empty())
347 return;
348
349 getMutableDeclSpec().getAttributes().clearListOnly();
350 for (ParsedAttr *AL : savedAttrs)
351 getMutableDeclSpec().getAttributes().addAtEnd(AL);
352 }
353
354 private:
355 DeclSpec &getMutableDeclSpec() const {
356 return const_cast<DeclSpec&>(declarator.getDeclSpec());
357 }
358 };
359} // end anonymous namespace
360
362 ParsedAttributesView &fromList,
363 ParsedAttributesView &toList) {
364 fromList.remove(&attr);
365 toList.addAtEnd(&attr);
366}
367
368/// The location of a type attribute.
370 /// The attribute is in the decl-specifier-seq.
372 /// The attribute is part of a DeclaratorChunk.
374 /// The attribute is immediately after the declaration's name.
377
378static void
379processTypeAttrs(TypeProcessingState &state, QualType &type,
380 TypeAttrLocation TAL, const ParsedAttributesView &attrs,
381 CUDAFunctionTarget CFT = CUDAFunctionTarget::HostDevice);
382
383static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
385
386static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
387 ParsedAttr &attr, QualType &type);
388
389static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
390 QualType &type);
391
392static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
393 ParsedAttr &attr, QualType &type);
394
395static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
396 ParsedAttr &attr, QualType &type) {
397 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
398 return handleObjCGCTypeAttr(state, attr, type);
399 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
400 return handleObjCOwnershipTypeAttr(state, attr, type);
401}
402
403/// Given the index of a declarator chunk, check whether that chunk
404/// directly specifies the return type of a function and, if so, find
405/// an appropriate place for it.
406///
407/// \param i - a notional index which the search will start
408/// immediately inside
409///
410/// \param onlyBlockPointers Whether we should only look into block
411/// pointer types (vs. all pointer types).
413 unsigned i,
414 bool onlyBlockPointers) {
415 assert(i <= declarator.getNumTypeObjects());
416
417 DeclaratorChunk *result = nullptr;
418
419 // First, look inwards past parens for a function declarator.
420 for (; i != 0; --i) {
421 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
422 switch (fnChunk.Kind) {
424 continue;
425
426 // If we find anything except a function, bail out.
433 return result;
434
435 // If we do find a function declarator, scan inwards from that,
436 // looking for a (block-)pointer declarator.
438 for (--i; i != 0; --i) {
439 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
440 switch (ptrChunk.Kind) {
446 continue;
447
450 if (onlyBlockPointers)
451 continue;
452
453 [[fallthrough]];
454
456 result = &ptrChunk;
457 goto continue_outer;
458 }
459 llvm_unreachable("bad declarator chunk kind");
460 }
461
462 // If we run out of declarators doing that, we're done.
463 return result;
464 }
465 llvm_unreachable("bad declarator chunk kind");
466
467 // Okay, reconsider from our new point.
468 continue_outer: ;
469 }
470
471 // Ran out of chunks, bail out.
472 return result;
473}
474
475/// Given that an objc_gc attribute was written somewhere on a
476/// declaration *other* than on the declarator itself (for which, use
477/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
478/// didn't apply in whatever position it was written in, try to move
479/// it to a more appropriate position.
480static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
481 ParsedAttr &attr, QualType type) {
482 Declarator &declarator = state.getDeclarator();
483
484 // Move it to the outermost normal or block pointer declarator.
485 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
486 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
487 switch (chunk.Kind) {
490 // But don't move an ARC ownership attribute to the return type
491 // of a block.
492 DeclaratorChunk *destChunk = nullptr;
493 if (state.isProcessingDeclSpec() &&
494 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
495 destChunk = maybeMovePastReturnType(declarator, i - 1,
496 /*onlyBlockPointers=*/true);
497 if (!destChunk) destChunk = &chunk;
498
499 moveAttrFromListToList(attr, state.getCurrentAttributes(),
500 destChunk->getAttrs());
501 return;
502 }
503
506 continue;
507
508 // We may be starting at the return type of a block.
510 if (state.isProcessingDeclSpec() &&
511 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
513 declarator, i,
514 /*onlyBlockPointers=*/true)) {
515 moveAttrFromListToList(attr, state.getCurrentAttributes(),
516 dest->getAttrs());
517 return;
518 }
519 }
520 goto error;
521
522 // Don't walk through these.
526 goto error;
527 }
528 }
529 error:
530
531 diagnoseBadTypeAttribute(state.getSema(), attr, type);
532}
533
534/// Distribute an objc_gc type attribute that was written on the
535/// declarator.
537 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
538 Declarator &declarator = state.getDeclarator();
539
540 // objc_gc goes on the innermost pointer to something that's not a
541 // pointer.
542 unsigned innermost = -1U;
543 bool considerDeclSpec = true;
544 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
545 DeclaratorChunk &chunk = declarator.getTypeObject(i);
546 switch (chunk.Kind) {
549 innermost = i;
550 continue;
551
557 continue;
558
560 considerDeclSpec = false;
561 goto done;
562 }
563 }
564 done:
565
566 // That might actually be the decl spec if we weren't blocked by
567 // anything in the declarator.
568 if (considerDeclSpec) {
569 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
570 // Splice the attribute into the decl spec. Prevents the
571 // attribute from being applied multiple times and gives
572 // the source-location-filler something to work with.
573 state.saveDeclSpecAttrs();
575 declarator.getAttributes(), &attr);
576 return;
577 }
578 }
579
580 // Otherwise, if we found an appropriate chunk, splice the attribute
581 // into it.
582 if (innermost != -1U) {
584 declarator.getTypeObject(innermost).getAttrs());
585 return;
586 }
587
588 // Otherwise, diagnose when we're done building the type.
589 declarator.getAttributes().remove(&attr);
590 state.addIgnoredTypeAttr(attr);
591}
592
593/// A function type attribute was written somewhere in a declaration
594/// *other* than on the declarator itself or in the decl spec. Given
595/// that it didn't apply in whatever position it was written in, try
596/// to move it to a more appropriate position.
597static void distributeFunctionTypeAttr(TypeProcessingState &state,
598 ParsedAttr &attr, QualType type) {
599 Declarator &declarator = state.getDeclarator();
600
601 // Try to push the attribute from the return type of a function to
602 // the function itself.
603 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
604 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
605 switch (chunk.Kind) {
607 moveAttrFromListToList(attr, state.getCurrentAttributes(),
608 chunk.getAttrs());
609 return;
610
618 continue;
619 }
620 }
621
622 diagnoseBadTypeAttribute(state.getSema(), attr, type);
623}
624
625/// Try to distribute a function type attribute to the innermost
626/// function chunk or type. Returns true if the attribute was
627/// distributed, false if no location was found.
629 TypeProcessingState &state, ParsedAttr &attr,
630 ParsedAttributesView &attrList, QualType &declSpecType,
631 CUDAFunctionTarget CFT) {
632 Declarator &declarator = state.getDeclarator();
633
634 // Put it on the innermost function chunk, if there is one.
635 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
636 DeclaratorChunk &chunk = declarator.getTypeObject(i);
637 if (chunk.Kind != DeclaratorChunk::Function) continue;
638
639 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
640 return true;
641 }
642
643 return handleFunctionTypeAttr(state, attr, declSpecType, CFT);
644}
645
646/// A function type attribute was written in the decl spec. Try to
647/// apply it somewhere.
648static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
649 ParsedAttr &attr,
650 QualType &declSpecType,
651 CUDAFunctionTarget CFT) {
652 state.saveDeclSpecAttrs();
653
654 // Try to distribute to the innermost.
656 state, attr, state.getCurrentAttributes(), declSpecType, CFT))
657 return;
658
659 // If that failed, diagnose the bad attribute when the declarator is
660 // fully built.
661 state.addIgnoredTypeAttr(attr);
662}
663
664/// A function type attribute was written on the declarator or declaration.
665/// Try to apply it somewhere.
666/// `Attrs` is the attribute list containing the declaration (either of the
667/// declarator or the declaration).
668static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
669 ParsedAttr &attr,
670 QualType &declSpecType,
671 CUDAFunctionTarget CFT) {
672 Declarator &declarator = state.getDeclarator();
673
674 // Try to distribute to the innermost.
676 state, attr, declarator.getAttributes(), declSpecType, CFT))
677 return;
678
679 // If that failed, diagnose the bad attribute when the declarator is
680 // fully built.
681 declarator.getAttributes().remove(&attr);
682 state.addIgnoredTypeAttr(attr);
683}
684
685/// Given that there are attributes written on the declarator or declaration
686/// itself, try to distribute any type attributes to the appropriate
687/// declarator chunk.
688///
689/// These are attributes like the following:
690/// int f ATTR;
691/// int (f ATTR)();
692/// but not necessarily this:
693/// int f() ATTR;
694///
695/// `Attrs` is the attribute list containing the declaration (either of the
696/// declarator or the declaration).
697static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
698 QualType &declSpecType,
699 CUDAFunctionTarget CFT) {
700 // The called functions in this loop actually remove things from the current
701 // list, so iterating over the existing list isn't possible. Instead, make a
702 // non-owning copy and iterate over that.
703 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
704 for (ParsedAttr &attr : AttrsCopy) {
705 // Do not distribute [[]] attributes. They have strict rules for what
706 // they appertain to.
707 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute())
708 continue;
709
710 switch (attr.getKind()) {
713 break;
714
716 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT);
717 break;
718
720 // Microsoft type attributes cannot go after the declarator-id.
721 continue;
722
724 // Nullability specifiers cannot go after the declarator-id.
725
726 // Objective-C __kindof does not get distributed.
727 case ParsedAttr::AT_ObjCKindOf:
728 continue;
729
730 default:
731 break;
732 }
733 }
734}
735
736/// Add a synthetic '()' to a block-literal declarator if it is
737/// required, given the return type.
738static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
739 QualType declSpecType) {
740 Declarator &declarator = state.getDeclarator();
741
742 // First, check whether the declarator would produce a function,
743 // i.e. whether the innermost semantic chunk is a function.
744 if (declarator.isFunctionDeclarator()) {
745 // If so, make that declarator a prototyped declarator.
746 declarator.getFunctionTypeInfo().hasPrototype = true;
747 return;
748 }
749
750 // If there are any type objects, the type as written won't name a
751 // function, regardless of the decl spec type. This is because a
752 // block signature declarator is always an abstract-declarator, and
753 // abstract-declarators can't just be parentheses chunks. Therefore
754 // we need to build a function chunk unless there are no type
755 // objects and the decl spec type is a function.
756 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
757 return;
758
759 // Note that there *are* cases with invalid declarators where
760 // declarators consist solely of parentheses. In general, these
761 // occur only in failed efforts to make function declarators, so
762 // faking up the function chunk is still the right thing to do.
763
764 // Otherwise, we need to fake up a function declarator.
765 SourceLocation loc = declarator.getBeginLoc();
766
767 // ...and *prepend* it to the declarator.
768 SourceLocation NoLoc;
770 /*HasProto=*/true,
771 /*IsAmbiguous=*/false,
772 /*LParenLoc=*/NoLoc,
773 /*ArgInfo=*/nullptr,
774 /*NumParams=*/0,
775 /*EllipsisLoc=*/NoLoc,
776 /*RParenLoc=*/NoLoc,
777 /*RefQualifierIsLvalueRef=*/true,
778 /*RefQualifierLoc=*/NoLoc,
779 /*MutableLoc=*/NoLoc, EST_None,
780 /*ESpecRange=*/SourceRange(),
781 /*Exceptions=*/nullptr,
782 /*ExceptionRanges=*/nullptr,
783 /*NumExceptions=*/0,
784 /*NoexceptExpr=*/nullptr,
785 /*ExceptionSpecTokens=*/nullptr,
786 /*DeclsInPrototype=*/std::nullopt, loc, loc, declarator));
787
788 // For consistency, make sure the state still has us as processing
789 // the decl spec.
790 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
791 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
792}
793
795 unsigned &TypeQuals,
796 QualType TypeSoFar,
797 unsigned RemoveTQs,
798 unsigned DiagID) {
799 // If this occurs outside a template instantiation, warn the user about
800 // it; they probably didn't mean to specify a redundant qualifier.
801 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
802 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
805 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
806 if (!(RemoveTQs & Qual.first))
807 continue;
808
809 if (!S.inTemplateInstantiation()) {
810 if (TypeQuals & Qual.first)
811 S.Diag(Qual.second, DiagID)
812 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
813 << FixItHint::CreateRemoval(Qual.second);
814 }
815
816 TypeQuals &= ~Qual.first;
817 }
818}
819
820/// Return true if this is omitted block return type. Also check type
821/// attributes and type qualifiers when returning true.
822static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
823 QualType Result) {
824 if (!isOmittedBlockReturnType(declarator))
825 return false;
826
827 // Warn if we see type attributes for omitted return type on a block literal.
829 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
830 if (AL.isInvalid() || !AL.isTypeAttr())
831 continue;
832 S.Diag(AL.getLoc(),
833 diag::warn_block_literal_attributes_on_omitted_return_type)
834 << AL;
835 ToBeRemoved.push_back(&AL);
836 }
837 // Remove bad attributes from the list.
838 for (ParsedAttr *AL : ToBeRemoved)
839 declarator.getMutableDeclSpec().getAttributes().remove(AL);
840
841 // Warn if we see type qualifiers for omitted return type on a block literal.
842 const DeclSpec &DS = declarator.getDeclSpec();
843 unsigned TypeQuals = DS.getTypeQualifiers();
844 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
845 diag::warn_block_literal_qualifiers_on_omitted_return_type);
847
848 return true;
849}
850
851/// Apply Objective-C type arguments to the given type.
854 SourceRange typeArgsRange, bool failOnError,
855 bool rebuilding) {
856 // We can only apply type arguments to an Objective-C class type.
857 const auto *objcObjectType = type->getAs<ObjCObjectType>();
858 if (!objcObjectType || !objcObjectType->getInterface()) {
859 S.Diag(loc, diag::err_objc_type_args_non_class)
860 << type
861 << typeArgsRange;
862
863 if (failOnError)
864 return QualType();
865 return type;
866 }
867
868 // The class type must be parameterized.
869 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
870 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
871 if (!typeParams) {
872 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
873 << objcClass->getDeclName()
874 << FixItHint::CreateRemoval(typeArgsRange);
875
876 if (failOnError)
877 return QualType();
878
879 return type;
880 }
881
882 // The type must not already be specialized.
883 if (objcObjectType->isSpecialized()) {
884 S.Diag(loc, diag::err_objc_type_args_specialized_class)
885 << type
886 << FixItHint::CreateRemoval(typeArgsRange);
887
888 if (failOnError)
889 return QualType();
890
891 return type;
892 }
893
894 // Check the type arguments.
895 SmallVector<QualType, 4> finalTypeArgs;
896 unsigned numTypeParams = typeParams->size();
897 bool anyPackExpansions = false;
898 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
899 TypeSourceInfo *typeArgInfo = typeArgs[i];
900 QualType typeArg = typeArgInfo->getType();
901
902 // Type arguments cannot have explicit qualifiers or nullability.
903 // We ignore indirect sources of these, e.g. behind typedefs or
904 // template arguments.
905 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
906 bool diagnosed = false;
907 SourceRange rangeToRemove;
908 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
909 rangeToRemove = attr.getLocalSourceRange();
910 if (attr.getTypePtr()->getImmediateNullability()) {
911 typeArg = attr.getTypePtr()->getModifiedType();
912 S.Diag(attr.getBeginLoc(),
913 diag::err_objc_type_arg_explicit_nullability)
914 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
915 diagnosed = true;
916 }
917 }
918
919 // When rebuilding, qualifiers might have gotten here through a
920 // final substitution.
921 if (!rebuilding && !diagnosed) {
922 S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
923 << typeArg << typeArg.getQualifiers().getAsString()
924 << FixItHint::CreateRemoval(rangeToRemove);
925 }
926 }
927
928 // Remove qualifiers even if they're non-local.
929 typeArg = typeArg.getUnqualifiedType();
930
931 finalTypeArgs.push_back(typeArg);
932
933 if (typeArg->getAs<PackExpansionType>())
934 anyPackExpansions = true;
935
936 // Find the corresponding type parameter, if there is one.
937 ObjCTypeParamDecl *typeParam = nullptr;
938 if (!anyPackExpansions) {
939 if (i < numTypeParams) {
940 typeParam = typeParams->begin()[i];
941 } else {
942 // Too many arguments.
943 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
944 << false
945 << objcClass->getDeclName()
946 << (unsigned)typeArgs.size()
947 << numTypeParams;
948 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
949 << objcClass;
950
951 if (failOnError)
952 return QualType();
953
954 return type;
955 }
956 }
957
958 // Objective-C object pointer types must be substitutable for the bounds.
959 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
960 // If we don't have a type parameter to match against, assume
961 // everything is fine. There was a prior pack expansion that
962 // means we won't be able to match anything.
963 if (!typeParam) {
964 assert(anyPackExpansions && "Too many arguments?");
965 continue;
966 }
967
968 // Retrieve the bound.
969 QualType bound = typeParam->getUnderlyingType();
970 const auto *boundObjC = bound->castAs<ObjCObjectPointerType>();
971
972 // Determine whether the type argument is substitutable for the bound.
973 if (typeArgObjC->isObjCIdType()) {
974 // When the type argument is 'id', the only acceptable type
975 // parameter bound is 'id'.
976 if (boundObjC->isObjCIdType())
977 continue;
978 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
979 // Otherwise, we follow the assignability rules.
980 continue;
981 }
982
983 // Diagnose the mismatch.
984 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
985 diag::err_objc_type_arg_does_not_match_bound)
986 << typeArg << bound << typeParam->getDeclName();
987 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
988 << typeParam->getDeclName();
989
990 if (failOnError)
991 return QualType();
992
993 return type;
994 }
995
996 // Block pointer types are permitted for unqualified 'id' bounds.
997 if (typeArg->isBlockPointerType()) {
998 // If we don't have a type parameter to match against, assume
999 // everything is fine. There was a prior pack expansion that
1000 // means we won't be able to match anything.
1001 if (!typeParam) {
1002 assert(anyPackExpansions && "Too many arguments?");
1003 continue;
1004 }
1005
1006 // Retrieve the bound.
1007 QualType bound = typeParam->getUnderlyingType();
1009 continue;
1010
1011 // Diagnose the mismatch.
1012 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1013 diag::err_objc_type_arg_does_not_match_bound)
1014 << typeArg << bound << typeParam->getDeclName();
1015 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
1016 << typeParam->getDeclName();
1017
1018 if (failOnError)
1019 return QualType();
1020
1021 return type;
1022 }
1023
1024 // Types that have __attribute__((NSObject)) are permitted.
1025 if (typeArg->isObjCNSObjectType()) {
1026 continue;
1027 }
1028
1029 // Dependent types will be checked at instantiation time.
1030 if (typeArg->isDependentType()) {
1031 continue;
1032 }
1033
1034 // Diagnose non-id-compatible type arguments.
1035 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1036 diag::err_objc_type_arg_not_id_compatible)
1037 << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
1038
1039 if (failOnError)
1040 return QualType();
1041
1042 return type;
1043 }
1044
1045 // Make sure we didn't have the wrong number of arguments.
1046 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
1047 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
1048 << (typeArgs.size() < typeParams->size())
1049 << objcClass->getDeclName()
1050 << (unsigned)finalTypeArgs.size()
1051 << (unsigned)numTypeParams;
1052 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1053 << objcClass;
1054
1055 if (failOnError)
1056 return QualType();
1057
1058 return type;
1059 }
1060
1061 // Success. Form the specialized type.
1062 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1063}
1064
1066 SourceLocation ProtocolLAngleLoc,
1068 ArrayRef<SourceLocation> ProtocolLocs,
1069 SourceLocation ProtocolRAngleLoc,
1070 bool FailOnError) {
1071 QualType Result = QualType(Decl->getTypeForDecl(), 0);
1072 if (!Protocols.empty()) {
1073 bool HasError;
1075 HasError);
1076 if (HasError) {
1077 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1078 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1079 if (FailOnError) Result = QualType();
1080 }
1081 if (FailOnError && Result.isNull())
1082 return QualType();
1083 }
1084
1085 return Result;
1086}
1087
1089 QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc,
1090 ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc,
1091 SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols,
1092 ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
1093 bool FailOnError, bool Rebuilding) {
1094 QualType Result = BaseType;
1095 if (!TypeArgs.empty()) {
1096 Result =
1097 applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1098 SourceRange(TypeArgsLAngleLoc, TypeArgsRAngleLoc),
1099 FailOnError, Rebuilding);
1100 if (FailOnError && Result.isNull())
1101 return QualType();
1102 }
1103
1104 if (!Protocols.empty()) {
1105 bool HasError;
1107 HasError);
1108 if (HasError) {
1109 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1110 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1111 if (FailOnError) Result = QualType();
1112 }
1113 if (FailOnError && Result.isNull())
1114 return QualType();
1115 }
1116
1117 return Result;
1118}
1119
1121 SourceLocation lAngleLoc,
1122 ArrayRef<Decl *> protocols,
1123 ArrayRef<SourceLocation> protocolLocs,
1124 SourceLocation rAngleLoc) {
1125 // Form id<protocol-list>.
1128 llvm::ArrayRef((ObjCProtocolDecl *const *)protocols.data(),
1129 protocols.size()),
1130 false);
1132
1134 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1135
1136 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1137 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1138
1139 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1140 .castAs<ObjCObjectTypeLoc>();
1141 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1142 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1143
1144 // No type arguments.
1145 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1146 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1147
1148 // Fill in protocol qualifiers.
1149 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1150 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1151 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1152 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1153
1154 // We're done. Return the completed type to the parser.
1155 return CreateParsedType(Result, ResultTInfo);
1156}
1157
1159 Scope *S,
1160 SourceLocation Loc,
1161 ParsedType BaseType,
1162 SourceLocation TypeArgsLAngleLoc,
1163 ArrayRef<ParsedType> TypeArgs,
1164 SourceLocation TypeArgsRAngleLoc,
1165 SourceLocation ProtocolLAngleLoc,
1166 ArrayRef<Decl *> Protocols,
1167 ArrayRef<SourceLocation> ProtocolLocs,
1168 SourceLocation ProtocolRAngleLoc) {
1169 TypeSourceInfo *BaseTypeInfo = nullptr;
1170 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1171 if (T.isNull())
1172 return true;
1173
1174 // Handle missing type-source info.
1175 if (!BaseTypeInfo)
1176 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1177
1178 // Extract type arguments.
1179 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1180 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1181 TypeSourceInfo *TypeArgInfo = nullptr;
1182 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1183 if (TypeArg.isNull()) {
1184 ActualTypeArgInfos.clear();
1185 break;
1186 }
1187
1188 assert(TypeArgInfo && "No type source info?");
1189 ActualTypeArgInfos.push_back(TypeArgInfo);
1190 }
1191
1192 // Build the object type.
1194 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1195 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1196 ProtocolLAngleLoc,
1197 llvm::ArrayRef((ObjCProtocolDecl *const *)Protocols.data(),
1198 Protocols.size()),
1199 ProtocolLocs, ProtocolRAngleLoc,
1200 /*FailOnError=*/false,
1201 /*Rebuilding=*/false);
1202
1203 if (Result == T)
1204 return BaseType;
1205
1206 // Create source information for this type.
1208 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1209
1210 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1211 // object pointer type. Fill in source information for it.
1212 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1213 // The '*' is implicit.
1214 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1215 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1216 }
1217
1218 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1219 // Protocol qualifier information.
1220 if (OTPTL.getNumProtocols() > 0) {
1221 assert(OTPTL.getNumProtocols() == Protocols.size());
1222 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1223 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1224 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1225 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1226 }
1227
1228 // We're done. Return the completed type to the parser.
1229 return CreateParsedType(Result, ResultTInfo);
1230 }
1231
1232 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1233
1234 // Type argument information.
1235 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1236 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1237 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1238 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1239 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1240 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1241 } else {
1242 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1243 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1244 }
1245
1246 // Protocol qualifier information.
1247 if (ObjCObjectTL.getNumProtocols() > 0) {
1248 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1249 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1250 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1251 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1252 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1253 } else {
1254 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1255 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1256 }
1257
1258 // Base type.
1259 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1260 if (ObjCObjectTL.getType() == T)
1261 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1262 else
1263 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1264
1265 // We're done. Return the completed type to the parser.
1266 return CreateParsedType(Result, ResultTInfo);
1267}
1268
1269static OpenCLAccessAttr::Spelling
1271 for (const ParsedAttr &AL : Attrs)
1272 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1273 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1274 return OpenCLAccessAttr::Keyword_read_only;
1275}
1276
1279 switch (SwitchTST) {
1280#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
1281 case TST_##Trait: \
1282 return UnaryTransformType::Enum;
1283#include "clang/Basic/TransformTypeTraits.def"
1284 default:
1285 llvm_unreachable("attempted to parse a non-unary transform builtin");
1286 }
1287}
1288
1289/// Convert the specified declspec to the appropriate type
1290/// object.
1291/// \param state Specifies the declarator containing the declaration specifier
1292/// to be converted, along with other associated processing state.
1293/// \returns The type described by the declaration specifiers. This function
1294/// never returns null.
1295static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1296 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1297 // checking.
1298
1299 Sema &S = state.getSema();
1300 Declarator &declarator = state.getDeclarator();
1301 DeclSpec &DS = declarator.getMutableDeclSpec();
1302 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1303 if (DeclLoc.isInvalid())
1304 DeclLoc = DS.getBeginLoc();
1305
1306 ASTContext &Context = S.Context;
1307
1309 switch (DS.getTypeSpecType()) {
1310 case DeclSpec::TST_void:
1311 Result = Context.VoidTy;
1312 break;
1313 case DeclSpec::TST_char:
1315 Result = Context.CharTy;
1317 Result = Context.SignedCharTy;
1318 else {
1320 "Unknown TSS value");
1321 Result = Context.UnsignedCharTy;
1322 }
1323 break;
1326 Result = Context.WCharTy;
1327 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
1328 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1330 Context.getPrintingPolicy());
1331 Result = Context.getSignedWCharType();
1332 } else {
1334 "Unknown TSS value");
1335 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1337 Context.getPrintingPolicy());
1338 Result = Context.getUnsignedWCharType();
1339 }
1340 break;
1343 "Unknown TSS value");
1344 Result = Context.Char8Ty;
1345 break;
1348 "Unknown TSS value");
1349 Result = Context.Char16Ty;
1350 break;
1353 "Unknown TSS value");
1354 Result = Context.Char32Ty;
1355 break;
1357 // If this is a missing declspec in a block literal return context, then it
1358 // is inferred from the return statements inside the block.
1359 // The declspec is always missing in a lambda expr context; it is either
1360 // specified with a trailing return type or inferred.
1361 if (S.getLangOpts().CPlusPlus14 &&
1362 declarator.getContext() == DeclaratorContext::LambdaExpr) {
1363 // In C++1y, a lambda's implicit return type is 'auto'.
1364 Result = Context.getAutoDeductType();
1365 break;
1366 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
1367 checkOmittedBlockReturnType(S, declarator,
1368 Context.DependentTy)) {
1369 Result = Context.DependentTy;
1370 break;
1371 }
1372
1373 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1374 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1375 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1376 // Note that the one exception to this is function definitions, which are
1377 // allowed to be completely missing a declspec. This is handled in the
1378 // parser already though by it pretending to have seen an 'int' in this
1379 // case.
1381 S.Diag(DeclLoc, diag::warn_missing_type_specifier)
1382 << DS.getSourceRange()
1384 } else if (!DS.hasTypeSpecifier()) {
1385 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1386 // "At least one type specifier shall be given in the declaration
1387 // specifiers in each declaration, and in the specifier-qualifier list in
1388 // each struct declaration and type name."
1389 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
1390 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1391 << DS.getSourceRange();
1392
1393 // When this occurs, often something is very broken with the value
1394 // being declared, poison it as invalid so we don't get chains of
1395 // errors.
1396 declarator.setInvalidType(true);
1397 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1398 DS.isTypeSpecPipe()) {
1399 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1400 << DS.getSourceRange();
1401 declarator.setInvalidType(true);
1402 } else {
1403 assert(S.getLangOpts().isImplicitIntAllowed() &&
1404 "implicit int is disabled?");
1405 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1406 << DS.getSourceRange()
1408 }
1409 }
1410
1411 [[fallthrough]];
1412 case DeclSpec::TST_int: {
1414 switch (DS.getTypeSpecWidth()) {
1416 Result = Context.IntTy;
1417 break;
1419 Result = Context.ShortTy;
1420 break;
1422 Result = Context.LongTy;
1423 break;
1425 Result = Context.LongLongTy;
1426
1427 // 'long long' is a C99 or C++11 feature.
1428 if (!S.getLangOpts().C99) {
1429 if (S.getLangOpts().CPlusPlus)
1431 S.getLangOpts().CPlusPlus11 ?
1432 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1433 else
1434 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1435 }
1436 break;
1437 }
1438 } else {
1439 switch (DS.getTypeSpecWidth()) {
1441 Result = Context.UnsignedIntTy;
1442 break;
1444 Result = Context.UnsignedShortTy;
1445 break;
1447 Result = Context.UnsignedLongTy;
1448 break;
1450 Result = Context.UnsignedLongLongTy;
1451
1452 // 'long long' is a C99 or C++11 feature.
1453 if (!S.getLangOpts().C99) {
1454 if (S.getLangOpts().CPlusPlus)
1456 S.getLangOpts().CPlusPlus11 ?
1457 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1458 else
1459 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1460 }
1461 break;
1462 }
1463 }
1464 break;
1465 }
1466 case DeclSpec::TST_bitint: {
1468 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1469 Result =
1471 DS.getRepAsExpr(), DS.getBeginLoc());
1472 if (Result.isNull()) {
1473 Result = Context.IntTy;
1474 declarator.setInvalidType(true);
1475 }
1476 break;
1477 }
1478 case DeclSpec::TST_accum: {
1479 switch (DS.getTypeSpecWidth()) {
1481 Result = Context.ShortAccumTy;
1482 break;
1484 Result = Context.AccumTy;
1485 break;
1487 Result = Context.LongAccumTy;
1488 break;
1490 llvm_unreachable("Unable to specify long long as _Accum width");
1491 }
1492
1495
1496 if (DS.isTypeSpecSat())
1498
1499 break;
1500 }
1501 case DeclSpec::TST_fract: {
1502 switch (DS.getTypeSpecWidth()) {
1504 Result = Context.ShortFractTy;
1505 break;
1507 Result = Context.FractTy;
1508 break;
1510 Result = Context.LongFractTy;
1511 break;
1513 llvm_unreachable("Unable to specify long long as _Fract width");
1514 }
1515
1518
1519 if (DS.isTypeSpecSat())
1521
1522 break;
1523 }
1525 if (!S.Context.getTargetInfo().hasInt128Type() &&
1526 !(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice ||
1527 (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice)))
1528 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1529 << "__int128";
1531 Result = Context.UnsignedInt128Ty;
1532 else
1533 Result = Context.Int128Ty;
1534 break;
1536 // CUDA host and device may have different _Float16 support, therefore
1537 // do not diagnose _Float16 usage to avoid false alarm.
1538 // ToDo: more precise diagnostics for CUDA.
1539 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1540 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1541 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1542 << "_Float16";
1543 Result = Context.Float16Ty;
1544 break;
1545 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1548 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) &&
1549 !S.getLangOpts().SYCLIsDevice)
1550 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16";
1551 Result = Context.BFloat16Ty;
1552 break;
1553 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1556 Result = Context.LongDoubleTy;
1557 else
1558 Result = Context.DoubleTy;
1559 if (S.getLangOpts().OpenCL) {
1560 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1561 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1562 << 0 << Result
1564 ? "cl_khr_fp64 and __opencl_c_fp64"
1565 : "cl_khr_fp64");
1566 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1567 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1568 }
1569 break;
1572 !S.getLangOpts().SYCLIsDevice && !S.getLangOpts().CUDAIsDevice &&
1573 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1574 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1575 << "__float128";
1576 Result = Context.Float128Ty;
1577 break;
1579 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1580 !S.getLangOpts().SYCLIsDevice &&
1581 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1582 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1583 Result = Context.Ibm128Ty;
1584 break;
1585 case DeclSpec::TST_bool:
1586 Result = Context.BoolTy; // _Bool or bool
1587 break;
1588 case DeclSpec::TST_decimal32: // _Decimal32
1589 case DeclSpec::TST_decimal64: // _Decimal64
1590 case DeclSpec::TST_decimal128: // _Decimal128
1591 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1592 Result = Context.IntTy;
1593 declarator.setInvalidType(true);
1594 break;
1596 case DeclSpec::TST_enum:
1600 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1601 if (!D) {
1602 // This can happen in C++ with ambiguous lookups.
1603 Result = Context.IntTy;
1604 declarator.setInvalidType(true);
1605 break;
1606 }
1607
1608 // If the type is deprecated or unavailable, diagnose it.
1610
1612 DS.getTypeSpecComplex() == 0 &&
1614 "No qualifiers on tag names!");
1615
1616 // TypeQuals handled by caller.
1617 Result = Context.getTypeDeclType(D);
1618
1619 // In both C and C++, make an ElaboratedType.
1620 ElaboratedTypeKeyword Keyword
1623 DS.isTypeSpecOwned() ? D : nullptr);
1624 break;
1625 }
1628 DS.getTypeSpecComplex() == 0 &&
1630 "Can't handle qualifiers on typedef names yet!");
1632 if (Result.isNull()) {
1633 declarator.setInvalidType(true);
1634 }
1635
1636 // TypeQuals handled by caller.
1637 break;
1638 }
1641 // FIXME: Preserve type source info.
1643 assert(!Result.isNull() && "Didn't get a type for typeof?");
1644 if (!Result->isDependentType())
1645 if (const TagType *TT = Result->getAs<TagType>())
1646 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1647 // TypeQuals handled by caller.
1648 Result = Context.getTypeOfType(
1652 break;
1655 Expr *E = DS.getRepAsExpr();
1656 assert(E && "Didn't get an expression for typeof?");
1657 // TypeQuals handled by caller.
1662 if (Result.isNull()) {
1663 Result = Context.IntTy;
1664 declarator.setInvalidType(true);
1665 }
1666 break;
1667 }
1669 Expr *E = DS.getRepAsExpr();
1670 assert(E && "Didn't get an expression for decltype?");
1671 // TypeQuals handled by caller.
1673 if (Result.isNull()) {
1674 Result = Context.IntTy;
1675 declarator.setInvalidType(true);
1676 }
1677 break;
1678 }
1680 Expr *E = DS.getPackIndexingExpr();
1681 assert(E && "Didn't get an expression for pack indexing");
1682 QualType Pattern = S.GetTypeFromParser(DS.getRepAsType());
1683 Result = S.BuildPackIndexingType(Pattern, E, DS.getBeginLoc(),
1684 DS.getEllipsisLoc());
1685 if (Result.isNull()) {
1686 declarator.setInvalidType(true);
1687 Result = Context.IntTy;
1688 }
1689 break;
1690 }
1691
1692#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1693#include "clang/Basic/TransformTypeTraits.def"
1695 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1698 DS.getTypeSpecTypeLoc());
1699 if (Result.isNull()) {
1700 Result = Context.IntTy;
1701 declarator.setInvalidType(true);
1702 }
1703 break;
1704
1705 case DeclSpec::TST_auto:
1707 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1710
1711 ConceptDecl *TypeConstraintConcept = nullptr;
1713 if (DS.isConstrainedAuto()) {
1714 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1715 TypeConstraintConcept =
1716 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1717 TemplateArgumentListInfo TemplateArgsInfo;
1718 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1719 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1720 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1721 TemplateId->NumArgs);
1722 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1723 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1724 TemplateArgs.push_back(ArgLoc.getArgument());
1725 } else {
1726 declarator.setInvalidType(true);
1727 }
1728 }
1729 Result = S.Context.getAutoType(QualType(), AutoKW,
1730 /*IsDependent*/ false, /*IsPack=*/false,
1731 TypeConstraintConcept, TemplateArgs);
1732 break;
1733 }
1734
1737 break;
1738
1740 Result = Context.UnknownAnyTy;
1741 break;
1742
1745 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1747 if (Result.isNull()) {
1748 Result = Context.IntTy;
1749 declarator.setInvalidType(true);
1750 }
1751 break;
1752
1753#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1754 case DeclSpec::TST_##ImgType##_t: \
1755 switch (getImageAccess(DS.getAttributes())) { \
1756 case OpenCLAccessAttr::Keyword_write_only: \
1757 Result = Context.Id##WOTy; \
1758 break; \
1759 case OpenCLAccessAttr::Keyword_read_write: \
1760 Result = Context.Id##RWTy; \
1761 break; \
1762 case OpenCLAccessAttr::Keyword_read_only: \
1763 Result = Context.Id##ROTy; \
1764 break; \
1765 case OpenCLAccessAttr::SpellingNotCalculated: \
1766 llvm_unreachable("Spelling not yet calculated"); \
1767 } \
1768 break;
1769#include "clang/Basic/OpenCLImageTypes.def"
1770
1772 Result = Context.IntTy;
1773 declarator.setInvalidType(true);
1774 break;
1775 }
1776
1777 // FIXME: we want resulting declarations to be marked invalid, but claiming
1778 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1779 // a null type.
1780 if (Result->containsErrors())
1781 declarator.setInvalidType();
1782
1783 if (S.getLangOpts().OpenCL) {
1784 const auto &OpenCLOptions = S.getOpenCLOptions();
1785 bool IsOpenCLC30Compatible =
1787 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1788 // support.
1789 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1790 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1791 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1792 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1793 // only when the optional feature is supported
1794 if ((Result->isImageType() || Result->isSamplerT()) &&
1795 (IsOpenCLC30Compatible &&
1796 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1797 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1798 << 0 << Result << "__opencl_c_images";
1799 declarator.setInvalidType();
1800 } else if (Result->isOCLImage3dWOType() &&
1801 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1802 S.getLangOpts())) {
1803 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1804 << 0 << Result
1805 << (IsOpenCLC30Compatible
1806 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1807 : "cl_khr_3d_image_writes");
1808 declarator.setInvalidType();
1809 }
1810 }
1811
1812 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1814
1815 // Only fixed point types can be saturated
1816 if (DS.isTypeSpecSat() && !IsFixedPointType)
1817 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1819 Context.getPrintingPolicy());
1820
1821 // Handle complex types.
1823 if (S.getLangOpts().Freestanding)
1824 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1825 Result = Context.getComplexType(Result);
1826 } else if (DS.isTypeAltiVecVector()) {
1827 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1828 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1830 if (DS.isTypeAltiVecPixel())
1831 VecKind = VectorKind::AltiVecPixel;
1832 else if (DS.isTypeAltiVecBool())
1833 VecKind = VectorKind::AltiVecBool;
1834 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1835 }
1836
1837 // FIXME: Imaginary.
1839 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1840
1841 // Before we process any type attributes, synthesize a block literal
1842 // function declarator if necessary.
1843 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1845
1846 // Apply any type attributes from the decl spec. This may cause the
1847 // list of type attributes to be temporarily saved while the type
1848 // attributes are pushed around.
1849 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1850 if (!DS.isTypeSpecPipe()) {
1851 // We also apply declaration attributes that "slide" to the decl spec.
1852 // Ordering can be important for attributes. The decalaration attributes
1853 // come syntactically before the decl spec attributes, so we process them
1854 // in that order.
1855 ParsedAttributesView SlidingAttrs;
1856 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1857 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1858 SlidingAttrs.addAtEnd(&AL);
1859
1860 // For standard syntax attributes, which would normally appertain to the
1861 // declaration here, suggest moving them to the type instead. But only
1862 // do this for our own vendor attributes; moving other vendors'
1863 // attributes might hurt portability.
1864 // There's one special case that we need to deal with here: The
1865 // `MatrixType` attribute may only be used in a typedef declaration. If
1866 // it's being used anywhere else, don't output the warning as
1867 // ProcessDeclAttributes() will output an error anyway.
1868 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1869 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1871 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1872 << AL;
1873 }
1874 }
1875 }
1876 // During this call to processTypeAttrs(),
1877 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1878 // reference to the DeclSpec attributes, rather than the declaration
1879 // attributes. However, this doesn't matter, as getCurrentAttributes()
1880 // is only called when distributing attributes from one attribute list
1881 // to another. Declaration attributes are always C++11 attributes, and these
1882 // are never distributed.
1883 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1885 }
1886
1887 // Apply const/volatile/restrict qualifiers to T.
1888 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1889 // Warn about CV qualifiers on function types.
1890 // C99 6.7.3p8:
1891 // If the specification of a function type includes any type qualifiers,
1892 // the behavior is undefined.
1893 // C++11 [dcl.fct]p7:
1894 // The effect of a cv-qualifier-seq in a function declarator is not the
1895 // same as adding cv-qualification on top of the function type. In the
1896 // latter case, the cv-qualifiers are ignored.
1897 if (Result->isFunctionType()) {
1899 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1900 S.getLangOpts().CPlusPlus
1901 ? diag::warn_typecheck_function_qualifiers_ignored
1902 : diag::warn_typecheck_function_qualifiers_unspecified);
1903 // No diagnostic for 'restrict' or '_Atomic' applied to a
1904 // function type; we'll diagnose those later, in BuildQualifiedType.
1905 }
1906
1907 // C++11 [dcl.ref]p1:
1908 // Cv-qualified references are ill-formed except when the
1909 // cv-qualifiers are introduced through the use of a typedef-name
1910 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1911 //
1912 // There don't appear to be any other contexts in which a cv-qualified
1913 // reference type could be formed, so the 'ill-formed' clause here appears
1914 // to never happen.
1915 if (TypeQuals && Result->isReferenceType()) {
1917 S, DS, TypeQuals, Result,
1919 diag::warn_typecheck_reference_qualifiers);
1920 }
1921
1922 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1923 // than once in the same specifier-list or qualifier-list, either directly
1924 // or via one or more typedefs."
1925 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1926 && TypeQuals & Result.getCVRQualifiers()) {
1927 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1928 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1929 << "const";
1930 }
1931
1932 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1933 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1934 << "volatile";
1935 }
1936
1937 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1938 // produce a warning in this case.
1939 }
1940
1941 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1942
1943 // If adding qualifiers fails, just use the unqualified type.
1944 if (Qualified.isNull())
1945 declarator.setInvalidType(true);
1946 else
1947 Result = Qualified;
1948 }
1949
1950 assert(!Result.isNull() && "This function should not return a null type");
1951 return Result;
1952}
1953
1954static std::string getPrintableNameForEntity(DeclarationName Entity) {
1955 if (Entity)
1956 return Entity.getAsString();
1957
1958 return "type name";
1959}
1960
1962 if (T->isDependentType())
1963 return true;
1964
1965 const auto *AT = dyn_cast<AutoType>(T);
1966 return AT && AT->isGNUAutoType();
1967}
1968
1970 Qualifiers Qs, const DeclSpec *DS) {
1971 if (T.isNull())
1972 return QualType();
1973
1974 // Ignore any attempt to form a cv-qualified reference.
1975 if (T->isReferenceType()) {
1976 Qs.removeConst();
1977 Qs.removeVolatile();
1978 }
1979
1980 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1981 // object or incomplete types shall not be restrict-qualified."
1982 if (Qs.hasRestrict()) {
1983 unsigned DiagID = 0;
1984 QualType ProblemTy;
1985
1986 if (T->isAnyPointerType() || T->isReferenceType() ||
1988 QualType EltTy;
1990 EltTy = T;
1991 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1992 EltTy = PTy->getPointeeType();
1993 else
1994 EltTy = T->getPointeeType();
1995
1996 // If we have a pointer or reference, the pointee must have an object
1997 // incomplete type.
1998 if (!EltTy->isIncompleteOrObjectType()) {
1999 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
2000 ProblemTy = EltTy;
2001 }
2002 } else if (!isDependentOrGNUAutoType(T)) {
2003 // For an __auto_type variable, we may not have seen the initializer yet
2004 // and so have no idea whether the underlying type is a pointer type or
2005 // not.
2006 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
2007 ProblemTy = T;
2008 }
2009
2010 if (DiagID) {
2011 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
2012 Qs.removeRestrict();
2013 }
2014 }
2015
2016 return Context.getQualifiedType(T, Qs);
2017}
2018
2020 unsigned CVRAU, const DeclSpec *DS) {
2021 if (T.isNull())
2022 return QualType();
2023
2024 // Ignore any attempt to form a cv-qualified reference.
2025 if (T->isReferenceType())
2026 CVRAU &=
2028
2029 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
2030 // TQ_unaligned;
2031 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
2032
2033 // C11 6.7.3/5:
2034 // If the same qualifier appears more than once in the same
2035 // specifier-qualifier-list, either directly or via one or more typedefs,
2036 // the behavior is the same as if it appeared only once.
2037 //
2038 // It's not specified what happens when the _Atomic qualifier is applied to
2039 // a type specified with the _Atomic specifier, but we assume that this
2040 // should be treated as if the _Atomic qualifier appeared multiple times.
2041 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
2042 // C11 6.7.3/5:
2043 // If other qualifiers appear along with the _Atomic qualifier in a
2044 // specifier-qualifier-list, the resulting type is the so-qualified
2045 // atomic type.
2046 //
2047 // Don't need to worry about array types here, since _Atomic can't be
2048 // applied to such types.
2049 SplitQualType Split = T.getSplitUnqualifiedType();
2050 T = BuildAtomicType(QualType(Split.Ty, 0),
2051 DS ? DS->getAtomicSpecLoc() : Loc);
2052 if (T.isNull())
2053 return T;
2054 Split.Quals.addCVRQualifiers(CVR);
2055 return BuildQualifiedType(T, Loc, Split.Quals);
2056 }
2057
2060 return BuildQualifiedType(T, Loc, Q, DS);
2061}
2062
2063/// Build a paren type including \p T.
2065 return Context.getParenType(T);
2066}
2067
2068/// Given that we're building a pointer or reference to the given
2070 SourceLocation loc,
2071 bool isReference) {
2072 // Bail out if retention is unrequired or already specified.
2073 if (!type->isObjCLifetimeType() ||
2074 type.getObjCLifetime() != Qualifiers::OCL_None)
2075 return type;
2076
2078
2079 // If the object type is const-qualified, we can safely use
2080 // __unsafe_unretained. This is safe (because there are no read
2081 // barriers), and it'll be safe to coerce anything but __weak* to
2082 // the resulting type.
2083 if (type.isConstQualified()) {
2084 implicitLifetime = Qualifiers::OCL_ExplicitNone;
2085
2086 // Otherwise, check whether the static type does not require
2087 // retaining. This currently only triggers for Class (possibly
2088 // protocol-qualifed, and arrays thereof).
2089 } else if (type->isObjCARCImplicitlyUnretainedType()) {
2090 implicitLifetime = Qualifiers::OCL_ExplicitNone;
2091
2092 // If we are in an unevaluated context, like sizeof, skip adding a
2093 // qualification.
2094 } else if (S.isUnevaluatedContext()) {
2095 return type;
2096
2097 // If that failed, give an error and recover using __strong. __strong
2098 // is the option most likely to prevent spurious second-order diagnostics,
2099 // like when binding a reference to a field.
2100 } else {
2101 // These types can show up in private ivars in system headers, so
2102 // we need this to not be an error in those cases. Instead we
2103 // want to delay.
2107 diag::err_arc_indirect_no_ownership, type, isReference));
2108 } else {
2109 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
2110 }
2111 implicitLifetime = Qualifiers::OCL_Strong;
2112 }
2113 assert(implicitLifetime && "didn't infer any lifetime!");
2114
2115 Qualifiers qs;
2116 qs.addObjCLifetime(implicitLifetime);
2117 return S.Context.getQualifiedType(type, qs);
2118}
2119
2120static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2121 std::string Quals = FnTy->getMethodQuals().getAsString();
2122
2123 switch (FnTy->getRefQualifier()) {
2124 case RQ_None:
2125 break;
2126
2127 case RQ_LValue:
2128 if (!Quals.empty())
2129 Quals += ' ';
2130 Quals += '&';
2131 break;
2132
2133 case RQ_RValue:
2134 if (!Quals.empty())
2135 Quals += ' ';
2136 Quals += "&&";
2137 break;
2138 }
2139
2140 return Quals;
2141}
2142
2143namespace {
2144/// Kinds of declarator that cannot contain a qualified function type.
2145///
2146/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2147/// a function type with a cv-qualifier or a ref-qualifier can only appear
2148/// at the topmost level of a type.
2149///
2150/// Parens and member pointers are permitted. We don't diagnose array and
2151/// function declarators, because they don't allow function types at all.
2152///
2153/// The values of this enum are used in diagnostics.
2154enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2155} // end anonymous namespace
2156
2157/// Check whether the type T is a qualified function type, and if it is,
2158/// diagnose that it cannot be contained within the given kind of declarator.
2160 QualifiedFunctionKind QFK) {
2161 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2162 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2163 if (!FPT ||
2164 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2165 return false;
2166
2167 S.Diag(Loc, diag::err_compound_qualified_function_type)
2168 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2170 return true;
2171}
2172
2174 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2175 if (!FPT ||
2176 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2177 return false;
2178
2179 Diag(Loc, diag::err_qualified_function_typeid)
2181 return true;
2182}
2183
2184// Helper to deduce addr space of a pointee type in OpenCL mode.
2186 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
2187 !PointeeType->isSamplerT() &&
2188 !PointeeType.hasAddressSpace())
2189 PointeeType = S.getASTContext().getAddrSpaceQualType(
2191 return PointeeType;
2192}
2193
2194/// Build a pointer type.
2195///
2196/// \param T The type to which we'll be building a pointer.
2197///
2198/// \param Loc The location of the entity whose type involves this
2199/// pointer type or, if there is no such entity, the location of the
2200/// type that will have pointer type.
2201///
2202/// \param Entity The name of the entity that involves the pointer
2203/// type, if known.
2204///
2205/// \returns A suitable pointer type, if there are no
2206/// errors. Otherwise, returns a NULL type.
2208 SourceLocation Loc, DeclarationName Entity) {
2209 if (T->isReferenceType()) {
2210 // C++ 8.3.2p4: There shall be no ... pointers to references ...
2211 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2212 << getPrintableNameForEntity(Entity) << T;
2213 return QualType();
2214 }
2215
2216 if (T->isFunctionType() && getLangOpts().OpenCL &&
2217 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2218 getLangOpts())) {
2219 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2220 return QualType();
2221 }
2222
2223 if (getLangOpts().HLSL && Loc.isValid()) {
2224 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2225 return QualType();
2226 }
2227
2228 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2229 return QualType();
2230
2231 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2232
2233 // In ARC, it is forbidden to build pointers to unqualified pointers.
2234 if (getLangOpts().ObjCAutoRefCount)
2235 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2236
2237 if (getLangOpts().OpenCL)
2239
2240 // In WebAssembly, pointers to reference types and pointers to tables are
2241 // illegal.
2242 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
2243 if (T.isWebAssemblyReferenceType()) {
2244 Diag(Loc, diag::err_wasm_reference_pr) << 0;
2245 return QualType();
2246 }
2247
2248 // We need to desugar the type here in case T is a ParenType.
2250 Diag(Loc, diag::err_wasm_table_pr) << 0;
2251 return QualType();
2252 }
2253 }
2254
2255 // Build the pointer type.
2256 return Context.getPointerType(T);
2257}
2258
2259/// Build a reference type.
2260///
2261/// \param T The type to which we'll be building a reference.
2262///
2263/// \param Loc The location of the entity whose type involves this
2264/// reference type or, if there is no such entity, the location of the
2265/// type that will have reference type.
2266///
2267/// \param Entity The name of the entity that involves the reference
2268/// type, if known.
2269///
2270/// \returns A suitable reference type, if there are no
2271/// errors. Otherwise, returns a NULL type.
2273 SourceLocation Loc,
2274 DeclarationName Entity) {
2276 "Unresolved overloaded function type");
2277
2278 // C++0x [dcl.ref]p6:
2279 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2280 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2281 // type T, an attempt to create the type "lvalue reference to cv TR" creates
2282 // the type "lvalue reference to T", while an attempt to create the type
2283 // "rvalue reference to cv TR" creates the type TR.
2284 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
2285
2286 // C++ [dcl.ref]p4: There shall be no references to references.
2287 //
2288 // According to C++ DR 106, references to references are only
2289 // diagnosed when they are written directly (e.g., "int & &"),
2290 // but not when they happen via a typedef:
2291 //
2292 // typedef int& intref;
2293 // typedef intref& intref2;
2294 //
2295 // Parser::ParseDeclaratorInternal diagnoses the case where
2296 // references are written directly; here, we handle the
2297 // collapsing of references-to-references as described in C++0x.
2298 // DR 106 and 540 introduce reference-collapsing into C++98/03.
2299
2300 // C++ [dcl.ref]p1:
2301 // A declarator that specifies the type "reference to cv void"
2302 // is ill-formed.
2303 if (T->isVoidType()) {
2304 Diag(Loc, diag::err_reference_to_void);
2305 return QualType();
2306 }
2307
2308 if (getLangOpts().HLSL && Loc.isValid()) {
2309 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
2310 return QualType();
2311 }
2312
2313 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2314 return QualType();
2315
2316 if (T->isFunctionType() && getLangOpts().OpenCL &&
2317 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2318 getLangOpts())) {
2319 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
2320 return QualType();
2321 }
2322
2323 // In ARC, it is forbidden to build references to unqualified pointers.
2324 if (getLangOpts().ObjCAutoRefCount)
2325 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2326
2327 if (getLangOpts().OpenCL)
2329
2330 // In WebAssembly, references to reference types and tables are illegal.
2331 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
2332 T.isWebAssemblyReferenceType()) {
2333 Diag(Loc, diag::err_wasm_reference_pr) << 1;
2334 return QualType();
2335 }
2336 if (T->isWebAssemblyTableType()) {
2337 Diag(Loc, diag::err_wasm_table_pr) << 1;
2338 return QualType();
2339 }
2340
2341 // Handle restrict on references.
2342 if (LValueRef)
2343 return Context.getLValueReferenceType(T, SpelledAsLValue);
2345}
2346
2347/// Build a Read-only Pipe type.
2348///
2349/// \param T The type to which we'll be building a Pipe.
2350///
2351/// \param Loc We do not use it for now.
2352///
2353/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2354/// NULL type.
2356 return Context.getReadPipeType(T);
2357}
2358
2359/// Build a Write-only Pipe type.
2360///
2361/// \param T The type to which we'll be building a Pipe.
2362///
2363/// \param Loc We do not use it for now.
2364///
2365/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2366/// NULL type.
2368 return Context.getWritePipeType(T);
2369}
2370
2371/// Build a bit-precise integer type.
2372///
2373/// \param IsUnsigned Boolean representing the signedness of the type.
2374///
2375/// \param BitWidth Size of this int type in bits, or an expression representing
2376/// that.
2377///
2378/// \param Loc Location of the keyword.
2379QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
2380 SourceLocation Loc) {
2381 if (BitWidth->isInstantiationDependent())
2382 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
2383
2384 llvm::APSInt Bits(32);
2385 ExprResult ICE =
2386 VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
2387
2388 if (ICE.isInvalid())
2389 return QualType();
2390
2391 size_t NumBits = Bits.getZExtValue();
2392 if (!IsUnsigned && NumBits < 2) {
2393 Diag(Loc, diag::err_bit_int_bad_size) << 0;
2394 return QualType();
2395 }
2396
2397 if (IsUnsigned && NumBits < 1) {
2398 Diag(Loc, diag::err_bit_int_bad_size) << 1;
2399 return QualType();
2400 }
2401
2402 const TargetInfo &TI = getASTContext().getTargetInfo();
2403 if (NumBits > TI.getMaxBitIntWidth()) {
2404 Diag(Loc, diag::err_bit_int_max_size)
2405 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2406 return QualType();
2407 }
2408
2409 return Context.getBitIntType(IsUnsigned, NumBits);
2410}
2411
2412/// Check whether the specified array bound can be evaluated using the relevant
2413/// language rules. If so, returns the possibly-converted expression and sets
2414/// SizeVal to the size. If not, but the expression might be a VLA bound,
2415/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2416/// ExprError().
2417static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2418 llvm::APSInt &SizeVal, unsigned VLADiag,
2419 bool VLAIsError) {
2420 if (S.getLangOpts().CPlusPlus14 &&
2421 (VLAIsError ||
2422 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2423 // C++14 [dcl.array]p1:
2424 // The constant-expression shall be a converted constant expression of
2425 // type std::size_t.
2426 //
2427 // Don't apply this rule if we might be forming a VLA: in that case, we
2428 // allow non-constant expressions and constant-folding. We only need to use
2429 // the converted constant expression rules (to properly convert the source)
2430 // when the source expression is of class type.
2432 ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
2433 }
2434
2435 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2436 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2437 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2438 public:
2439 unsigned VLADiag;
2440 bool VLAIsError;
2441 bool IsVLA = false;
2442
2443 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2444 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2445
2446 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2447 QualType T) override {
2448 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2449 }
2450
2451 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2452 SourceLocation Loc) override {
2453 IsVLA = !VLAIsError;
2454 return S.Diag(Loc, VLADiag);
2455 }
2456
2457 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2458 SourceLocation Loc) override {
2459 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2460 }
2461 } Diagnoser(VLADiag, VLAIsError);
2462
2463 ExprResult R =
2464 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2465 if (Diagnoser.IsVLA)
2466 return ExprResult();
2467 return R;
2468}
2469
2471 EltTy = Context.getBaseElementType(EltTy);
2472 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2473 EltTy->isUndeducedType())
2474 return true;
2475
2476 CharUnits Size = Context.getTypeSizeInChars(EltTy);
2477 CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2478
2479 if (Size.isMultipleOf(Alignment))
2480 return true;
2481
2482 Diag(Loc, diag::err_array_element_alignment)
2483 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2484 return false;
2485}
2486
2487/// Build an array type.
2488///
2489/// \param T The type of each element in the array.
2490///
2491/// \param ASM C99 array size modifier (e.g., '*', 'static').
2492///
2493/// \param ArraySize Expression describing the size of the array.
2494///
2495/// \param Brackets The range from the opening '[' to the closing ']'.
2496///
2497/// \param Entity The name of the entity that involves the array
2498/// type, if known.
2499///
2500/// \returns A suitable array type, if there are no errors. Otherwise,
2501/// returns a NULL type.
2503 Expr *ArraySize, unsigned Quals,
2504 SourceRange Brackets, DeclarationName Entity) {
2505
2506 SourceLocation Loc = Brackets.getBegin();
2507 if (getLangOpts().CPlusPlus) {
2508 // C++ [dcl.array]p1:
2509 // T is called the array element type; this type shall not be a reference
2510 // type, the (possibly cv-qualified) type void, a function type or an
2511 // abstract class type.
2512 //
2513 // C++ [dcl.array]p3:
2514 // When several "array of" specifications are adjacent, [...] only the
2515 // first of the constant expressions that specify the bounds of the arrays
2516 // may be omitted.
2517 //
2518 // Note: function types are handled in the common path with C.
2519 if (T->isReferenceType()) {
2520 Diag(Loc, diag::err_illegal_decl_array_of_references)
2521 << getPrintableNameForEntity(Entity) << T;
2522 return QualType();
2523 }
2524
2525 if (T->isVoidType() || T->isIncompleteArrayType()) {
2526 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2527 return QualType();
2528 }
2529
2530 if (RequireNonAbstractType(Brackets.getBegin(), T,
2531 diag::err_array_of_abstract_type))
2532 return QualType();
2533
2534 // Mentioning a member pointer type for an array type causes us to lock in
2535 // an inheritance model, even if it's inside an unused typedef.
2537 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2538 if (!MPTy->getClass()->isDependentType())
2539 (void)isCompleteType(Loc, T);
2540
2541 } else {
2542 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2543 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2544 if (!T.isWebAssemblyReferenceType() &&
2546 diag::err_array_incomplete_or_sizeless_type))
2547 return QualType();
2548 }
2549
2550 // Multi-dimensional arrays of WebAssembly references are not allowed.
2551 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2552 const auto *ATy = dyn_cast<ArrayType>(T);
2553 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2554 Diag(Loc, diag::err_wasm_reftype_multidimensional_array);
2555 return QualType();
2556 }
2557 }
2558
2559 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2560 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2561 return QualType();
2562 }
2563
2564 if (T->isFunctionType()) {
2565 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2566 << getPrintableNameForEntity(Entity) << T;
2567 return QualType();
2568 }
2569
2570 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2571 // If the element type is a struct or union that contains a variadic
2572 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2573 if (EltTy->getDecl()->hasFlexibleArrayMember())
2574 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2575 } else if (T->isObjCObjectType()) {
2576 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2577 return QualType();
2578 }
2579
2580 if (!checkArrayElementAlignment(T, Loc))
2581 return QualType();
2582
2583 // Do placeholder conversions on the array size expression.
2584 if (ArraySize && ArraySize->hasPlaceholderType()) {
2586 if (Result.isInvalid()) return QualType();
2587 ArraySize = Result.get();
2588 }
2589
2590 // Do lvalue-to-rvalue conversions on the array size expression.
2591 if (ArraySize && !ArraySize->isPRValue()) {
2593 if (Result.isInvalid())
2594 return QualType();
2595
2596 ArraySize = Result.get();
2597 }
2598
2599 // C99 6.7.5.2p1: The size expression shall have integer type.
2600 // C++11 allows contextual conversions to such types.
2601 if (!getLangOpts().CPlusPlus11 &&
2602 ArraySize && !ArraySize->isTypeDependent() &&
2604 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2605 << ArraySize->getType() << ArraySize->getSourceRange();
2606 return QualType();
2607 }
2608
2609 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2610 if (!ArraySize)
2611 return false;
2612
2613 // If the array size expression is a conditional expression whose branches
2614 // are both integer constant expressions, one negative and one positive,
2615 // then it's assumed to be like an old-style static assertion. e.g.,
2616 // int old_style_assert[expr ? 1 : -1];
2617 // We will accept any integer constant expressions instead of assuming the
2618 // values 1 and -1 are always used.
2619 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2620 ArraySize->IgnoreParenImpCasts())) {
2621 std::optional<llvm::APSInt> LHS =
2622 CondExpr->getLHS()->getIntegerConstantExpr(Context);
2623 std::optional<llvm::APSInt> RHS =
2624 CondExpr->getRHS()->getIntegerConstantExpr(Context);
2625 return LHS && RHS && LHS->isNegative() != RHS->isNegative();
2626 }
2627 return false;
2628 };
2629
2630 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2631 unsigned VLADiag;
2632 bool VLAIsError;
2633 if (getLangOpts().OpenCL) {
2634 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2635 VLADiag = diag::err_opencl_vla;
2636 VLAIsError = true;
2637 } else if (getLangOpts().C99) {
2638 VLADiag = diag::warn_vla_used;
2639 VLAIsError = false;
2640 } else if (isSFINAEContext()) {
2641 VLADiag = diag::err_vla_in_sfinae;
2642 VLAIsError = true;
2643 } else if (getLangOpts().OpenMP && isInOpenMPTaskUntiedContext()) {
2644 VLADiag = diag::err_openmp_vla_in_task_untied;
2645 VLAIsError = true;
2646 } else if (getLangOpts().CPlusPlus) {
2647 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context))
2648 VLADiag = getLangOpts().GNUMode
2649 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2650 : diag::ext_vla_cxx_static_assert;
2651 else
2652 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode
2653 : diag::ext_vla_cxx;
2654 VLAIsError = false;
2655 } else {
2656 VLADiag = diag::ext_vla;
2657 VLAIsError = false;
2658 }
2659
2660 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2661 if (!ArraySize) {
2662 if (ASM == ArraySizeModifier::Star) {
2663 Diag(Loc, VLADiag);
2664 if (VLAIsError)
2665 return QualType();
2666
2667 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2668 } else {
2669 T = Context.getIncompleteArrayType(T, ASM, Quals);
2670 }
2671 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2672 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2673 } else {
2674 ExprResult R =
2675 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2676 if (R.isInvalid())
2677 return QualType();
2678
2679 if (!R.isUsable()) {
2680 // C99: an array with a non-ICE size is a VLA. We accept any expression
2681 // that we can fold to a non-zero positive value as a non-VLA as an
2682 // extension.
2683 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2684 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2685 !T->isConstantSizeType()) {
2686 // C99: an array with an element type that has a non-constant-size is a
2687 // VLA.
2688 // FIXME: Add a note to explain why this isn't a VLA.
2689 Diag(Loc, VLADiag);
2690 if (VLAIsError)
2691 return QualType();
2692 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2693 } else {
2694 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2695 // have a value greater than zero.
2696 // In C++, this follows from narrowing conversions being disallowed.
2697 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2698 if (Entity)
2699 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2700 << getPrintableNameForEntity(Entity)
2701 << ArraySize->getSourceRange();
2702 else
2703 Diag(ArraySize->getBeginLoc(),
2704 diag::err_typecheck_negative_array_size)
2705 << ArraySize->getSourceRange();
2706 return QualType();
2707 }
2708 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2709 // GCC accepts zero sized static arrays. We allow them when
2710 // we're not in a SFINAE context.
2711 Diag(ArraySize->getBeginLoc(),
2712 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2713 : diag::ext_typecheck_zero_array_size)
2714 << 0 << ArraySize->getSourceRange();
2715 }
2716
2717 // Is the array too large?
2718 unsigned ActiveSizeBits =
2722 : ConstVal.getActiveBits();
2723 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2724 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2725 << toString(ConstVal, 10) << ArraySize->getSourceRange();
2726 return QualType();
2727 }
2728
2729 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2730 }
2731 }
2732
2733 if (T->isVariableArrayType()) {
2735 // CUDA device code and some other targets don't support VLAs.
2736 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2737 targetDiag(Loc,
2738 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2739 << (IsCUDADevice ? llvm::to_underlying(CUDA().CurrentTarget()) : 0);
2740 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2741 // VLAs are supported on this target, but we may need to do delayed
2742 // checking that the VLA is not being used within a coroutine.
2743 FSI->setHasVLA(Loc);
2744 }
2745 }
2746
2747 // If this is not C99, diagnose array size modifiers on non-VLAs.
2748 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2749 (ASM != ArraySizeModifier::Normal || Quals != 0)) {
2750 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2751 : diag::ext_c99_array_usage)
2752 << llvm::to_underlying(ASM);
2753 }
2754
2755 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2756 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2757 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2758 if (getLangOpts().OpenCL) {
2759 const QualType ArrType = Context.getBaseElementType(T);
2760 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2761 ArrType->isSamplerT() || ArrType->isImageType()) {
2762 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2763 return QualType();
2764 }
2765 }
2766
2767 return T;
2768}
2769
2771 SourceLocation AttrLoc) {
2772 // The base type must be integer (not Boolean or enumeration) or float, and
2773 // can't already be a vector.
2774 if ((!CurType->isDependentType() &&
2775 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2776 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2777 !CurType->isBitIntType()) ||
2778 CurType->isArrayType()) {
2779 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2780 return QualType();
2781 }
2782 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2783 if (const auto *BIT = CurType->getAs<BitIntType>()) {
2784 unsigned NumBits = BIT->getNumBits();
2785 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2786 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2787 << (NumBits < 8);
2788 return QualType();
2789 }
2790 }
2791
2792 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2793 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2795
2796 std::optional<llvm::APSInt> VecSize =
2798 if (!VecSize) {
2799 Diag(AttrLoc, diag::err_attribute_argument_type)
2800 << "vector_size" << AANT_ArgumentIntegerConstant
2801 << SizeExpr->getSourceRange();
2802 return QualType();
2803 }
2804
2805 if (CurType->isDependentType())
2806 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2808
2809 // vecSize is specified in bytes - convert to bits.
2810 if (!VecSize->isIntN(61)) {
2811 // Bit size will overflow uint64.
2812 Diag(AttrLoc, diag::err_attribute_size_too_large)
2813 << SizeExpr->getSourceRange() << "vector";
2814 return QualType();
2815 }
2816 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2817 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2818
2819 if (VectorSizeBits == 0) {
2820 Diag(AttrLoc, diag::err_attribute_zero_size)
2821 << SizeExpr->getSourceRange() << "vector";
2822 return QualType();
2823 }
2824
2825 if (!TypeSize || VectorSizeBits % TypeSize) {
2826 Diag(AttrLoc, diag::err_attribute_invalid_size)
2827 << SizeExpr->getSourceRange();
2828 return QualType();
2829 }
2830
2831 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2832 Diag(AttrLoc, diag::err_attribute_size_too_large)
2833 << SizeExpr->getSourceRange() << "vector";
2834 return QualType();
2835 }
2836
2837 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2839}
2840
2841/// Build an ext-vector type.
2842///
2843/// Run the required checks for the extended vector type.
2845 SourceLocation AttrLoc) {
2846 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2847 // in conjunction with complex types (pointers, arrays, functions, etc.).
2848 //
2849 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2850 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2851 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2852 // of bool aren't allowed.
2853 //
2854 // We explictly allow bool elements in ext_vector_type for C/C++.
2855 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2856 if ((!T->isDependentType() && !T->isIntegerType() &&
2857 !T->isRealFloatingType()) ||
2858 (IsNoBoolVecLang && T->isBooleanType())) {
2859 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2860 return QualType();
2861 }
2862
2863 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2864 if (T->isBitIntType()) {
2865 unsigned NumBits = T->castAs<BitIntType>()->getNumBits();
2866 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2867 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2868 << (NumBits < 8);
2869 return QualType();
2870 }
2871 }
2872
2873 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2874 std::optional<llvm::APSInt> vecSize =
2875 ArraySize->getIntegerConstantExpr(Context);
2876 if (!vecSize) {
2877 Diag(AttrLoc, diag::err_attribute_argument_type)
2878 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2879 << ArraySize->getSourceRange();
2880 return QualType();
2881 }
2882
2883 if (!vecSize->isIntN(32)) {
2884 Diag(AttrLoc, diag::err_attribute_size_too_large)
2885 << ArraySize->getSourceRange() << "vector";
2886 return QualType();
2887 }
2888 // Unlike gcc's vector_size attribute, the size is specified as the
2889 // number of elements, not the number of bytes.
2890 unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2891
2892 if (vectorSize == 0) {
2893 Diag(AttrLoc, diag::err_attribute_zero_size)
2894 << ArraySize->getSourceRange() << "vector";
2895 return QualType();
2896 }
2897
2898 return Context.getExtVectorType(T, vectorSize);
2899 }
2900
2901 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2902}
2903
2904QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2905 SourceLocation AttrLoc) {
2906 assert(Context.getLangOpts().MatrixTypes &&
2907 "Should never build a matrix type when it is disabled");
2908
2909 // Check element type, if it is not dependent.
2910 if (!ElementTy->isDependentType() &&
2911 !MatrixType::isValidElementType(ElementTy)) {
2912 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2913 return QualType();
2914 }
2915
2916 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2917 NumRows->isValueDependent() || NumCols->isValueDependent())
2918 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2919 AttrLoc);
2920
2921 std::optional<llvm::APSInt> ValueRows =
2923 std::optional<llvm::APSInt> ValueColumns =
2925
2926 auto const RowRange = NumRows->getSourceRange();
2927 auto const ColRange = NumCols->getSourceRange();
2928
2929 // Both are row and column expressions are invalid.
2930 if (!ValueRows && !ValueColumns) {
2931 Diag(AttrLoc, diag::err_attribute_argument_type)
2932 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2933 << ColRange;
2934 return QualType();
2935 }
2936
2937 // Only the row expression is invalid.
2938 if (!ValueRows) {
2939 Diag(AttrLoc, diag::err_attribute_argument_type)
2940 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2941 return QualType();
2942 }
2943
2944 // Only the column expression is invalid.
2945 if (!ValueColumns) {
2946 Diag(AttrLoc, diag::err_attribute_argument_type)
2947 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2948 return QualType();
2949 }
2950
2951 // Check the matrix dimensions.
2952 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2953 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2954 if (MatrixRows == 0 && MatrixColumns == 0) {
2955 Diag(AttrLoc, diag::err_attribute_zero_size)
2956 << "matrix" << RowRange << ColRange;
2957 return QualType();
2958 }
2959 if (MatrixRows == 0) {
2960 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2961 return QualType();
2962 }
2963 if (MatrixColumns == 0) {
2964 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2965 return QualType();
2966 }
2967 if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2968 Diag(AttrLoc, diag::err_attribute_size_too_large)
2969 << RowRange << "matrix row";
2970 return QualType();
2971 }
2972 if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2973 Diag(AttrLoc, diag::err_attribute_size_too_large)
2974 << ColRange << "matrix column";
2975 return QualType();
2976 }
2977 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2978}
2979
2981 if (T->isArrayType() || T->isFunctionType()) {
2982 Diag(Loc, diag::err_func_returning_array_function)
2983 << T->isFunctionType() << T;
2984 return true;
2985 }
2986
2987 // Functions cannot return half FP.
2988 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2990 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2992 return true;
2993 }
2994
2995 // Methods cannot return interface types. All ObjC objects are
2996 // passed by reference.
2997 if (T->isObjCObjectType()) {
2998 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2999 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
3000 return true;
3001 }
3002
3003 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
3004 T.hasNonTrivialToPrimitiveCopyCUnion())
3007
3008 // C++2a [dcl.fct]p12:
3009 // A volatile-qualified return type is deprecated
3010 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
3011 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
3012
3013 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
3014 return true;
3015 return false;
3016}
3017
3018/// Check the extended parameter information. Most of the necessary
3019/// checking should occur when applying the parameter attribute; the
3020/// only other checks required are positional restrictions.
3023 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
3024 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
3025
3026 bool emittedError = false;
3027 auto actualCC = EPI.ExtInfo.getCC();
3028 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
3029 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
3030 bool isCompatible =
3031 (required == RequiredCC::OnlySwift)
3032 ? (actualCC == CC_Swift)
3033 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
3034 if (isCompatible || emittedError)
3035 return;
3036 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
3038 << (required == RequiredCC::OnlySwift);
3039 emittedError = true;
3040 };
3041 for (size_t paramIndex = 0, numParams = paramTypes.size();
3042 paramIndex != numParams; ++paramIndex) {
3043 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
3044 // Nothing interesting to check for orindary-ABI parameters.
3046 continue;
3047
3048 // swift_indirect_result parameters must be a prefix of the function
3049 // arguments.
3051 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
3052 if (paramIndex != 0 &&
3053 EPI.ExtParameterInfos[paramIndex - 1].getABI()
3055 S.Diag(getParamLoc(paramIndex),
3056 diag::err_swift_indirect_result_not_first);
3057 }
3058 continue;
3059
3061 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
3062 continue;
3063
3064 // SwiftAsyncContext is not limited to swiftasynccall functions.
3066 continue;
3067
3068 // swift_error parameters must be preceded by a swift_context parameter.
3070 checkCompatible(paramIndex, RequiredCC::OnlySwift);
3071 if (paramIndex == 0 ||
3072 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
3074 S.Diag(getParamLoc(paramIndex),
3075 diag::err_swift_error_result_not_after_swift_context);
3076 }
3077 continue;
3078 }
3079 llvm_unreachable("bad ABI kind");
3080 }
3081}
3082
3084 MutableArrayRef<QualType> ParamTypes,
3085 SourceLocation Loc, DeclarationName Entity,
3087 bool Invalid = false;
3088
3090
3091 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
3092 // FIXME: Loc is too inprecise here, should use proper locations for args.
3093 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
3094 if (ParamType->isVoidType()) {
3095 Diag(Loc, diag::err_param_with_void_type);
3096 Invalid = true;
3097 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
3099 // Disallow half FP arguments.
3100 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
3102 Invalid = true;
3103 } else if (ParamType->isWebAssemblyTableType()) {
3104 Diag(Loc, diag::err_wasm_table_as_function_parameter);
3105 Invalid = true;
3106 }
3107
3108 // C++2a [dcl.fct]p4:
3109 // A parameter with volatile-qualified type is deprecated
3110 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
3111 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
3112
3113 ParamTypes[Idx] = ParamType;
3114 }
3115
3116 if (EPI.ExtParameterInfos) {
3117 checkExtParameterInfos(*this, ParamTypes, EPI,
3118 [=](unsigned i) { return Loc; });
3119 }
3120
3121 if (EPI.ExtInfo.getProducesResult()) {
3122 // This is just a warning, so we can't fail to build if we see it.
3124 }
3125
3126 if (Invalid)
3127 return QualType();
3128
3129 return Context.getFunctionType(T, ParamTypes, EPI);
3130}
3131
3132/// Build a member pointer type \c T Class::*.
3133///
3134/// \param T the type to which the member pointer refers.
3135/// \param Class the class type into which the member pointer points.
3136/// \param Loc the location where this type begins
3137/// \param Entity the name of the entity that will have this member pointer type
3138///
3139/// \returns a member pointer type, if successful, or a NULL type if there was
3140/// an error.
3142 SourceLocation Loc,
3143 DeclarationName Entity) {
3144 // Verify that we're not building a pointer to pointer to function with
3145 // exception specification.
3147 Diag(Loc, diag::err_distant_exception_spec);
3148 return QualType();
3149 }
3150
3151 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
3152 // with reference type, or "cv void."
3153 if (T->isReferenceType()) {
3154 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
3155 << getPrintableNameForEntity(Entity) << T;
3156 return QualType();
3157 }
3158
3159 if (T->isVoidType()) {
3160 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
3161 << getPrintableNameForEntity(Entity);
3162 return QualType();
3163 }
3164
3165 if (!Class->isDependentType() && !Class->isRecordType()) {
3166 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
3167 return QualType();
3168 }
3169
3170 if (T->isFunctionType() && getLangOpts().OpenCL &&
3171 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
3172 getLangOpts())) {
3173 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
3174 return QualType();
3175 }
3176
3177 if (getLangOpts().HLSL && Loc.isValid()) {
3178 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
3179 return QualType();
3180 }
3181
3182 // Adjust the default free function calling convention to the default method
3183 // calling convention.
3184 bool IsCtorOrDtor =
3187 if (T->isFunctionType())
3188 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
3189
3190 return Context.getMemberPointerType(T, Class.getTypePtr());
3191}
3192
3193/// Build a block pointer type.
3194///
3195/// \param T The type to which we'll be building a block pointer.
3196///
3197/// \param Loc The source location, used for diagnostics.
3198///
3199/// \param Entity The name of the entity that involves the block pointer
3200/// type, if known.
3201///
3202/// \returns A suitable block pointer type, if there are no
3203/// errors. Otherwise, returns a NULL type.
3205 SourceLocation Loc,
3206 DeclarationName Entity) {
3207 if (!T->isFunctionType()) {
3208 Diag(Loc, diag::err_nonfunction_block_type);
3209 return QualType();
3210 }
3211
3212 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
3213 return QualType();
3214
3215 if (getLangOpts().OpenCL)
3217
3219}
3220
3222 QualType QT = Ty.get();
3223 if (QT.isNull()) {
3224 if (TInfo) *TInfo = nullptr;
3225 return QualType();
3226 }
3227
3228 TypeSourceInfo *DI = nullptr;
3229 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
3230 QT = LIT->getType();
3231 DI = LIT->getTypeSourceInfo();
3232 }
3233
3234 if (TInfo) *TInfo = DI;
3235 return QT;
3236}
3237
3238static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3239 Qualifiers::ObjCLifetime ownership,
3240 unsigned chunkIndex);
3241
3242/// Given that this is the declaration of a parameter under ARC,
3243/// attempt to infer attributes and such for pointer-to-whatever
3244/// types.
3245static void inferARCWriteback(TypeProcessingState &state,
3246 QualType &declSpecType) {
3247 Sema &S = state.getSema();
3248 Declarator &declarator = state.getDeclarator();
3249
3250 // TODO: should we care about decl qualifiers?
3251
3252 // Check whether the declarator has the expected form. We walk
3253 // from the inside out in order to make the block logic work.
3254 unsigned outermostPointerIndex = 0;
3255 bool isBlockPointer = false;
3256 unsigned numPointers = 0;
3257 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
3258 unsigned chunkIndex = i;
3259 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
3260 switch (chunk.Kind) {
3262 // Ignore parens.
3263 break;
3264
3267 // Count the number of pointers. Treat references
3268 // interchangeably as pointers; if they're mis-ordered, normal
3269 // type building will discover that.
3270 outermostPointerIndex = chunkIndex;
3271 numPointers++;
3272 break;
3273
3275 // If we have a pointer to block pointer, that's an acceptable
3276 // indirect reference; anything else is not an application of
3277 // the rules.
3278 if (numPointers != 1) return;
3279 numPointers++;
3280 outermostPointerIndex = chunkIndex;
3281 isBlockPointer = true;
3282
3283 // We don't care about pointer structure in return values here.
3284 goto done;
3285
3286 case DeclaratorChunk::Array: // suppress if written (id[])?
3290 return;
3291 }
3292 }
3293 done:
3294
3295 // If we have *one* pointer, then we want to throw the qualifier on
3296 // the declaration-specifiers, which means that it needs to be a
3297 // retainable object type.
3298 if (numPointers == 1) {
3299 // If it's not a retainable object type, the rule doesn't apply.
3300 if (!declSpecType->isObjCRetainableType()) return;
3301
3302 // If it already has lifetime, don't do anything.
3303 if (declSpecType.getObjCLifetime()) return;
3304
3305 // Otherwise, modify the type in-place.
3306 Qualifiers qs;
3307
3308 if (declSpecType->isObjCARCImplicitlyUnretainedType())
3310 else
3312 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
3313
3314 // If we have *two* pointers, then we want to throw the qualifier on
3315 // the outermost pointer.
3316 } else if (numPointers == 2) {
3317 // If we don't have a block pointer, we need to check whether the
3318 // declaration-specifiers gave us something that will turn into a
3319 // retainable object pointer after we slap the first pointer on it.
3320 if (!isBlockPointer && !declSpecType->isObjCObjectType())
3321 return;
3322
3323 // Look for an explicit lifetime attribute there.
3324 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
3325 if (chunk.Kind != DeclaratorChunk::Pointer &&
3327 return;
3328 for (const ParsedAttr &AL : chunk.getAttrs())
3329 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
3330 return;
3331
3333 outermostPointerIndex);
3334
3335 // Any other number of pointers/references does not trigger the rule.
3336 } else return;
3337
3338 // TODO: mark whether we did this inference?
3339}
3340
3341void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3342 SourceLocation FallbackLoc,
3343 SourceLocation ConstQualLoc,
3344 SourceLocation VolatileQualLoc,
3345 SourceLocation RestrictQualLoc,
3346 SourceLocation AtomicQualLoc,
3347 SourceLocation UnalignedQualLoc) {
3348 if (!Quals)
3349 return;
3350
3351 struct Qual {
3352 const char *Name;
3353 unsigned Mask;
3354 SourceLocation Loc;
3355 } const QualKinds[5] = {
3356 { "const", DeclSpec::TQ_const, ConstQualLoc },
3357 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3358 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3359 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3360 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3361 };
3362
3363 SmallString<32> QualStr;
3364 unsigned NumQuals = 0;
3365 SourceLocation Loc;
3366 FixItHint FixIts[5];
3367
3368 // Build a string naming the redundant qualifiers.
3369 for (auto &E : QualKinds) {
3370 if (Quals & E.Mask) {
3371 if (!QualStr.empty()) QualStr += ' ';
3372 QualStr += E.Name;
3373
3374 // If we have a location for the qualifier, offer a fixit.
3375 SourceLocation QualLoc = E.Loc;
3376 if (QualLoc.isValid()) {
3377 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3378 if (Loc.isInvalid() ||
3379 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
3380 Loc = QualLoc;
3381 }
3382
3383 ++NumQuals;
3384 }
3385 }
3386
3387 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3388 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3389}
3390
3391// Diagnose pointless type qualifiers on the return type of a function.
3393 Declarator &D,
3394 unsigned FunctionChunkIndex) {
3396 D.getTypeObject(FunctionChunkIndex).Fun;
3397 if (FTI.hasTrailingReturnType()) {
3398 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3399 RetTy.getLocalCVRQualifiers(),
3401 return;
3402 }
3403
3404 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3405 End = D.getNumTypeObjects();
3406 OuterChunkIndex != End; ++OuterChunkIndex) {
3407 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3408 switch (OuterChunk.Kind) {
3410 continue;
3411
3413 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3415 diag::warn_qual_return_type,
3416 PTI.TypeQuals,
3418 PTI.ConstQualLoc,
3419 PTI.VolatileQualLoc,
3420 PTI.RestrictQualLoc,
3421 PTI.AtomicQualLoc,
3422 PTI.UnalignedQualLoc);
3423 return;
3424 }
3425
3432 // FIXME: We can't currently provide an accurate source location and a
3433 // fix-it hint for these.
3434 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3435 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3436 RetTy.getCVRQualifiers() | AtomicQual,
3437 D.getIdentifierLoc());
3438 return;
3439 }
3440
3441 llvm_unreachable("unknown declarator chunk kind");
3442 }
3443
3444 // If the qualifiers come from a conversion function type, don't diagnose
3445 // them -- they're not necessarily redundant, since such a conversion
3446 // operator can be explicitly called as "x.operator const int()".
3448 return;
3449
3450 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3451 // which are present there.
3452 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3454 D.getIdentifierLoc(),
3460}
3461
3462static std::pair<QualType, TypeSourceInfo *>
3463InventTemplateParameter(TypeProcessingState &state, QualType T,
3464 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3466 Sema &S = state.getSema();
3467 Declarator &D = state.getDeclarator();
3468
3469 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3470 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3471 const bool IsParameterPack = D.hasEllipsis();
3472
3473 // If auto is mentioned in a lambda parameter or abbreviated function
3474 // template context, convert it to a template parameter type.
3475
3476 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3477 // template parameter type. Template parameters are temporarily added
3478 // to the TU until the associated TemplateDecl is created.
3479 TemplateTypeParmDecl *InventedTemplateParam =
3482 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3483 /*NameLoc=*/D.getIdentifierLoc(),
3484 TemplateParameterDepth, AutoParameterPosition,
3486 D.getIdentifier(), AutoParameterPosition), false,
3487 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3488 InventedTemplateParam->setImplicit();
3489 Info.TemplateParams.push_back(InventedTemplateParam);
3490
3491 // Attach type constraints to the new parameter.
3492 if (Auto->isConstrained()) {
3493 if (TrailingTSI) {
3494 // The 'auto' appears in a trailing return type we've already built;
3495 // extract its type constraints to attach to the template parameter.
3496 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3497 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3498 bool Invalid = false;
3499 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3500 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3503 Invalid = true;
3504 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3505 }
3506
3507 if (!Invalid) {
3509 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3510 AutoLoc.getNamedConcept(), /*FoundDecl=*/AutoLoc.getFoundDecl(),
3511 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3512 InventedTemplateParam, D.getEllipsisLoc());
3513 }
3514 } else {
3515 // The 'auto' appears in the decl-specifiers; we've not finished forming
3516 // TypeSourceInfo for it yet.
3518 TemplateArgumentListInfo TemplateArgsInfo;
3519 bool Invalid = false;
3520 if (TemplateId->LAngleLoc.isValid()) {
3521 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3522 TemplateId->NumArgs);
3523 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3524
3525 if (D.getEllipsisLoc().isInvalid()) {
3526 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3529 Invalid = true;
3530 break;
3531 }
3532 }
3533 }
3534 }
3535 if (!Invalid) {
3536 UsingShadowDecl *USD =
3537 TemplateId->Template.get().getAsUsingShadowDecl();
3538 auto *CD =
3539 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
3543 TemplateId->TemplateNameLoc),
3544 CD,
3545 /*FoundDecl=*/
3546 USD ? cast<NamedDecl>(USD) : CD,
3547 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3548 InventedTemplateParam, D.getEllipsisLoc());
3549 }
3550 }
3551 }
3552
3553 // Replace the 'auto' in the function parameter with this invented
3554 // template type parameter.
3555 // FIXME: Retain some type sugar to indicate that this was written
3556 // as 'auto'?
3557 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3558 QualType NewT = state.ReplaceAutoType(T, Replacement);
3559 TypeSourceInfo *NewTSI =
3560 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3561 : nullptr;
3562 return {NewT, NewTSI};
3563}
3564
3565static TypeSourceInfo *
3566GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3567 QualType T, TypeSourceInfo *ReturnTypeInfo);
3568
3569static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3570 TypeSourceInfo *&ReturnTypeInfo) {
3571 Sema &SemaRef = state.getSema();
3572 Declarator &D = state.getDeclarator();
3573 QualType T;
3574 ReturnTypeInfo = nullptr;
3575
3576 // The TagDecl owned by the DeclSpec.
3577 TagDecl *OwnedTagDecl = nullptr;
3578
3579 switch (D.getName().getKind()) {
3585 T = ConvertDeclSpecToType(state);
3586
3587 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3588 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3589 // Owned declaration is embedded in declarator.
3590 OwnedTagDecl->setEmbeddedInDeclarator(true);
3591 }
3592 break;
3593
3597 // Constructors and destructors don't have return types. Use
3598 // "void" instead.
3599 T = SemaRef.Context.VoidTy;
3602 break;
3603
3605 // Deduction guides have a trailing return type and no type in their
3606 // decl-specifier sequence. Use a placeholder return type for now.
3607 T = SemaRef.Context.DependentTy;
3608 break;
3609
3611 // The result type of a conversion function is the type that it
3612 // converts to.
3614 &ReturnTypeInfo);
3615 break;
3616 }
3617
3618 // Note: We don't need to distribute declaration attributes (i.e.
3619 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3620 // and those don't get distributed.
3622 state, T, SemaRef.CUDA().IdentifyTarget(D.getAttributes()));
3623
3624 // Find the deduced type in this type. Look in the trailing return type if we
3625 // have one, otherwise in the DeclSpec type.
3626 // FIXME: The standard wording doesn't currently describe this.
3628 bool DeducedIsTrailingReturnType = false;
3629 if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3631 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3632 DeducedIsTrailingReturnType = true;
3633 }
3634
3635 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3636 if (Deduced) {
3637 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3638 int Error = -1;
3639
3640 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3641 // class template argument deduction)?
3642 bool IsCXXAutoType =
3643 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3644 bool IsDeducedReturnType = false;
3645
3646 switch (D.getContext()) {
3648 // Declared return type of a lambda-declarator is implicit and is always
3649 // 'auto'.
3650 break;
3653 Error = 0;
3654 break;
3656 Error = 22;
3657 break;
3660 InventedTemplateParameterInfo *Info = nullptr;
3662 // With concepts we allow 'auto' in function parameters.
3663 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3664 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3665 Error = 0;
3666 break;
3667 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3668 Error = 21;
3669 break;
3670 }
3671
3672 Info = &SemaRef.InventedParameterInfos.back();
3673 } else {
3674 // In C++14, generic lambdas allow 'auto' in their parameters.
3675 if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto ||
3676 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3677 Error = 16;
3678 break;
3679 }
3680 Info = SemaRef.getCurLambda();
3681 assert(Info && "No LambdaScopeInfo on the stack!");
3682 }
3683
3684 // We'll deal with inventing template parameters for 'auto' in trailing
3685 // return types when we pick up the trailing return type when processing
3686 // the function chunk.
3687 if (!DeducedIsTrailingReturnType)
3688 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3689 break;
3690 }
3694 break;
3695 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3696 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3697 Error = 6; // Interface member.
3698 } else {
3699 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3700 case TagTypeKind::Enum:
3701 llvm_unreachable("unhandled tag kind");
3703 Error = Cxx ? 1 : 2; /* Struct member */
3704 break;
3705 case TagTypeKind::Union:
3706 Error = Cxx ? 3 : 4; /* Union member */
3707 break;
3708 case TagTypeKind::Class:
3709 Error = 5; /* Class member */
3710 break;
3712 Error = 6; /* Interface member */
3713 break;
3714 }
3715 }
3717 Error = 20; // Friend type
3718 break;
3719 }
3722 Error = 7; // Exception declaration
3723 break;
3725 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3726 !SemaRef.getLangOpts().CPlusPlus20)
3727 Error = 19; // Template parameter (until C++20)
3728 else if (!SemaRef.getLangOpts().CPlusPlus17)
3729 Error = 8; // Template parameter (until C++17)
3730 break;
3732 Error = 9; // Block literal
3733 break;
3735 // Within a template argument list, a deduced template specialization
3736 // type will be reinterpreted as a template template argument.
3737 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3738 !D.getNumTypeObjects() &&
3740 break;
3741 [[fallthrough]];
3743 Error = 10; // Template type argument
3744 break;
3747 Error = 12; // Type alias
3748 break;
3751 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3752 Error = 13; // Function return type
3753 IsDeducedReturnType = true;
3754 break;
3756 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3757 Error = 14; // conversion-type-id
3758 IsDeducedReturnType = true;
3759 break;
3761 if (isa<DeducedTemplateSpecializationType>(Deduced))
3762 break;
3763 if (SemaRef.getLangOpts().CPlusPlus23 && IsCXXAutoType &&
3764 !Auto->isDecltypeAuto())
3765 break; // auto(x)
3766 [[fallthrough]];
3769 Error = 15; // Generic
3770 break;
3776 // FIXME: P0091R3 (erroneously) does not permit class template argument
3777 // deduction in conditions, for-init-statements, and other declarations
3778 // that are not simple-declarations.
3779 break;
3781 // FIXME: P0091R3 does not permit class template argument deduction here,
3782 // but we follow GCC and allow it anyway.
3783 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3784 Error = 17; // 'new' type
3785 break;
3787 Error = 18; // K&R function parameter
3788 break;
3789 }
3790
3792 Error = 11;
3793
3794 // In Objective-C it is an error to use 'auto' on a function declarator
3795 // (and everywhere for '__auto_type').
3796 if (D.isFunctionDeclarator() &&
3797 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3798 Error = 13;
3799
3800 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3802 AutoRange = D.getName().getSourceRange();
3803
3804 if (Error != -1) {
3805 unsigned Kind;
3806 if (Auto) {
3807 switch (Auto->getKeyword()) {
3808 case AutoTypeKeyword::Auto: Kind = 0; break;
3809 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3810 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3811 }
3812 } else {
3813 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3814 "unknown auto type");
3815 Kind = 3;
3816 }
3817
3818 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3819 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3820
3821 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3822 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3823 << QualType(Deduced, 0) << AutoRange;
3824 if (auto *TD = TN.getAsTemplateDecl())
3825 SemaRef.NoteTemplateLocation(*TD);
3826
3827 T = SemaRef.Context.IntTy;
3828 D.setInvalidType(true);
3829 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3830 // If there was a trailing return type, we already got
3831 // warn_cxx98_compat_trailing_return_type in the parser.
3832 SemaRef.Diag(AutoRange.getBegin(),
3834 ? diag::warn_cxx11_compat_generic_lambda
3835 : IsDeducedReturnType
3836 ? diag::warn_cxx11_compat_deduced_return_type
3837 : diag::warn_cxx98_compat_auto_type_specifier)
3838 << AutoRange;
3839 }
3840 }
3841
3842 if (SemaRef.getLangOpts().CPlusPlus &&
3843 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3844 // Check the contexts where C++ forbids the declaration of a new class
3845 // or enumeration in a type-specifier-seq.
3846 unsigned DiagID = 0;
3847 switch (D.getContext()) {
3850 // Class and enumeration definitions are syntactically not allowed in
3851 // trailing return types.
3852 llvm_unreachable("parser should not have allowed this");
3853 break;
3861 // C++11 [dcl.type]p3:
3862 // A type-specifier-seq shall not define a class or enumeration unless
3863 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3864 // the declaration of a template-declaration.
3866 break;
3868 DiagID = diag::err_type_defined_in_alias_template;
3869 break;
3880 DiagID = diag::err_type_defined_in_type_specifier;
3881 break;
3888 // C++ [dcl.fct]p6:
3889 // Types shall not be defined in return or parameter types.
3890 DiagID = diag::err_type_defined_in_param_type;
3891 break;
3893 // C++ 6.4p2:
3894 // The type-specifier-seq shall not contain typedef and shall not declare
3895 // a new class or enumeration.
3896 DiagID = diag::err_type_defined_in_condition;
3897 break;
3898 }
3899
3900 if (DiagID != 0) {
3901 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3902 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3903 D.setInvalidType(true);
3904 }
3905 }
3906
3907 assert(!T.isNull() && "This function should not return a null type");
3908 return T;
3909}
3910
3911/// Produce an appropriate diagnostic for an ambiguity between a function
3912/// declarator and a C++ direct-initializer.
3914 DeclaratorChunk &DeclType, QualType RT) {
3915 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3916 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3917
3918 // If the return type is void there is no ambiguity.
3919 if (RT->isVoidType())
3920 return;
3921
3922 // An initializer for a non-class type can have at most one argument.
3923 if (!RT->isRecordType() && FTI.NumParams > 1)
3924 return;
3925
3926 // An initializer for a reference must have exactly one argument.
3927 if (RT->isReferenceType() && FTI.NumParams != 1)
3928 return;
3929
3930 // Only warn if this declarator is declaring a function at block scope, and
3931 // doesn't have a storage class (such as 'extern') specified.
3932 if (!D.isFunctionDeclarator() ||
3936 return;
3937
3938 // Inside a condition, a direct initializer is not permitted. We allow one to
3939 // be parsed in order to give better diagnostics in condition parsing.
3941 return;
3942
3943 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3944
3945 S.Diag(DeclType.Loc,
3946 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3947 : diag::warn_empty_parens_are_function_decl)
3948 << ParenRange;
3949
3950 // If the declaration looks like:
3951 // T var1,
3952 // f();
3953 // and name lookup finds a function named 'f', then the ',' was
3954 // probably intended to be a ';'.
3955 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3956 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3958 if (Comma.getFileID() != Name.getFileID() ||
3959 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3962 if (S.LookupName(Result, S.getCurScope()))
3963 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3965 << D.getIdentifier();
3966 Result.suppressDiagnostics();
3967 }
3968 }
3969
3970 if (FTI.NumParams > 0) {
3971 // For a declaration with parameters, eg. "T var(T());", suggest adding
3972 // parens around the first parameter to turn the declaration into a
3973 // variable declaration.
3974 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3975 SourceLocation B = Range.getBegin();
3976 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3977 // FIXME: Maybe we should suggest adding braces instead of parens
3978 // in C++11 for classes that don't have an initializer_list constructor.
3979 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3981 << FixItHint::CreateInsertion(E, ")");
3982 } else {
3983 // For a declaration without parameters, eg. "T var();", suggest replacing
3984 // the parens with an initializer to turn the declaration into a variable
3985 // declaration.
3986 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3987
3988 // Empty parens mean value-initialization, and no parens mean
3989 // default initialization. These are equivalent if the default
3990 // constructor is user-provided or if zero-initialization is a
3991 // no-op.
3992 if (RD && RD->hasDefinition() &&
3994 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3995 << FixItHint::CreateRemoval(ParenRange);
3996 else {
3997 std::string Init =
3998 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3999 if (Init.empty() && S.LangOpts.CPlusPlus11)
4000 Init = "{}";
4001 if (!Init.empty())
4002 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
4003 << FixItHint::CreateReplacement(ParenRange, Init);
4004 }
4005 }
4006}
4007
4008/// Produce an appropriate diagnostic for a declarator with top-level
4009/// parentheses.
4012 assert(Paren.Kind == DeclaratorChunk::Paren &&
4013 "do not have redundant top-level parentheses");
4014
4015 // This is a syntactic check; we're not interested in cases that arise
4016 // during template instantiation.
4018 return;
4019
4020 // Check whether this could be intended to be a construction of a temporary
4021 // object in C++ via a function-style cast.
4022 bool CouldBeTemporaryObject =
4023 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
4024 !D.isInvalidType() && D.getIdentifier() &&
4026 (T->isRecordType() || T->isDependentType()) &&
4028
4029 bool StartsWithDeclaratorId = true;
4030 for (auto &C : D.type_objects()) {
4031 switch (C.Kind) {
4033 if (&C == &Paren)
4034 continue;
4035 [[fallthrough]];
4037 StartsWithDeclaratorId = false;
4038 continue;
4039
4041 if (!C.Arr.NumElts)
4042 CouldBeTemporaryObject = false;
4043 continue;
4044
4046 // FIXME: Suppress the warning here if there is no initializer; we're
4047 // going to give an error anyway.
4048 // We assume that something like 'T (&x) = y;' is highly likely to not
4049 // be intended to be a temporary object.
4050 CouldBeTemporaryObject = false;
4051 StartsWithDeclaratorId = false;
4052 continue;
4053
4055 // In a new-type-id, function chunks require parentheses.
4057 return;
4058 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
4059 // redundant-parens warning, but we don't know whether the function
4060 // chunk was syntactically valid as an expression here.
4061 CouldBeTemporaryObject = false;
4062 continue;
4063
4067 // These cannot appear in expressions.
4068 CouldBeTemporaryObject = false;
4069 StartsWithDeclaratorId = false;
4070 continue;
4071 }
4072 }
4073
4074 // FIXME: If there is an initializer, assume that this is not intended to be
4075 // a construction of a temporary object.
4076
4077 // Check whether the name has already been declared; if not, this is not a
4078 // function-style cast.
4079 if (CouldBeTemporaryObject) {
4082 if (!S.LookupName(Result, S.getCurScope()))
4083 CouldBeTemporaryObject = false;
4084 Result.suppressDiagnostics();
4085 }
4086
4087 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
4088
4089 if (!CouldBeTemporaryObject) {
4090 // If we have A (::B), the parentheses affect the meaning of the program.
4091 // Suppress the warning in that case. Don't bother looking at the DeclSpec
4092 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
4093 // formally unambiguous.
4094 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
4095 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
4096 NNS = NNS->getPrefix()) {
4097 if (NNS->getKind() == NestedNameSpecifier::Global)
4098 return;
4099 }
4100 }
4101
4102 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
4103 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
4105 return;
4106 }
4107
4108 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
4109 << ParenRange << D.getIdentifier();
4110 auto *RD = T->getAsCXXRecordDecl();
4111 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
4112 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
4113 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
4114 << D.getIdentifier();
4115 // FIXME: A cast to void is probably a better suggestion in cases where it's
4116 // valid (when there is no initializer and we're not in a condition).
4117 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
4120 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
4123}
4124
4125/// Helper for figuring out the default CC for a function declarator type. If
4126/// this is the outermost chunk, then we can determine the CC from the
4127/// declarator context. If not, then this could be either a member function
4128/// type or normal function type.
4130 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
4131 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
4132 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
4133
4134 // Check for an explicit CC attribute.
4135 for (const ParsedAttr &AL : AttrList) {
4136 switch (AL.getKind()) {
4138 // Ignore attributes that don't validate or can't apply to the
4139 // function type. We'll diagnose the failure to apply them in
4140 // handleFunctionTypeAttr.
4141 CallingConv CC;
4142 if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr,
4143 S.CUDA().IdentifyTarget(D.getAttributes())) &&
4144 (!FTI.isVariadic || supportsVariadicCall(CC))) {
4145 return CC;
4146 }
4147 break;
4148 }
4149
4150 default:
4151 break;
4152 }
4153 }
4154
4155 bool IsCXXInstanceMethod = false;
4156
4157 if (S.getLangOpts().CPlusPlus) {
4158 // Look inwards through parentheses to see if this chunk will form a
4159 // member pointer type or if we're the declarator. Any type attributes
4160 // between here and there will override the CC we choose here.
4161 unsigned I = ChunkIndex;
4162 bool FoundNonParen = false;
4163 while (I && !FoundNonParen) {
4164 --I;
4166 FoundNonParen = true;
4167 }
4168
4169 if (FoundNonParen) {
4170 // If we're not the declarator, we're a regular function type unless we're
4171 // in a member pointer.
4172 IsCXXInstanceMethod =
4174 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
4175 // This can only be a call operator for a lambda, which is an instance
4176 // method, unless explicitly specified as 'static'.
4177 IsCXXInstanceMethod =
4179 } else {
4180 // We're the innermost decl chunk, so must be a function declarator.
4181 assert(D.isFunctionDeclarator());
4182
4183 // If we're inside a record, we're declaring a method, but it could be
4184 // explicitly or implicitly static.
4185 IsCXXInstanceMethod =
4188 !D.isStaticMember();
4189 }
4190 }
4191
4193 IsCXXInstanceMethod);
4194
4195 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
4196 // and AMDGPU targets, hence it cannot be treated as a calling
4197 // convention attribute. This is the simplest place to infer
4198 // calling convention for OpenCL kernels.
4199 if (S.getLangOpts().OpenCL) {
4200 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4201 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
4202 CC = CC_OpenCLKernel;
4203 break;
4204 }
4205 }
4206 } else if (S.getLangOpts().CUDA) {
4207 // If we're compiling CUDA/HIP code and targeting SPIR-V we need to make
4208 // sure the kernels will be marked with the right calling convention so that
4209 // they will be visible by the APIs that ingest SPIR-V.
4210 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
4211 if (Triple.getArch() == llvm::Triple::spirv32 ||
4212 Triple.getArch() == llvm::Triple::spirv64) {
4213 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4214 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
4215 CC = CC_OpenCLKernel;
4216 break;
4217 }
4218 }
4219 }
4220 }
4221
4222 return CC;
4223}
4224
4225namespace {
4226 /// A simple notion of pointer kinds, which matches up with the various
4227 /// pointer declarators.
4228 enum class SimplePointerKind {
4229 Pointer,
4230 BlockPointer,
4231 MemberPointer,
4232 Array,
4233 };
4234} // end anonymous namespace
4235
4237 switch (nullability) {
4239 if (!Ident__Nonnull)
4240 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
4241 return Ident__Nonnull;
4242
4244 if (!Ident__Nullable)
4245 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
4246 return Ident__Nullable;
4247
4249 if (!Ident__Nullable_result)
4250 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
4251 return Ident__Nullable_result;
4252
4254 if (!Ident__Null_unspecified)
4255 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
4256 return Ident__Null_unspecified;
4257 }
4258 llvm_unreachable("Unknown nullability kind.");
4259}
4260
4261/// Retrieve the identifier "NSError".
4263 if (!Ident_NSError)
4264 Ident_NSError = PP.getIdentifierInfo("NSError");
4265
4266 return Ident_NSError;
4267}
4268
4269/// Check whether there is a nullability attribute of any kind in the given
4270/// attribute list.
4271static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
4272 for (const ParsedAttr &AL : attrs) {
4273 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
4274 AL.getKind() == ParsedAttr::AT_TypeNullable ||
4275 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
4276 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
4277 return true;
4278 }
4279
4280 return false;
4281}
4282
4283namespace {
4284 /// Describes the kind of a pointer a declarator describes.
4285 enum class PointerDeclaratorKind {
4286 // Not a pointer.
4287 NonPointer,
4288 // Single-level pointer.
4289 SingleLevelPointer,
4290 // Multi-level pointer (of any pointer kind).
4291 MultiLevelPointer,
4292 // CFFooRef*
4293 MaybePointerToCFRef,
4294 // CFErrorRef*
4295 CFErrorRefPointer,
4296 // NSError**
4297 NSErrorPointerPointer,
4298 };
4299
4300 /// Describes a declarator chunk wrapping a pointer that marks inference as
4301 /// unexpected.
4302 // These values must be kept in sync with diagnostics.
4303 enum class PointerWrappingDeclaratorKind {
4304 /// Pointer is top-level.
4305 None = -1,
4306 /// Pointer is an array element.
4307 Array = 0,
4308 /// Pointer is the referent type of a C++ reference.
4309 Reference = 1
4310 };
4311} // end anonymous namespace
4312
4313/// Classify the given declarator, whose type-specified is \c type, based on
4314/// what kind of pointer it refers to.
4315///
4316/// This is used to determine the default nullability.
4317static PointerDeclaratorKind
4319 PointerWrappingDeclaratorKind &wrappingKind) {
4320 unsigned numNormalPointers = 0;
4321
4322 // For any dependent type, we consider it a non-pointer.
4323 if (type->isDependentType())
4324 return PointerDeclaratorKind::NonPointer;
4325
4326 // Look through the declarator chunks to identify pointers.
4327 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
4328 DeclaratorChunk &chunk = declarator.getTypeObject(i);
4329 switch (chunk.Kind) {
4331 if (numNormalPointers == 0)
4332 wrappingKind = PointerWrappingDeclaratorKind::Array;
4333 break;
4334
4337 break;
4338
4341 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4342 : PointerDeclaratorKind::SingleLevelPointer;
4343
4345 break;
4346
4348 if (numNormalPointers == 0)
4349 wrappingKind = PointerWrappingDeclaratorKind::Reference;
4350 break;
4351
4353 ++numNormalPointers;
4354 if (numNormalPointers > 2)
4355 return PointerDeclaratorKind::MultiLevelPointer;
4356 break;
4357 }
4358 }
4359
4360 // Then, dig into the type specifier itself.
4361 unsigned numTypeSpecifierPointers = 0;
4362 do {
4363 // Decompose normal pointers.
4364 if (auto ptrType = type->getAs<PointerType>()) {
4365 ++numNormalPointers;
4366
4367 if (numNormalPointers > 2)
4368 return PointerDeclaratorKind::MultiLevelPointer;
4369
4370 type = ptrType->getPointeeType();
4371 ++numTypeSpecifierPointers;
4372 continue;
4373 }
4374
4375 // Decompose block pointers.
4376 if (type->getAs<BlockPointerType>()) {
4377 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4378 : PointerDeclaratorKind::SingleLevelPointer;
4379 }
4380
4381 // Decompose member pointers.
4382 if (type->getAs<MemberPointerType>()) {
4383 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4384 : PointerDeclaratorKind::SingleLevelPointer;
4385 }
4386
4387 // Look at Objective-C object pointers.
4388 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4389 ++numNormalPointers;
4390 ++numTypeSpecifierPointers;
4391
4392 // If this is NSError**, report that.
4393 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4394 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
4395 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4396 return PointerDeclaratorKind::NSErrorPointerPointer;
4397 }
4398 }
4399
4400 break;
4401 }
4402
4403 // Look at Objective-C class types.
4404 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4405 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
4406 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4407 return PointerDeclaratorKind::NSErrorPointerPointer;
4408 }
4409
4410 break;
4411 }
4412
4413 // If at this point we haven't seen a pointer, we won't see one.
4414 if (numNormalPointers == 0)
4415 return PointerDeclaratorKind::NonPointer;
4416
4417 if (auto recordType = type->getAs<RecordType>()) {
4418 RecordDecl *recordDecl = recordType->getDecl();
4419
4420 // If this is CFErrorRef*, report it as such.
4421 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4422 S.isCFError(recordDecl)) {
4423 return PointerDeclaratorKind::CFErrorRefPointer;
4424 }
4425 break;
4426 }
4427
4428 break;
4429 } while (true);
4430
4431 switch (numNormalPointers) {
4432 case 0:
4433 return PointerDeclaratorKind::NonPointer;
4434
4435 case 1:
4436 return PointerDeclaratorKind::SingleLevelPointer;
4437
4438 case 2:
4439 return PointerDeclaratorKind::MaybePointerToCFRef;
4440
4441 default:
4442 return PointerDeclaratorKind::MultiLevelPointer;
4443 }
4444}
4445
4447 // If we already know about CFError, test it directly.
4448 if (CFError)
4449 return CFError == RD;
4450
4451 // Check whether this is CFError, which we identify based on its bridge to
4452 // NSError. CFErrorRef used to be declared with "objc_bridge" but is now
4453 // declared with "objc_bridge_mutable", so look for either one of the two
4454 // attributes.
4455 if (RD->getTagKind() == TagTypeKind::Struct) {
4456 IdentifierInfo *bridgedType = nullptr;
4457 if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
4458 bridgedType = bridgeAttr->getBridgedType();
4459 else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
4460 bridgedType = bridgeAttr->getBridgedType();
4461
4462 if (bridgedType == getNSErrorIdent()) {
4463 CFError = RD;
4464 return true;
4465 }
4466 }
4467
4468 return false;
4469}
4470
4472 SourceLocation loc) {
4473 // If we're anywhere in a function, method, or closure context, don't perform
4474 // completeness checks.
4475 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4476 if (ctx->isFunctionOrMethod())
4477 return FileID();
4478
4479 if (ctx->isFileContext())
4480 break;
4481 }
4482
4483 // We only care about the expansion location.
4484 loc = S.SourceMgr.getExpansionLoc(loc);
4485 FileID file = S.SourceMgr.getFileID(loc);
4486 if (file.isInvalid())
4487 return FileID();
4488
4489 // Retrieve file information.
4490 bool invalid = false;
4491 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4492 if (invalid || !sloc.isFile())
4493 return FileID();
4494
4495 // We don't want to perform completeness checks on the main file or in
4496 // system headers.
4497 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4498 if (fileInfo.getIncludeLoc().isInvalid())
4499 return FileID();
4500 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4502 return FileID();
4503 }
4504
4505 return file;
4506}
4507
4508/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4509/// taking into account whitespace before and after.
4510template <typename DiagBuilderT>
4511static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4512 SourceLocation PointerLoc,
4513 NullabilityKind Nullability) {
4514 assert(PointerLoc.isValid());
4515 if (PointerLoc.isMacroID())
4516 return;
4517
4518 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4519 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4520 return;
4521
4522 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4523 if (!NextChar)
4524 return;
4525
4526 SmallString<32> InsertionTextBuf{" "};
4527 InsertionTextBuf += getNullabilitySpelling(Nullability);
4528 InsertionTextBuf += " ";
4529 StringRef InsertionText = InsertionTextBuf.str();
4530
4531 if (isWhitespace(*NextChar)) {
4532 InsertionText = InsertionText.drop_back();
4533 } else if (NextChar[-1] == '[') {
4534 if (NextChar[0] == ']')
4535 InsertionText = InsertionText.drop_back().drop_front();
4536 else
4537 InsertionText = InsertionText.drop_front();
4538 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4539 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4540 InsertionText = InsertionText.drop_back().drop_front();
4541 }
4542
4543 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4544}
4545
4547 SimplePointerKind PointerKind,
4548 SourceLocation PointerLoc,
4549 SourceLocation PointerEndLoc) {
4550 assert(PointerLoc.isValid());
4551
4552 if (PointerKind == SimplePointerKind::Array) {
4553 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4554 } else {
4555 S.Diag(PointerLoc, diag::warn_nullability_missing)
4556 << static_cast<unsigned>(PointerKind);
4557 }
4558
4559 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4560 if (FixItLoc.isMacroID())
4561 return;
4562
4563 auto addFixIt = [&](NullabilityKind Nullability) {
4564 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4565 Diag << static_cast<unsigned>(Nullability);
4566 Diag << static_cast<unsigned>(PointerKind);
4567 fixItNullability(S, Diag, FixItLoc, Nullability);
4568 };
4569 addFixIt(NullabilityKind::Nullable);
4570 addFixIt(NullabilityKind::NonNull);
4571}
4572
4573/// Complains about missing nullability if the file containing \p pointerLoc
4574/// has other uses of nullability (either the keywords or the \c assume_nonnull
4575/// pragma).
4576///
4577/// If the file has \e not seen other uses of nullability, this particular
4578/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4579static void
4580checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4581 SourceLocation pointerLoc,
4582 SourceLocation pointerEndLoc = SourceLocation()) {
4583 // Determine which file we're performing consistency checking for.
4584 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4585 if (file.isInvalid())
4586 return;
4587
4588 // If we haven't seen any type nullability in this file, we won't warn now
4589 // about anything.
4590 FileNullability &fileNullability = S.NullabilityMap[file];
4591 if (!fileNullability.SawTypeNullability) {
4592 // If this is the first pointer declarator in the file, and the appropriate
4593 // warning is on, record it in case we need to diagnose it retroactively.
4594 diag::kind diagKind;
4595 if (pointerKind == SimplePointerKind::Array)
4596 diagKind = diag::warn_nullability_missing_array;
4597 else
4598 diagKind = diag::warn_nullability_missing;
4599
4600 if (fileNullability.PointerLoc.isInvalid() &&
4601 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4602 fileNullability.PointerLoc = pointerLoc;
4603 fileNullability.PointerEndLoc = pointerEndLoc;
4604 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4605 }
4606
4607 return;
4608 }
4609
4610 // Complain about missing nullability.
4611 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4612}
4613
4614/// Marks that a nullability feature has been used in the file containing
4615/// \p loc.
4616///
4617/// If this file already had pointer types in it that were missing nullability,
4618/// the first such instance is retroactively diagnosed.
4619///
4620/// \sa checkNullabilityConsistency
4623 if (file.isInvalid())
4624 return;
4625
4626 FileNullability &fileNullability = S.NullabilityMap[file];
4627 if (fileNullability.SawTypeNullability)
4628 return;
4629 fileNullability.SawTypeNullability = true;
4630
4631 // If we haven't seen any type nullability before, now we have. Retroactively
4632 // diagnose the first unannotated pointer, if there was one.
4633 if (fileNullability.PointerLoc.isInvalid())
4634 return;
4635
4636 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4637 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4638 fileNullability.PointerEndLoc);
4639}
4640
4641/// Returns true if any of the declarator chunks before \p endIndex include a
4642/// level of indirection: array, pointer, reference, or pointer-to-member.
4643///
4644/// Because declarator chunks are stored in outer-to-inner order, testing
4645/// every chunk before \p endIndex is testing all chunks that embed the current
4646/// chunk as part of their type.
4647///
4648/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4649/// end index, in which case all chunks are tested.
4650static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4651 unsigned i = endIndex;
4652 while (i != 0) {
4653 // Walk outwards along the declarator chunks.
4654 --i;
4655 const DeclaratorChunk &DC = D.getTypeObject(i);
4656 switch (DC.Kind) {
4658 break;
4663 return true;
4667 // These are invalid anyway, so just ignore.
4668 break;
4669 }
4670 }
4671 return false;
4672}
4673
4674static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4675 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4676 Chunk.Kind == DeclaratorChunk::Array);
4677}
4678
4679template<typename AttrT>
4680static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4681 AL.setUsedAsTypeAttr();
4682 return ::new (Ctx) AttrT(Ctx, AL);
4683}
4684
4686 NullabilityKind NK) {
4687 switch (NK) {
4689 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4690
4692 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4693
4695 return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4696
4698 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4699 }
4700 llvm_unreachable("unknown NullabilityKind");
4701}
4702
4703// Diagnose whether this is a case with the multiple addr spaces.
4704// Returns true if this is an invalid case.
4705// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4706// by qualifiers for two or more different address spaces."
4708 LangAS ASNew,
4709 SourceLocation AttrLoc) {
4710 if (ASOld != LangAS::Default) {
4711 if (ASOld != ASNew) {
4712 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4713 return true;
4714 }
4715 // Emit a warning if they are identical; it's likely unintended.
4716 S.Diag(AttrLoc,
4717 diag::warn_attribute_address_multiple_identical_qualifiers);
4718 }
4719 return false;
4720}
4721
4722// Whether this is a type broadly expected to have nullability attached.
4723// These types are affected by `#pragma assume_nonnull`, and missing nullability
4724// will be diagnosed with -Wnullability-completeness.
4726 return T->canHaveNullability(/*ResultIfUnknown=*/false) &&
4727 // For now, do not infer/require nullability on C++ smart pointers.
4728 // It's unclear whether the pragma's behavior is useful for C++.
4729 // e.g. treating type-aliases and template-type-parameters differently
4730 // from types of declarations can be surprising.
4731 !isa<RecordType>(T->getCanonicalTypeInternal());
4732}
4733
4734static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4735 QualType declSpecType,
4736 TypeSourceInfo *TInfo) {
4737 // The TypeSourceInfo that this function returns will not be a null type.
4738 // If there is an error, this function will fill in a dummy type as fallback.
4739 QualType T = declSpecType;
4740 Declarator &D = state.getDeclarator();
4741 Sema &S = state.getSema();
4742 ASTContext &Context = S.Context;
4743 const LangOptions &LangOpts = S.getLangOpts();
4744
4745 // The name we're declaring, if any.
4746 DeclarationName Name;
4747 if (D.getIdentifier())
4748 Name = D.getIdentifier();
4749
4750 // Does this declaration declare a typedef-name?
4751 bool IsTypedefName =
4755
4756 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4757 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4758 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4759 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4760
4761 // If T is 'decltype(auto)', the only declarators we can have are parens
4762 // and at most one function declarator if this is a function declaration.
4763 // If T is a deduced class template specialization type, we can have no
4764 // declarator chunks at all.
4765 if (auto *DT = T->getAs<DeducedType>()) {
4766 const AutoType *AT = T->getAs<AutoType>();
4767 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4768 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4769 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4770 unsigned Index = E - I - 1;
4771 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4772 unsigned DiagId = IsClassTemplateDeduction
4773 ? diag::err_deduced_class_template_compound_type
4774 : diag::err_decltype_auto_compound_type;
4775 unsigned DiagKind = 0;
4776 switch (DeclChunk.Kind) {
4778 // FIXME: Rejecting this is a little silly.
4779 if (IsClassTemplateDeduction) {
4780 DiagKind = 4;
4781 break;
4782 }
4783 continue;
4785 if (IsClassTemplateDeduction) {
4786 DiagKind = 3;
4787 break;
4788 }
4789 unsigned FnIndex;
4791 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4792 continue;
4793 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4794 break;
4795 }
4799 DiagKind = 0;
4800 break;
4802 DiagKind = 1;
4803 break;
4805 DiagKind = 2;
4806 break;
4808 break;
4809 }
4810
4811 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4812 D.setInvalidType(true);
4813 break;
4814 }
4815 }
4816 }
4817
4818 // Determine whether we should infer _Nonnull on pointer types.
4819 std::optional<NullabilityKind> inferNullability;
4820 bool inferNullabilityCS = false;
4821 bool inferNullabilityInnerOnly = false;
4822 bool inferNullabilityInnerOnlyComplete = false;
4823
4824 // Are we in an assume-nonnull region?
4825 bool inAssumeNonNullRegion = false;
4826 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4827 if (assumeNonNullLoc.isValid()) {
4828 inAssumeNonNullRegion = true;
4829 recordNullabilitySeen(S, assumeNonNullLoc);
4830 }
4831
4832 // Whether to complain about missing nullability specifiers or not.
4833 enum {
4834 /// Never complain.
4835 CAMN_No,
4836 /// Complain on the inner pointers (but not the outermost
4837 /// pointer).
4838 CAMN_InnerPointers,
4839 /// Complain about any pointers that don't have nullability
4840 /// specified or inferred.
4841 CAMN_Yes
4842 } complainAboutMissingNullability = CAMN_No;
4843 unsigned NumPointersRemaining = 0;
4844 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4845
4846 if (IsTypedefName) {
4847 // For typedefs, we do not infer any nullability (the default),
4848 // and we only complain about missing nullability specifiers on
4849 // inner pointers.
4850 complainAboutMissingNullability = CAMN_InnerPointers;
4851
4853 // Note that we allow but don't require nullability on dependent types.
4854 ++NumPointersRemaining;
4855 }
4856
4857 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4858 DeclaratorChunk &chunk = D.getTypeObject(i);
4859 switch (chunk.Kind) {