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