1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements type-related semantic analysis.
11 //===----------------------------------------------------------------------===//
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/ASTStructuralEquivalence.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/TypeLoc.h"
23 #include "clang/AST/TypeLocVisitor.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/DeclSpec.h"
28 #include "clang/Sema/DelayedDiagnostic.h"
29 #include "clang/Sema/Lookup.h"
30 #include "clang/Sema/ParsedTemplate.h"
31 #include "clang/Sema/ScopeInfo.h"
32 #include "clang/Sema/SemaInternal.h"
33 #include "clang/Sema/Template.h"
34 #include "clang/Sema/TemplateInstCallback.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/Support/ErrorHandling.h"
41 using namespace clang;
43 enum TypeDiagSelector {
49 /// isOmittedBlockReturnType - Return true if this declarator is missing a
50 /// return type because this is a omitted return type on a block literal.
51 static bool isOmittedBlockReturnType(const Declarator &D) {
52 if (D.getContext() != DeclaratorContext::BlockLiteralContext ||
53 D.getDeclSpec().hasTypeSpecifier())
56 if (D.getNumTypeObjects() == 0)
57 return true; // ^{ ... }
59 if (D.getNumTypeObjects() == 1 &&
60 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
61 return true; // ^(int X, float Y) { ... }
66 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
67 /// doesn't apply to the given type.
68 static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
70 TypeDiagSelector WhichType;
71 bool useExpansionLoc = true;
72 switch (attr.getKind()) {
73 case ParsedAttr::AT_ObjCGC:
74 WhichType = TDS_Pointer;
76 case ParsedAttr::AT_ObjCOwnership:
77 WhichType = TDS_ObjCObjOrBlock;
80 // Assume everything else was a function attribute.
81 WhichType = TDS_Function;
82 useExpansionLoc = false;
86 SourceLocation loc = attr.getLoc();
87 StringRef name = attr.getAttrName()->getName();
89 // The GC attributes are usually written with macros; special-case them.
90 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
92 if (useExpansionLoc && loc.isMacroID() && II) {
93 if (II->isStr("strong")) {
94 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
95 } else if (II->isStr("weak")) {
96 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
100 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
104 // objc_gc applies to Objective-C pointers or, otherwise, to the
105 // smallest available pointer type (i.e. 'void*' in 'void**').
106 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
107 case ParsedAttr::AT_ObjCGC: \
108 case ParsedAttr::AT_ObjCOwnership
110 // Calling convention attributes.
111 #define CALLING_CONV_ATTRS_CASELIST \
112 case ParsedAttr::AT_CDecl: \
113 case ParsedAttr::AT_FastCall: \
114 case ParsedAttr::AT_StdCall: \
115 case ParsedAttr::AT_ThisCall: \
116 case ParsedAttr::AT_RegCall: \
117 case ParsedAttr::AT_Pascal: \
118 case ParsedAttr::AT_SwiftCall: \
119 case ParsedAttr::AT_VectorCall: \
120 case ParsedAttr::AT_AArch64VectorPcs: \
121 case ParsedAttr::AT_MSABI: \
122 case ParsedAttr::AT_SysVABI: \
123 case ParsedAttr::AT_Pcs: \
124 case ParsedAttr::AT_IntelOclBicc: \
125 case ParsedAttr::AT_PreserveMost: \
126 case ParsedAttr::AT_PreserveAll
128 // Function type attributes.
129 #define FUNCTION_TYPE_ATTRS_CASELIST \
130 case ParsedAttr::AT_NSReturnsRetained: \
131 case ParsedAttr::AT_NoReturn: \
132 case ParsedAttr::AT_Regparm: \
133 case ParsedAttr::AT_CmseNSCall: \
134 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
135 case ParsedAttr::AT_AnyX86NoCfCheck: \
136 CALLING_CONV_ATTRS_CASELIST
138 // Microsoft-specific type qualifiers.
139 #define MS_TYPE_ATTRS_CASELIST \
140 case ParsedAttr::AT_Ptr32: \
141 case ParsedAttr::AT_Ptr64: \
142 case ParsedAttr::AT_SPtr: \
143 case ParsedAttr::AT_UPtr
145 // Nullability qualifiers.
146 #define NULLABILITY_TYPE_ATTRS_CASELIST \
147 case ParsedAttr::AT_TypeNonNull: \
148 case ParsedAttr::AT_TypeNullable: \
149 case ParsedAttr::AT_TypeNullUnspecified
152 /// An object which stores processing state for the entire
153 /// GetTypeForDeclarator process.
154 class TypeProcessingState {
157 /// The declarator being processed.
158 Declarator &declarator;
160 /// The index of the declarator chunk we're currently processing.
161 /// May be the total number of valid chunks, indicating the
165 /// Whether there are non-trivial modifications to the decl spec.
168 /// Whether we saved the attributes in the decl spec.
171 /// The original set of attributes on the DeclSpec.
172 SmallVector<ParsedAttr *, 2> savedAttrs;
174 /// A list of attributes to diagnose the uselessness of when the
175 /// processing is complete.
176 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
178 /// Attributes corresponding to AttributedTypeLocs that we have not yet
180 // FIXME: The two-phase mechanism by which we construct Types and fill
181 // their TypeLocs makes it hard to correctly assign these. We keep the
182 // attributes in creation order as an attempt to make them line up
184 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
185 SmallVector<TypeAttrPair, 8> AttrsForTypes;
186 bool AttrsForTypesSorted = true;
188 /// MacroQualifiedTypes mapping to macro expansion locations that will be
189 /// stored in a MacroQualifiedTypeLoc.
190 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
192 /// Flag to indicate we parsed a noderef attribute. This is used for
193 /// validating that noderef was used on a pointer or array.
197 TypeProcessingState(Sema &sema, Declarator &declarator)
198 : sema(sema), declarator(declarator),
199 chunkIndex(declarator.getNumTypeObjects()), trivial(true),
200 hasSavedAttrs(false), parsedNoDeref(false) {}
202 Sema &getSema() const {
206 Declarator &getDeclarator() const {
210 bool isProcessingDeclSpec() const {
211 return chunkIndex == declarator.getNumTypeObjects();
214 unsigned getCurrentChunkIndex() const {
218 void setCurrentChunkIndex(unsigned idx) {
219 assert(idx <= declarator.getNumTypeObjects());
223 ParsedAttributesView &getCurrentAttributes() const {
224 if (isProcessingDeclSpec())
225 return getMutableDeclSpec().getAttributes();
226 return declarator.getTypeObject(chunkIndex).getAttrs();
229 /// Save the current set of attributes on the DeclSpec.
230 void saveDeclSpecAttrs() {
231 // Don't try to save them multiple times.
232 if (hasSavedAttrs) return;
234 DeclSpec &spec = getMutableDeclSpec();
235 for (ParsedAttr &AL : spec.getAttributes())
236 savedAttrs.push_back(&AL);
237 trivial &= savedAttrs.empty();
238 hasSavedAttrs = true;
241 /// Record that we had nowhere to put the given type attribute.
242 /// We will diagnose such attributes later.
243 void addIgnoredTypeAttr(ParsedAttr &attr) {
244 ignoredTypeAttrs.push_back(&attr);
247 /// Diagnose all the ignored type attributes, given that the
248 /// declarator worked out to the given type.
249 void diagnoseIgnoredTypeAttrs(QualType type) const {
250 for (auto *Attr : ignoredTypeAttrs)
251 diagnoseBadTypeAttribute(getSema(), *Attr, type);
254 /// Get an attributed type for the given attribute, and remember the Attr
255 /// object so that we can attach it to the AttributedTypeLoc.
256 QualType getAttributedType(Attr *A, QualType ModifiedType,
257 QualType EquivType) {
259 sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
260 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
261 AttrsForTypesSorted = false;
265 /// Completely replace the \c auto in \p TypeWithAuto by
266 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
268 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
269 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
270 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
271 // Attributed type still should be an attributed type after replacement.
272 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
273 for (TypeAttrPair &A : AttrsForTypes) {
274 if (A.first == AttrTy)
277 AttrsForTypesSorted = false;
282 /// Extract and remove the Attr* for a given attributed type.
283 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
284 if (!AttrsForTypesSorted) {
285 llvm::stable_sort(AttrsForTypes, llvm::less_first());
286 AttrsForTypesSorted = true;
289 // FIXME: This is quadratic if we have lots of reuses of the same
291 for (auto It = std::partition_point(
292 AttrsForTypes.begin(), AttrsForTypes.end(),
293 [=](const TypeAttrPair &A) { return A.first < AT; });
294 It != AttrsForTypes.end() && It->first == AT; ++It) {
296 const Attr *Result = It->second;
297 It->second = nullptr;
302 llvm_unreachable("no Attr* for AttributedType*");
306 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
307 auto FoundLoc = LocsForMacros.find(MQT);
308 assert(FoundLoc != LocsForMacros.end() &&
309 "Unable to find macro expansion location for MacroQualifedType");
310 return FoundLoc->second;
313 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
314 SourceLocation Loc) {
315 LocsForMacros[MQT] = Loc;
318 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
320 bool didParseNoDeref() const { return parsedNoDeref; }
322 ~TypeProcessingState() {
325 restoreDeclSpecAttrs();
329 DeclSpec &getMutableDeclSpec() const {
330 return const_cast<DeclSpec&>(declarator.getDeclSpec());
333 void restoreDeclSpecAttrs() {
334 assert(hasSavedAttrs);
336 getMutableDeclSpec().getAttributes().clearListOnly();
337 for (ParsedAttr *AL : savedAttrs)
338 getMutableDeclSpec().getAttributes().addAtEnd(AL);
341 } // end anonymous namespace
343 static void moveAttrFromListToList(ParsedAttr &attr,
344 ParsedAttributesView &fromList,
345 ParsedAttributesView &toList) {
346 fromList.remove(&attr);
347 toList.addAtEnd(&attr);
350 /// The location of a type attribute.
351 enum TypeAttrLocation {
352 /// The attribute is in the decl-specifier-seq.
354 /// The attribute is part of a DeclaratorChunk.
356 /// The attribute is immediately after the declaration's name.
360 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
361 TypeAttrLocation TAL, ParsedAttributesView &attrs);
363 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
366 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
367 ParsedAttr &attr, QualType &type);
369 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
372 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
373 ParsedAttr &attr, QualType &type);
375 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
376 ParsedAttr &attr, QualType &type) {
377 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
378 return handleObjCGCTypeAttr(state, attr, type);
379 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
380 return handleObjCOwnershipTypeAttr(state, attr, type);
383 /// Given the index of a declarator chunk, check whether that chunk
384 /// directly specifies the return type of a function and, if so, find
385 /// an appropriate place for it.
387 /// \param i - a notional index which the search will start
388 /// immediately inside
390 /// \param onlyBlockPointers Whether we should only look into block
391 /// pointer types (vs. all pointer types).
392 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
394 bool onlyBlockPointers) {
395 assert(i <= declarator.getNumTypeObjects());
397 DeclaratorChunk *result = nullptr;
399 // First, look inwards past parens for a function declarator.
400 for (; i != 0; --i) {
401 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
402 switch (fnChunk.Kind) {
403 case DeclaratorChunk::Paren:
406 // If we find anything except a function, bail out.
407 case DeclaratorChunk::Pointer:
408 case DeclaratorChunk::BlockPointer:
409 case DeclaratorChunk::Array:
410 case DeclaratorChunk::Reference:
411 case DeclaratorChunk::MemberPointer:
412 case DeclaratorChunk::Pipe:
415 // If we do find a function declarator, scan inwards from that,
416 // looking for a (block-)pointer declarator.
417 case DeclaratorChunk::Function:
418 for (--i; i != 0; --i) {
419 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
420 switch (ptrChunk.Kind) {
421 case DeclaratorChunk::Paren:
422 case DeclaratorChunk::Array:
423 case DeclaratorChunk::Function:
424 case DeclaratorChunk::Reference:
425 case DeclaratorChunk::Pipe:
428 case DeclaratorChunk::MemberPointer:
429 case DeclaratorChunk::Pointer:
430 if (onlyBlockPointers)
435 case DeclaratorChunk::BlockPointer:
439 llvm_unreachable("bad declarator chunk kind");
442 // If we run out of declarators doing that, we're done.
445 llvm_unreachable("bad declarator chunk kind");
447 // Okay, reconsider from our new point.
451 // Ran out of chunks, bail out.
455 /// Given that an objc_gc attribute was written somewhere on a
456 /// declaration *other* than on the declarator itself (for which, use
457 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
458 /// didn't apply in whatever position it was written in, try to move
459 /// it to a more appropriate position.
460 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
461 ParsedAttr &attr, QualType type) {
462 Declarator &declarator = state.getDeclarator();
464 // Move it to the outermost normal or block pointer declarator.
465 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
466 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
467 switch (chunk.Kind) {
468 case DeclaratorChunk::Pointer:
469 case DeclaratorChunk::BlockPointer: {
470 // But don't move an ARC ownership attribute to the return type
472 DeclaratorChunk *destChunk = nullptr;
473 if (state.isProcessingDeclSpec() &&
474 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
475 destChunk = maybeMovePastReturnType(declarator, i - 1,
476 /*onlyBlockPointers=*/true);
477 if (!destChunk) destChunk = &chunk;
479 moveAttrFromListToList(attr, state.getCurrentAttributes(),
480 destChunk->getAttrs());
484 case DeclaratorChunk::Paren:
485 case DeclaratorChunk::Array:
488 // We may be starting at the return type of a block.
489 case DeclaratorChunk::Function:
490 if (state.isProcessingDeclSpec() &&
491 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
492 if (DeclaratorChunk *dest = maybeMovePastReturnType(
494 /*onlyBlockPointers=*/true)) {
495 moveAttrFromListToList(attr, state.getCurrentAttributes(),
502 // Don't walk through these.
503 case DeclaratorChunk::Reference:
504 case DeclaratorChunk::MemberPointer:
505 case DeclaratorChunk::Pipe:
511 diagnoseBadTypeAttribute(state.getSema(), attr, type);
514 /// Distribute an objc_gc type attribute that was written on the
516 static void distributeObjCPointerTypeAttrFromDeclarator(
517 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
518 Declarator &declarator = state.getDeclarator();
520 // objc_gc goes on the innermost pointer to something that's not a
522 unsigned innermost = -1U;
523 bool considerDeclSpec = true;
524 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
525 DeclaratorChunk &chunk = declarator.getTypeObject(i);
526 switch (chunk.Kind) {
527 case DeclaratorChunk::Pointer:
528 case DeclaratorChunk::BlockPointer:
532 case DeclaratorChunk::Reference:
533 case DeclaratorChunk::MemberPointer:
534 case DeclaratorChunk::Paren:
535 case DeclaratorChunk::Array:
536 case DeclaratorChunk::Pipe:
539 case DeclaratorChunk::Function:
540 considerDeclSpec = false;
546 // That might actually be the decl spec if we weren't blocked by
547 // anything in the declarator.
548 if (considerDeclSpec) {
549 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
550 // Splice the attribute into the decl spec. Prevents the
551 // attribute from being applied multiple times and gives
552 // the source-location-filler something to work with.
553 state.saveDeclSpecAttrs();
554 declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
555 declarator.getAttributes(), &attr);
560 // Otherwise, if we found an appropriate chunk, splice the attribute
562 if (innermost != -1U) {
563 moveAttrFromListToList(attr, declarator.getAttributes(),
564 declarator.getTypeObject(innermost).getAttrs());
568 // Otherwise, diagnose when we're done building the type.
569 declarator.getAttributes().remove(&attr);
570 state.addIgnoredTypeAttr(attr);
573 /// A function type attribute was written somewhere in a declaration
574 /// *other* than on the declarator itself or in the decl spec. Given
575 /// that it didn't apply in whatever position it was written in, try
576 /// to move it to a more appropriate position.
577 static void distributeFunctionTypeAttr(TypeProcessingState &state,
578 ParsedAttr &attr, QualType type) {
579 Declarator &declarator = state.getDeclarator();
581 // Try to push the attribute from the return type of a function to
582 // the function itself.
583 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
584 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
585 switch (chunk.Kind) {
586 case DeclaratorChunk::Function:
587 moveAttrFromListToList(attr, state.getCurrentAttributes(),
591 case DeclaratorChunk::Paren:
592 case DeclaratorChunk::Pointer:
593 case DeclaratorChunk::BlockPointer:
594 case DeclaratorChunk::Array:
595 case DeclaratorChunk::Reference:
596 case DeclaratorChunk::MemberPointer:
597 case DeclaratorChunk::Pipe:
602 diagnoseBadTypeAttribute(state.getSema(), attr, type);
605 /// Try to distribute a function type attribute to the innermost
606 /// function chunk or type. Returns true if the attribute was
607 /// distributed, false if no location was found.
608 static bool distributeFunctionTypeAttrToInnermost(
609 TypeProcessingState &state, ParsedAttr &attr,
610 ParsedAttributesView &attrList, QualType &declSpecType) {
611 Declarator &declarator = state.getDeclarator();
613 // Put it on the innermost function chunk, if there is one.
614 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
615 DeclaratorChunk &chunk = declarator.getTypeObject(i);
616 if (chunk.Kind != DeclaratorChunk::Function) continue;
618 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
622 return handleFunctionTypeAttr(state, attr, declSpecType);
625 /// A function type attribute was written in the decl spec. Try to
626 /// apply it somewhere.
627 static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
629 QualType &declSpecType) {
630 state.saveDeclSpecAttrs();
632 // C++11 attributes before the decl specifiers actually appertain to
633 // the declarators. Move them straight there. We don't support the
634 // 'put them wherever you like' semantics we allow for GNU attributes.
635 if (attr.isCXX11Attribute()) {
636 moveAttrFromListToList(attr, state.getCurrentAttributes(),
637 state.getDeclarator().getAttributes());
641 // Try to distribute to the innermost.
642 if (distributeFunctionTypeAttrToInnermost(
643 state, attr, state.getCurrentAttributes(), declSpecType))
646 // If that failed, diagnose the bad attribute when the declarator is
648 state.addIgnoredTypeAttr(attr);
651 /// A function type attribute was written on the declarator. Try to
652 /// apply it somewhere.
653 static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
655 QualType &declSpecType) {
656 Declarator &declarator = state.getDeclarator();
658 // Try to distribute to the innermost.
659 if (distributeFunctionTypeAttrToInnermost(
660 state, attr, declarator.getAttributes(), declSpecType))
663 // If that failed, diagnose the bad attribute when the declarator is
665 declarator.getAttributes().remove(&attr);
666 state.addIgnoredTypeAttr(attr);
669 /// Given that there are attributes written on the declarator
670 /// itself, try to distribute any type attributes to the appropriate
671 /// declarator chunk.
673 /// These are attributes like the following:
676 /// but not necessarily this:
678 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
679 QualType &declSpecType) {
680 // Collect all the type attributes from the declarator itself.
681 assert(!state.getDeclarator().getAttributes().empty() &&
682 "declarator has no attrs!");
683 // The called functions in this loop actually remove things from the current
684 // list, so iterating over the existing list isn't possible. Instead, make a
685 // non-owning copy and iterate over that.
686 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
687 for (ParsedAttr &attr : AttrsCopy) {
688 // Do not distribute C++11 attributes. They have strict rules for what
689 // they appertain to.
690 if (attr.isCXX11Attribute())
693 switch (attr.getKind()) {
694 OBJC_POINTER_TYPE_ATTRS_CASELIST:
695 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
698 FUNCTION_TYPE_ATTRS_CASELIST:
699 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
702 MS_TYPE_ATTRS_CASELIST:
703 // Microsoft type attributes cannot go after the declarator-id.
706 NULLABILITY_TYPE_ATTRS_CASELIST:
707 // Nullability specifiers cannot go after the declarator-id.
709 // Objective-C __kindof does not get distributed.
710 case ParsedAttr::AT_ObjCKindOf:
719 /// Add a synthetic '()' to a block-literal declarator if it is
720 /// required, given the return type.
721 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
722 QualType declSpecType) {
723 Declarator &declarator = state.getDeclarator();
725 // First, check whether the declarator would produce a function,
726 // i.e. whether the innermost semantic chunk is a function.
727 if (declarator.isFunctionDeclarator()) {
728 // If so, make that declarator a prototyped declarator.
729 declarator.getFunctionTypeInfo().hasPrototype = true;
733 // If there are any type objects, the type as written won't name a
734 // function, regardless of the decl spec type. This is because a
735 // block signature declarator is always an abstract-declarator, and
736 // abstract-declarators can't just be parentheses chunks. Therefore
737 // we need to build a function chunk unless there are no type
738 // objects and the decl spec type is a function.
739 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
742 // Note that there *are* cases with invalid declarators where
743 // declarators consist solely of parentheses. In general, these
744 // occur only in failed efforts to make function declarators, so
745 // faking up the function chunk is still the right thing to do.
747 // Otherwise, we need to fake up a function declarator.
748 SourceLocation loc = declarator.getBeginLoc();
750 // ...and *prepend* it to the declarator.
751 SourceLocation NoLoc;
752 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
754 /*IsAmbiguous=*/false,
758 /*EllipsisLoc=*/NoLoc,
760 /*RefQualifierIsLvalueRef=*/true,
761 /*RefQualifierLoc=*/NoLoc,
762 /*MutableLoc=*/NoLoc, EST_None,
763 /*ESpecRange=*/SourceRange(),
764 /*Exceptions=*/nullptr,
765 /*ExceptionRanges=*/nullptr,
767 /*NoexceptExpr=*/nullptr,
768 /*ExceptionSpecTokens=*/nullptr,
769 /*DeclsInPrototype=*/None, loc, loc, declarator));
771 // For consistency, make sure the state still has us as processing
773 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
774 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
777 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
782 // If this occurs outside a template instantiation, warn the user about
783 // it; they probably didn't mean to specify a redundant qualifier.
784 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
785 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
786 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
787 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
788 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
789 if (!(RemoveTQs & Qual.first))
792 if (!S.inTemplateInstantiation()) {
793 if (TypeQuals & Qual.first)
794 S.Diag(Qual.second, DiagID)
795 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
796 << FixItHint::CreateRemoval(Qual.second);
799 TypeQuals &= ~Qual.first;
803 /// Return true if this is omitted block return type. Also check type
804 /// attributes and type qualifiers when returning true.
805 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
807 if (!isOmittedBlockReturnType(declarator))
810 // Warn if we see type attributes for omitted return type on a block literal.
811 SmallVector<ParsedAttr *, 2> ToBeRemoved;
812 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
813 if (AL.isInvalid() || !AL.isTypeAttr())
816 diag::warn_block_literal_attributes_on_omitted_return_type)
818 ToBeRemoved.push_back(&AL);
820 // Remove bad attributes from the list.
821 for (ParsedAttr *AL : ToBeRemoved)
822 declarator.getMutableDeclSpec().getAttributes().remove(AL);
824 // Warn if we see type qualifiers for omitted return type on a block literal.
825 const DeclSpec &DS = declarator.getDeclSpec();
826 unsigned TypeQuals = DS.getTypeQualifiers();
827 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
828 diag::warn_block_literal_qualifiers_on_omitted_return_type);
829 declarator.getMutableDeclSpec().ClearTypeQualifiers();
834 /// Apply Objective-C type arguments to the given type.
835 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
836 ArrayRef<TypeSourceInfo *> typeArgs,
837 SourceRange typeArgsRange,
838 bool failOnError = false) {
839 // We can only apply type arguments to an Objective-C class type.
840 const auto *objcObjectType = type->getAs<ObjCObjectType>();
841 if (!objcObjectType || !objcObjectType->getInterface()) {
842 S.Diag(loc, diag::err_objc_type_args_non_class)
851 // The class type must be parameterized.
852 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
853 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
855 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
856 << objcClass->getDeclName()
857 << FixItHint::CreateRemoval(typeArgsRange);
865 // The type must not already be specialized.
866 if (objcObjectType->isSpecialized()) {
867 S.Diag(loc, diag::err_objc_type_args_specialized_class)
869 << FixItHint::CreateRemoval(typeArgsRange);
877 // Check the type arguments.
878 SmallVector<QualType, 4> finalTypeArgs;
879 unsigned numTypeParams = typeParams->size();
880 bool anyPackExpansions = false;
881 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
882 TypeSourceInfo *typeArgInfo = typeArgs[i];
883 QualType typeArg = typeArgInfo->getType();
885 // Type arguments cannot have explicit qualifiers or nullability.
886 // We ignore indirect sources of these, e.g. behind typedefs or
887 // template arguments.
888 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
889 bool diagnosed = false;
890 SourceRange rangeToRemove;
891 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
892 rangeToRemove = attr.getLocalSourceRange();
893 if (attr.getTypePtr()->getImmediateNullability()) {
894 typeArg = attr.getTypePtr()->getModifiedType();
895 S.Diag(attr.getBeginLoc(),
896 diag::err_objc_type_arg_explicit_nullability)
897 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
903 S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
904 << typeArg << typeArg.getQualifiers().getAsString()
905 << FixItHint::CreateRemoval(rangeToRemove);
909 // Remove qualifiers even if they're non-local.
910 typeArg = typeArg.getUnqualifiedType();
912 finalTypeArgs.push_back(typeArg);
914 if (typeArg->getAs<PackExpansionType>())
915 anyPackExpansions = true;
917 // Find the corresponding type parameter, if there is one.
918 ObjCTypeParamDecl *typeParam = nullptr;
919 if (!anyPackExpansions) {
920 if (i < numTypeParams) {
921 typeParam = typeParams->begin()[i];
923 // Too many arguments.
924 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
926 << objcClass->getDeclName()
927 << (unsigned)typeArgs.size()
929 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
939 // Objective-C object pointer types must be substitutable for the bounds.
940 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
941 // If we don't have a type parameter to match against, assume
942 // everything is fine. There was a prior pack expansion that
943 // means we won't be able to match anything.
945 assert(anyPackExpansions && "Too many arguments?");
949 // Retrieve the bound.
950 QualType bound = typeParam->getUnderlyingType();
951 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
953 // Determine whether the type argument is substitutable for the bound.
954 if (typeArgObjC->isObjCIdType()) {
955 // When the type argument is 'id', the only acceptable type
956 // parameter bound is 'id'.
957 if (boundObjC->isObjCIdType())
959 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
960 // Otherwise, we follow the assignability rules.
964 // Diagnose the mismatch.
965 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
966 diag::err_objc_type_arg_does_not_match_bound)
967 << typeArg << bound << typeParam->getDeclName();
968 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
969 << typeParam->getDeclName();
977 // Block pointer types are permitted for unqualified 'id' bounds.
978 if (typeArg->isBlockPointerType()) {
979 // If we don't have a type parameter to match against, assume
980 // everything is fine. There was a prior pack expansion that
981 // means we won't be able to match anything.
983 assert(anyPackExpansions && "Too many arguments?");
987 // Retrieve the bound.
988 QualType bound = typeParam->getUnderlyingType();
989 if (bound->isBlockCompatibleObjCPointerType(S.Context))
992 // Diagnose the mismatch.
993 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
994 diag::err_objc_type_arg_does_not_match_bound)
995 << typeArg << bound << typeParam->getDeclName();
996 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
997 << typeParam->getDeclName();
1005 // Dependent types will be checked at instantiation time.
1006 if (typeArg->isDependentType()) {
1010 // Diagnose non-id-compatible type arguments.
1011 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1012 diag::err_objc_type_arg_not_id_compatible)
1013 << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
1021 // Make sure we didn't have the wrong number of arguments.
1022 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
1023 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
1024 << (typeArgs.size() < typeParams->size())
1025 << objcClass->getDeclName()
1026 << (unsigned)finalTypeArgs.size()
1027 << (unsigned)numTypeParams;
1028 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1037 // Success. Form the specialized type.
1038 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1041 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1042 SourceLocation ProtocolLAngleLoc,
1043 ArrayRef<ObjCProtocolDecl *> Protocols,
1044 ArrayRef<SourceLocation> ProtocolLocs,
1045 SourceLocation ProtocolRAngleLoc,
1047 QualType Result = QualType(Decl->getTypeForDecl(), 0);
1048 if (!Protocols.empty()) {
1050 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1053 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1054 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1055 if (FailOnError) Result = QualType();
1057 if (FailOnError && Result.isNull())
1064 QualType Sema::BuildObjCObjectType(QualType BaseType,
1066 SourceLocation TypeArgsLAngleLoc,
1067 ArrayRef<TypeSourceInfo *> TypeArgs,
1068 SourceLocation TypeArgsRAngleLoc,
1069 SourceLocation ProtocolLAngleLoc,
1070 ArrayRef<ObjCProtocolDecl *> Protocols,
1071 ArrayRef<SourceLocation> ProtocolLocs,
1072 SourceLocation ProtocolRAngleLoc,
1074 QualType Result = BaseType;
1075 if (!TypeArgs.empty()) {
1076 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1077 SourceRange(TypeArgsLAngleLoc,
1080 if (FailOnError && Result.isNull())
1084 if (!Protocols.empty()) {
1086 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1089 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1090 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1091 if (FailOnError) Result = QualType();
1093 if (FailOnError && Result.isNull())
1100 TypeResult Sema::actOnObjCProtocolQualifierType(
1101 SourceLocation lAngleLoc,
1102 ArrayRef<Decl *> protocols,
1103 ArrayRef<SourceLocation> protocolLocs,
1104 SourceLocation rAngleLoc) {
1105 // Form id<protocol-list>.
1106 QualType Result = Context.getObjCObjectType(
1107 Context.ObjCBuiltinIdTy, { },
1109 (ObjCProtocolDecl * const *)protocols.data(),
1112 Result = Context.getObjCObjectPointerType(Result);
1114 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1115 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1117 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1118 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1120 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1121 .castAs<ObjCObjectTypeLoc>();
1122 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1123 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1125 // No type arguments.
1126 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1127 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1129 // Fill in protocol qualifiers.
1130 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1131 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1132 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1133 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1135 // We're done. Return the completed type to the parser.
1136 return CreateParsedType(Result, ResultTInfo);
1139 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1142 ParsedType BaseType,
1143 SourceLocation TypeArgsLAngleLoc,
1144 ArrayRef<ParsedType> TypeArgs,
1145 SourceLocation TypeArgsRAngleLoc,
1146 SourceLocation ProtocolLAngleLoc,
1147 ArrayRef<Decl *> Protocols,
1148 ArrayRef<SourceLocation> ProtocolLocs,
1149 SourceLocation ProtocolRAngleLoc) {
1150 TypeSourceInfo *BaseTypeInfo = nullptr;
1151 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1155 // Handle missing type-source info.
1157 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1159 // Extract type arguments.
1160 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1161 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1162 TypeSourceInfo *TypeArgInfo = nullptr;
1163 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1164 if (TypeArg.isNull()) {
1165 ActualTypeArgInfos.clear();
1169 assert(TypeArgInfo && "No type source info?");
1170 ActualTypeArgInfos.push_back(TypeArgInfo);
1173 // Build the object type.
1174 QualType Result = BuildObjCObjectType(
1175 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1176 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1178 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1180 ProtocolLocs, ProtocolRAngleLoc,
1181 /*FailOnError=*/false);
1186 // Create source information for this type.
1187 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1188 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1190 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1191 // object pointer type. Fill in source information for it.
1192 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1193 // The '*' is implicit.
1194 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1195 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1198 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1199 // Protocol qualifier information.
1200 if (OTPTL.getNumProtocols() > 0) {
1201 assert(OTPTL.getNumProtocols() == Protocols.size());
1202 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1203 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1204 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1205 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1208 // We're done. Return the completed type to the parser.
1209 return CreateParsedType(Result, ResultTInfo);
1212 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1214 // Type argument information.
1215 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1216 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1217 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1218 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1219 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1220 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1222 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1223 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1226 // Protocol qualifier information.
1227 if (ObjCObjectTL.getNumProtocols() > 0) {
1228 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1229 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1230 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1231 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1232 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1234 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1235 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1239 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1240 if (ObjCObjectTL.getType() == T)
1241 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1243 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1245 // We're done. Return the completed type to the parser.
1246 return CreateParsedType(Result, ResultTInfo);
1249 static OpenCLAccessAttr::Spelling
1250 getImageAccess(const ParsedAttributesView &Attrs) {
1251 for (const ParsedAttr &AL : Attrs)
1252 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1253 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1254 return OpenCLAccessAttr::Keyword_read_only;
1257 static QualType ConvertConstrainedAutoDeclSpecToType(Sema &S, DeclSpec &DS,
1258 AutoTypeKeyword AutoKW) {
1259 assert(DS.isConstrainedAuto());
1260 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
1261 TemplateArgumentListInfo TemplateArgsInfo;
1262 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1263 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1264 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1265 TemplateId->NumArgs);
1266 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1267 llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1268 for (auto &ArgLoc : TemplateArgsInfo.arguments())
1269 TemplateArgs.push_back(ArgLoc.getArgument());
1270 return S.Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false,
1272 cast<ConceptDecl>(TemplateId->Template.get()
1273 .getAsTemplateDecl()),
1277 /// Convert the specified declspec to the appropriate type
1279 /// \param state Specifies the declarator containing the declaration specifier
1280 /// to be converted, along with other associated processing state.
1281 /// \returns The type described by the declaration specifiers. This function
1282 /// never returns null.
1283 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1284 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1287 Sema &S = state.getSema();
1288 Declarator &declarator = state.getDeclarator();
1289 DeclSpec &DS = declarator.getMutableDeclSpec();
1290 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1291 if (DeclLoc.isInvalid())
1292 DeclLoc = DS.getBeginLoc();
1294 ASTContext &Context = S.Context;
1297 switch (DS.getTypeSpecType()) {
1298 case DeclSpec::TST_void:
1299 Result = Context.VoidTy;
1301 case DeclSpec::TST_char:
1302 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1303 Result = Context.CharTy;
1304 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1305 Result = Context.SignedCharTy;
1307 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1308 "Unknown TSS value");
1309 Result = Context.UnsignedCharTy;
1312 case DeclSpec::TST_wchar:
1313 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1314 Result = Context.WCharTy;
1315 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1316 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1317 << DS.getSpecifierName(DS.getTypeSpecType(),
1318 Context.getPrintingPolicy());
1319 Result = Context.getSignedWCharType();
1321 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1322 "Unknown TSS value");
1323 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1324 << DS.getSpecifierName(DS.getTypeSpecType(),
1325 Context.getPrintingPolicy());
1326 Result = Context.getUnsignedWCharType();
1329 case DeclSpec::TST_char8:
1330 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1331 "Unknown TSS value");
1332 Result = Context.Char8Ty;
1334 case DeclSpec::TST_char16:
1335 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1336 "Unknown TSS value");
1337 Result = Context.Char16Ty;
1339 case DeclSpec::TST_char32:
1340 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1341 "Unknown TSS value");
1342 Result = Context.Char32Ty;
1344 case DeclSpec::TST_unspecified:
1345 // If this is a missing declspec in a block literal return context, then it
1346 // is inferred from the return statements inside the block.
1347 // The declspec is always missing in a lambda expr context; it is either
1348 // specified with a trailing return type or inferred.
1349 if (S.getLangOpts().CPlusPlus14 &&
1350 declarator.getContext() == DeclaratorContext::LambdaExprContext) {
1351 // In C++1y, a lambda's implicit return type is 'auto'.
1352 Result = Context.getAutoDeductType();
1354 } else if (declarator.getContext() ==
1355 DeclaratorContext::LambdaExprContext ||
1356 checkOmittedBlockReturnType(S, declarator,
1357 Context.DependentTy)) {
1358 Result = Context.DependentTy;
1362 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1363 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1364 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1365 // Note that the one exception to this is function definitions, which are
1366 // allowed to be completely missing a declspec. This is handled in the
1367 // parser already though by it pretending to have seen an 'int' in this
1369 if (S.getLangOpts().ImplicitInt) {
1370 // In C89 mode, we only warn if there is a completely missing declspec
1371 // when one is not allowed.
1373 S.Diag(DeclLoc, diag::ext_missing_declspec)
1374 << DS.getSourceRange()
1375 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1377 } else if (!DS.hasTypeSpecifier()) {
1378 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1379 // "At least one type specifier shall be given in the declaration
1380 // specifiers in each declaration, and in the specifier-qualifier list in
1381 // each struct declaration and type name."
1382 if (S.getLangOpts().CPlusPlus && !DS.isTypeSpecPipe()) {
1383 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1384 << DS.getSourceRange();
1386 // When this occurs in C++ code, often something is very broken with the
1387 // value being declared, poison it as invalid so we don't get chains of
1389 declarator.setInvalidType(true);
1390 } else if ((S.getLangOpts().OpenCLVersion >= 200 ||
1391 S.getLangOpts().OpenCLCPlusPlus) &&
1392 DS.isTypeSpecPipe()) {
1393 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1394 << DS.getSourceRange();
1395 declarator.setInvalidType(true);
1397 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1398 << DS.getSourceRange();
1403 case DeclSpec::TST_int: {
1404 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
1405 switch (DS.getTypeSpecWidth()) {
1406 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1407 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
1408 case DeclSpec::TSW_long: Result = Context.LongTy; break;
1409 case DeclSpec::TSW_longlong:
1410 Result = Context.LongLongTy;
1412 // 'long long' is a C99 or C++11 feature.
1413 if (!S.getLangOpts().C99) {
1414 if (S.getLangOpts().CPlusPlus)
1415 S.Diag(DS.getTypeSpecWidthLoc(),
1416 S.getLangOpts().CPlusPlus11 ?
1417 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1419 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1424 switch (DS.getTypeSpecWidth()) {
1425 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1426 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
1427 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
1428 case DeclSpec::TSW_longlong:
1429 Result = Context.UnsignedLongLongTy;
1431 // 'long long' is a C99 or C++11 feature.
1432 if (!S.getLangOpts().C99) {
1433 if (S.getLangOpts().CPlusPlus)
1434 S.Diag(DS.getTypeSpecWidthLoc(),
1435 S.getLangOpts().CPlusPlus11 ?
1436 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1438 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1445 case DeclSpec::TST_extint: {
1446 if (!S.Context.getTargetInfo().hasExtIntType())
1447 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1449 Result = S.BuildExtIntType(DS.getTypeSpecSign() == TSS_unsigned,
1450 DS.getRepAsExpr(), DS.getBeginLoc());
1451 if (Result.isNull()) {
1452 Result = Context.IntTy;
1453 declarator.setInvalidType(true);
1457 case DeclSpec::TST_accum: {
1458 switch (DS.getTypeSpecWidth()) {
1459 case DeclSpec::TSW_short:
1460 Result = Context.ShortAccumTy;
1462 case DeclSpec::TSW_unspecified:
1463 Result = Context.AccumTy;
1465 case DeclSpec::TSW_long:
1466 Result = Context.LongAccumTy;
1468 case DeclSpec::TSW_longlong:
1469 llvm_unreachable("Unable to specify long long as _Accum width");
1472 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1473 Result = Context.getCorrespondingUnsignedType(Result);
1475 if (DS.isTypeSpecSat())
1476 Result = Context.getCorrespondingSaturatedType(Result);
1480 case DeclSpec::TST_fract: {
1481 switch (DS.getTypeSpecWidth()) {
1482 case DeclSpec::TSW_short:
1483 Result = Context.ShortFractTy;
1485 case DeclSpec::TSW_unspecified:
1486 Result = Context.FractTy;
1488 case DeclSpec::TSW_long:
1489 Result = Context.LongFractTy;
1491 case DeclSpec::TSW_longlong:
1492 llvm_unreachable("Unable to specify long long as _Fract width");
1495 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1496 Result = Context.getCorrespondingUnsignedType(Result);
1498 if (DS.isTypeSpecSat())
1499 Result = Context.getCorrespondingSaturatedType(Result);
1503 case DeclSpec::TST_int128:
1504 if (!S.Context.getTargetInfo().hasInt128Type() &&
1505 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1506 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1508 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1509 Result = Context.UnsignedInt128Ty;
1511 Result = Context.Int128Ty;
1513 case DeclSpec::TST_float16:
1514 // CUDA host and device may have different _Float16 support, therefore
1515 // do not diagnose _Float16 usage to avoid false alarm.
1516 // ToDo: more precise diagnostics for CUDA.
1517 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1518 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1519 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1521 Result = Context.Float16Ty;
1523 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1524 case DeclSpec::TST_BFloat16:
1525 if (!S.Context.getTargetInfo().hasBFloat16Type())
1526 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1528 Result = Context.BFloat16Ty;
1530 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1531 case DeclSpec::TST_double:
1532 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1533 Result = Context.LongDoubleTy;
1535 Result = Context.DoubleTy;
1537 case DeclSpec::TST_float128:
1538 if (!S.Context.getTargetInfo().hasFloat128Type() &&
1539 !S.getLangOpts().SYCLIsDevice &&
1540 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1541 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1543 Result = Context.Float128Ty;
1545 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1547 case DeclSpec::TST_decimal32: // _Decimal32
1548 case DeclSpec::TST_decimal64: // _Decimal64
1549 case DeclSpec::TST_decimal128: // _Decimal128
1550 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1551 Result = Context.IntTy;
1552 declarator.setInvalidType(true);
1554 case DeclSpec::TST_class:
1555 case DeclSpec::TST_enum:
1556 case DeclSpec::TST_union:
1557 case DeclSpec::TST_struct:
1558 case DeclSpec::TST_interface: {
1559 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1561 // This can happen in C++ with ambiguous lookups.
1562 Result = Context.IntTy;
1563 declarator.setInvalidType(true);
1567 // If the type is deprecated or unavailable, diagnose it.
1568 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1570 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1571 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1573 // TypeQuals handled by caller.
1574 Result = Context.getTypeDeclType(D);
1576 // In both C and C++, make an ElaboratedType.
1577 ElaboratedTypeKeyword Keyword
1578 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1579 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1580 DS.isTypeSpecOwned() ? D : nullptr);
1583 case DeclSpec::TST_typename: {
1584 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1585 DS.getTypeSpecSign() == 0 &&
1586 "Can't handle qualifiers on typedef names yet!");
1587 Result = S.GetTypeFromParser(DS.getRepAsType());
1588 if (Result.isNull()) {
1589 declarator.setInvalidType(true);
1592 // TypeQuals handled by caller.
1595 case DeclSpec::TST_typeofType:
1596 // FIXME: Preserve type source info.
1597 Result = S.GetTypeFromParser(DS.getRepAsType());
1598 assert(!Result.isNull() && "Didn't get a type for typeof?");
1599 if (!Result->isDependentType())
1600 if (const TagType *TT = Result->getAs<TagType>())
1601 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1602 // TypeQuals handled by caller.
1603 Result = Context.getTypeOfType(Result);
1605 case DeclSpec::TST_typeofExpr: {
1606 Expr *E = DS.getRepAsExpr();
1607 assert(E && "Didn't get an expression for typeof?");
1608 // TypeQuals handled by caller.
1609 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1610 if (Result.isNull()) {
1611 Result = Context.IntTy;
1612 declarator.setInvalidType(true);
1616 case DeclSpec::TST_decltype: {
1617 Expr *E = DS.getRepAsExpr();
1618 assert(E && "Didn't get an expression for decltype?");
1619 // TypeQuals handled by caller.
1620 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1621 if (Result.isNull()) {
1622 Result = Context.IntTy;
1623 declarator.setInvalidType(true);
1627 case DeclSpec::TST_underlyingType:
1628 Result = S.GetTypeFromParser(DS.getRepAsType());
1629 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1630 Result = S.BuildUnaryTransformType(Result,
1631 UnaryTransformType::EnumUnderlyingType,
1632 DS.getTypeSpecTypeLoc());
1633 if (Result.isNull()) {
1634 Result = Context.IntTy;
1635 declarator.setInvalidType(true);
1639 case DeclSpec::TST_auto:
1640 if (DS.isConstrainedAuto()) {
1641 Result = ConvertConstrainedAutoDeclSpecToType(S, DS,
1642 AutoTypeKeyword::Auto);
1645 Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1648 case DeclSpec::TST_auto_type:
1649 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1652 case DeclSpec::TST_decltype_auto:
1653 if (DS.isConstrainedAuto()) {
1655 ConvertConstrainedAutoDeclSpecToType(S, DS,
1656 AutoTypeKeyword::DecltypeAuto);
1659 Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1660 /*IsDependent*/ false);
1663 case DeclSpec::TST_unknown_anytype:
1664 Result = Context.UnknownAnyTy;
1667 case DeclSpec::TST_atomic:
1668 Result = S.GetTypeFromParser(DS.getRepAsType());
1669 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1670 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1671 if (Result.isNull()) {
1672 Result = Context.IntTy;
1673 declarator.setInvalidType(true);
1677 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1678 case DeclSpec::TST_##ImgType##_t: \
1679 switch (getImageAccess(DS.getAttributes())) { \
1680 case OpenCLAccessAttr::Keyword_write_only: \
1681 Result = Context.Id##WOTy; \
1683 case OpenCLAccessAttr::Keyword_read_write: \
1684 Result = Context.Id##RWTy; \
1686 case OpenCLAccessAttr::Keyword_read_only: \
1687 Result = Context.Id##ROTy; \
1689 case OpenCLAccessAttr::SpellingNotCalculated: \
1690 llvm_unreachable("Spelling not yet calculated"); \
1693 #include "clang/Basic/OpenCLImageTypes.def"
1695 case DeclSpec::TST_error:
1696 Result = Context.IntTy;
1697 declarator.setInvalidType(true);
1701 // FIXME: we want resulting declarations to be marked invalid, but claiming
1702 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1704 if (Result->containsErrors())
1705 declarator.setInvalidType();
1707 if (S.getLangOpts().OpenCL &&
1708 S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
1709 declarator.setInvalidType(true);
1711 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1712 DS.getTypeSpecType() == DeclSpec::TST_fract;
1714 // Only fixed point types can be saturated
1715 if (DS.isTypeSpecSat() && !IsFixedPointType)
1716 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1717 << DS.getSpecifierName(DS.getTypeSpecType(),
1718 Context.getPrintingPolicy());
1720 // Handle complex types.
1721 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1722 if (S.getLangOpts().Freestanding)
1723 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1724 Result = Context.getComplexType(Result);
1725 } else if (DS.isTypeAltiVecVector()) {
1726 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1727 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1728 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1729 if (DS.isTypeAltiVecPixel())
1730 VecKind = VectorType::AltiVecPixel;
1731 else if (DS.isTypeAltiVecBool())
1732 VecKind = VectorType::AltiVecBool;
1733 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1736 // FIXME: Imaginary.
1737 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1738 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1740 // Before we process any type attributes, synthesize a block literal
1741 // function declarator if necessary.
1742 if (declarator.getContext() == DeclaratorContext::BlockLiteralContext)
1743 maybeSynthesizeBlockSignature(state, Result);
1745 // Apply any type attributes from the decl spec. This may cause the
1746 // list of type attributes to be temporarily saved while the type
1747 // attributes are pushed around.
1748 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1749 if (!DS.isTypeSpecPipe())
1750 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1752 // Apply const/volatile/restrict qualifiers to T.
1753 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1754 // Warn about CV qualifiers on function types.
1756 // If the specification of a function type includes any type qualifiers,
1757 // the behavior is undefined.
1758 // C++11 [dcl.fct]p7:
1759 // The effect of a cv-qualifier-seq in a function declarator is not the
1760 // same as adding cv-qualification on top of the function type. In the
1761 // latter case, the cv-qualifiers are ignored.
1762 if (Result->isFunctionType()) {
1763 diagnoseAndRemoveTypeQualifiers(
1764 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1765 S.getLangOpts().CPlusPlus
1766 ? diag::warn_typecheck_function_qualifiers_ignored
1767 : diag::warn_typecheck_function_qualifiers_unspecified);
1768 // No diagnostic for 'restrict' or '_Atomic' applied to a
1769 // function type; we'll diagnose those later, in BuildQualifiedType.
1772 // C++11 [dcl.ref]p1:
1773 // Cv-qualified references are ill-formed except when the
1774 // cv-qualifiers are introduced through the use of a typedef-name
1775 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1777 // There don't appear to be any other contexts in which a cv-qualified
1778 // reference type could be formed, so the 'ill-formed' clause here appears
1780 if (TypeQuals && Result->isReferenceType()) {
1781 diagnoseAndRemoveTypeQualifiers(
1782 S, DS, TypeQuals, Result,
1783 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1784 diag::warn_typecheck_reference_qualifiers);
1787 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1788 // than once in the same specifier-list or qualifier-list, either directly
1789 // or via one or more typedefs."
1790 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1791 && TypeQuals & Result.getCVRQualifiers()) {
1792 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1793 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1797 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1798 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1802 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1803 // produce a warning in this case.
1806 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1808 // If adding qualifiers fails, just use the unqualified type.
1809 if (Qualified.isNull())
1810 declarator.setInvalidType(true);
1815 assert(!Result.isNull() && "This function should not return a null type");
1819 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1821 return Entity.getAsString();
1826 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1827 Qualifiers Qs, const DeclSpec *DS) {
1831 // Ignore any attempt to form a cv-qualified reference.
1832 if (T->isReferenceType()) {
1834 Qs.removeVolatile();
1837 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1838 // object or incomplete types shall not be restrict-qualified."
1839 if (Qs.hasRestrict()) {
1840 unsigned DiagID = 0;
1843 if (T->isAnyPointerType() || T->isReferenceType() ||
1844 T->isMemberPointerType()) {
1846 if (T->isObjCObjectPointerType())
1848 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1849 EltTy = PTy->getPointeeType();
1851 EltTy = T->getPointeeType();
1853 // If we have a pointer or reference, the pointee must have an object
1855 if (!EltTy->isIncompleteOrObjectType()) {
1856 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1859 } else if (!T->isDependentType()) {
1860 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1865 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1866 Qs.removeRestrict();
1870 return Context.getQualifiedType(T, Qs);
1873 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1874 unsigned CVRAU, const DeclSpec *DS) {
1878 // Ignore any attempt to form a cv-qualified reference.
1879 if (T->isReferenceType())
1881 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1883 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1885 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1888 // If the same qualifier appears more than once in the same
1889 // specifier-qualifier-list, either directly or via one or more typedefs,
1890 // the behavior is the same as if it appeared only once.
1892 // It's not specified what happens when the _Atomic qualifier is applied to
1893 // a type specified with the _Atomic specifier, but we assume that this
1894 // should be treated as if the _Atomic qualifier appeared multiple times.
1895 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1897 // If other qualifiers appear along with the _Atomic qualifier in a
1898 // specifier-qualifier-list, the resulting type is the so-qualified
1901 // Don't need to worry about array types here, since _Atomic can't be
1902 // applied to such types.
1903 SplitQualType Split = T.getSplitUnqualifiedType();
1904 T = BuildAtomicType(QualType(Split.Ty, 0),
1905 DS ? DS->getAtomicSpecLoc() : Loc);
1908 Split.Quals.addCVRQualifiers(CVR);
1909 return BuildQualifiedType(T, Loc, Split.Quals);
1912 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1913 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1914 return BuildQualifiedType(T, Loc, Q, DS);
1917 /// Build a paren type including \p T.
1918 QualType Sema::BuildParenType(QualType T) {
1919 return Context.getParenType(T);
1922 /// Given that we're building a pointer or reference to the given
1923 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1926 // Bail out if retention is unrequired or already specified.
1927 if (!type->isObjCLifetimeType() ||
1928 type.getObjCLifetime() != Qualifiers::OCL_None)
1931 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1933 // If the object type is const-qualified, we can safely use
1934 // __unsafe_unretained. This is safe (because there are no read
1935 // barriers), and it'll be safe to coerce anything but __weak* to
1936 // the resulting type.
1937 if (type.isConstQualified()) {
1938 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1940 // Otherwise, check whether the static type does not require
1941 // retaining. This currently only triggers for Class (possibly
1942 // protocol-qualifed, and arrays thereof).
1943 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1944 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1946 // If we are in an unevaluated context, like sizeof, skip adding a
1948 } else if (S.isUnevaluatedContext()) {
1951 // If that failed, give an error and recover using __strong. __strong
1952 // is the option most likely to prevent spurious second-order diagnostics,
1953 // like when binding a reference to a field.
1955 // These types can show up in private ivars in system headers, so
1956 // we need this to not be an error in those cases. Instead we
1958 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1959 S.DelayedDiagnostics.add(
1960 sema::DelayedDiagnostic::makeForbiddenType(loc,
1961 diag::err_arc_indirect_no_ownership, type, isReference));
1963 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1965 implicitLifetime = Qualifiers::OCL_Strong;
1967 assert(implicitLifetime && "didn't infer any lifetime!");
1970 qs.addObjCLifetime(implicitLifetime);
1971 return S.Context.getQualifiedType(type, qs);
1974 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1975 std::string Quals = FnTy->getMethodQuals().getAsString();
1977 switch (FnTy->getRefQualifier()) {
1998 /// Kinds of declarator that cannot contain a qualified function type.
2000 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2001 /// a function type with a cv-qualifier or a ref-qualifier can only appear
2002 /// at the topmost level of a type.
2004 /// Parens and member pointers are permitted. We don't diagnose array and
2005 /// function declarators, because they don't allow function types at all.
2007 /// The values of this enum are used in diagnostics.
2008 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2009 } // end anonymous namespace
2011 /// Check whether the type T is a qualified function type, and if it is,
2012 /// diagnose that it cannot be contained within the given kind of declarator.
2013 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
2014 QualifiedFunctionKind QFK) {
2015 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2016 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2018 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2021 S.Diag(Loc, diag::err_compound_qualified_function_type)
2022 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2023 << getFunctionQualifiersAsString(FPT);
2027 bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
2028 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2030 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2033 Diag(Loc, diag::err_qualified_function_typeid)
2034 << T << getFunctionQualifiersAsString(FPT);
2038 // Helper to deduce addr space of a pointee type in OpenCL mode.
2039 static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
2040 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
2041 !PointeeType->isSamplerT() &&
2042 !PointeeType.hasAddressSpace())
2043 PointeeType = S.getASTContext().getAddrSpaceQualType(
2045 S.getLangOpts().OpenCLCPlusPlus || S.getLangOpts().OpenCLVersion == 200
2046 ? LangAS::opencl_generic
2047 : LangAS::opencl_private);
2051 /// Build a pointer type.
2053 /// \param T The type to which we'll be building a pointer.
2055 /// \param Loc The location of the entity whose type involves this
2056 /// pointer type or, if there is no such entity, the location of the
2057 /// type that will have pointer type.
2059 /// \param Entity The name of the entity that involves the pointer
2062 /// \returns A suitable pointer type, if there are no
2063 /// errors. Otherwise, returns a NULL type.
2064 QualType Sema::BuildPointerType(QualType T,
2065 SourceLocation Loc, DeclarationName Entity) {
2066 if (T->isReferenceType()) {
2067 // C++ 8.3.2p4: There shall be no ... pointers to references ...
2068 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2069 << getPrintableNameForEntity(Entity) << T;
2073 if (T->isFunctionType() && getLangOpts().OpenCL) {
2074 Diag(Loc, diag::err_opencl_function_pointer);
2078 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2081 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2083 // In ARC, it is forbidden to build pointers to unqualified pointers.
2084 if (getLangOpts().ObjCAutoRefCount)
2085 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2087 if (getLangOpts().OpenCL)
2088 T = deduceOpenCLPointeeAddrSpace(*this, T);
2090 // Build the pointer type.
2091 return Context.getPointerType(T);
2094 /// Build a reference type.
2096 /// \param T The type to which we'll be building a reference.
2098 /// \param Loc The location of the entity whose type involves this
2099 /// reference type or, if there is no such entity, the location of the
2100 /// type that will have reference type.
2102 /// \param Entity The name of the entity that involves the reference
2105 /// \returns A suitable reference type, if there are no
2106 /// errors. Otherwise, returns a NULL type.
2107 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2109 DeclarationName Entity) {
2110 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
2111 "Unresolved overloaded function type");
2113 // C++0x [dcl.ref]p6:
2114 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2115 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2116 // type T, an attempt to create the type "lvalue reference to cv TR" creates
2117 // the type "lvalue reference to T", while an attempt to create the type
2118 // "rvalue reference to cv TR" creates the type TR.
2119 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
2121 // C++ [dcl.ref]p4: There shall be no references to references.
2123 // According to C++ DR 106, references to references are only
2124 // diagnosed when they are written directly (e.g., "int & &"),
2125 // but not when they happen via a typedef:
2127 // typedef int& intref;
2128 // typedef intref& intref2;
2130 // Parser::ParseDeclaratorInternal diagnoses the case where
2131 // references are written directly; here, we handle the
2132 // collapsing of references-to-references as described in C++0x.
2133 // DR 106 and 540 introduce reference-collapsing into C++98/03.
2136 // A declarator that specifies the type "reference to cv void"
2138 if (T->isVoidType()) {
2139 Diag(Loc, diag::err_reference_to_void);
2143 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2146 // In ARC, it is forbidden to build references to unqualified pointers.
2147 if (getLangOpts().ObjCAutoRefCount)
2148 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2150 if (getLangOpts().OpenCL)
2151 T = deduceOpenCLPointeeAddrSpace(*this, T);
2153 // Handle restrict on references.
2155 return Context.getLValueReferenceType(T, SpelledAsLValue);
2156 return Context.getRValueReferenceType(T);
2159 /// Build a Read-only Pipe type.
2161 /// \param T The type to which we'll be building a Pipe.
2163 /// \param Loc We do not use it for now.
2165 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2167 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2168 return Context.getReadPipeType(T);
2171 /// Build a Write-only Pipe type.
2173 /// \param T The type to which we'll be building a Pipe.
2175 /// \param Loc We do not use it for now.
2177 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2179 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2180 return Context.getWritePipeType(T);
2183 /// Build a extended int type.
2185 /// \param IsUnsigned Boolean representing the signedness of the type.
2187 /// \param BitWidth Size of this int type in bits, or an expression representing
2190 /// \param Loc Location of the keyword.
2191 QualType Sema::BuildExtIntType(bool IsUnsigned, Expr *BitWidth,
2192 SourceLocation Loc) {
2193 if (BitWidth->isInstantiationDependent())
2194 return Context.getDependentExtIntType(IsUnsigned, BitWidth);
2196 llvm::APSInt Bits(32);
2197 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Bits);
2199 if (ICE.isInvalid())
2202 int64_t NumBits = Bits.getSExtValue();
2203 if (!IsUnsigned && NumBits < 2) {
2204 Diag(Loc, diag::err_ext_int_bad_size) << 0;
2208 if (IsUnsigned && NumBits < 1) {
2209 Diag(Loc, diag::err_ext_int_bad_size) << 1;
2213 if (NumBits > llvm::IntegerType::MAX_INT_BITS) {
2214 Diag(Loc, diag::err_ext_int_max_size) << IsUnsigned
2215 << llvm::IntegerType::MAX_INT_BITS;
2219 return Context.getExtIntType(IsUnsigned, NumBits);
2222 /// Check whether the specified array size makes the array type a VLA. If so,
2223 /// return true, if not, return the size of the array in SizeVal.
2224 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
2225 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2226 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2227 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2229 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
2231 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
2234 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
2235 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2239 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2240 S.LangOpts.GNUMode ||
2241 S.LangOpts.OpenCL).isInvalid();
2244 /// Build an array type.
2246 /// \param T The type of each element in the array.
2248 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2250 /// \param ArraySize Expression describing the size of the array.
2252 /// \param Brackets The range from the opening '[' to the closing ']'.
2254 /// \param Entity The name of the entity that involves the array
2257 /// \returns A suitable array type, if there are no errors. Otherwise,
2258 /// returns a NULL type.
2259 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2260 Expr *ArraySize, unsigned Quals,
2261 SourceRange Brackets, DeclarationName Entity) {
2263 SourceLocation Loc = Brackets.getBegin();
2264 if (getLangOpts().CPlusPlus) {
2265 // C++ [dcl.array]p1:
2266 // T is called the array element type; this type shall not be a reference
2267 // type, the (possibly cv-qualified) type void, a function type or an
2268 // abstract class type.
2270 // C++ [dcl.array]p3:
2271 // When several "array of" specifications are adjacent, [...] only the
2272 // first of the constant expressions that specify the bounds of the arrays
2275 // Note: function types are handled in the common path with C.
2276 if (T->isReferenceType()) {
2277 Diag(Loc, diag::err_illegal_decl_array_of_references)
2278 << getPrintableNameForEntity(Entity) << T;
2282 if (T->isVoidType() || T->isIncompleteArrayType()) {
2283 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2287 if (RequireNonAbstractType(Brackets.getBegin(), T,
2288 diag::err_array_of_abstract_type))
2291 // Mentioning a member pointer type for an array type causes us to lock in
2292 // an inheritance model, even if it's inside an unused typedef.
2293 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2294 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2295 if (!MPTy->getClass()->isDependentType())
2296 (void)isCompleteType(Loc, T);
2299 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2300 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2301 if (RequireCompleteSizedType(Loc, T,
2302 diag::err_array_incomplete_or_sizeless_type))
2306 if (T->isSizelessType()) {
2307 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2311 if (T->isFunctionType()) {
2312 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2313 << getPrintableNameForEntity(Entity) << T;
2317 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2318 // If the element type is a struct or union that contains a variadic
2319 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2320 if (EltTy->getDecl()->hasFlexibleArrayMember())
2321 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2322 } else if (T->isObjCObjectType()) {
2323 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2327 // Do placeholder conversions on the array size expression.
2328 if (ArraySize && ArraySize->hasPlaceholderType()) {
2329 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2330 if (Result.isInvalid()) return QualType();
2331 ArraySize = Result.get();
2334 // Do lvalue-to-rvalue conversions on the array size expression.
2335 if (ArraySize && !ArraySize->isRValue()) {
2336 ExprResult Result = DefaultLvalueConversion(ArraySize);
2337 if (Result.isInvalid())
2340 ArraySize = Result.get();
2343 // C99 6.7.5.2p1: The size expression shall have integer type.
2344 // C++11 allows contextual conversions to such types.
2345 if (!getLangOpts().CPlusPlus11 &&
2346 ArraySize && !ArraySize->isTypeDependent() &&
2347 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2348 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2349 << ArraySize->getType() << ArraySize->getSourceRange();
2353 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2355 if (ASM == ArrayType::Star)
2356 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2358 T = Context.getIncompleteArrayType(T, ASM, Quals);
2359 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2360 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2361 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2362 !T->isConstantSizeType()) ||
2363 isArraySizeVLA(*this, ArraySize, ConstVal)) {
2364 // Even in C++11, don't allow contextual conversions in the array bound
2366 if (getLangOpts().CPlusPlus11 &&
2367 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2368 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2369 << ArraySize->getType() << ArraySize->getSourceRange();
2373 // C99: an array with an element type that has a non-constant-size is a VLA.
2374 // C99: an array with a non-ICE size is a VLA. We accept any expression
2375 // that we can fold to a non-zero positive value as an extension.
2376 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2378 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2379 // have a value greater than zero.
2380 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2382 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2383 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2385 Diag(ArraySize->getBeginLoc(), diag::err_typecheck_negative_array_size)
2386 << ArraySize->getSourceRange();
2389 if (ConstVal == 0) {
2390 // GCC accepts zero sized static arrays. We allow them when
2391 // we're not in a SFINAE context.
2392 Diag(ArraySize->getBeginLoc(), isSFINAEContext()
2393 ? diag::err_typecheck_zero_array_size
2394 : diag::ext_typecheck_zero_array_size)
2395 << ArraySize->getSourceRange();
2396 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2397 !T->isIncompleteType() && !T->isUndeducedType()) {
2398 // Is the array too large?
2399 unsigned ActiveSizeBits
2400 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2401 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2402 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2403 << ConstVal.toString(10) << ArraySize->getSourceRange();
2408 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2411 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2412 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2413 Diag(Loc, diag::err_opencl_vla);
2417 if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2418 // CUDA device code and some other targets don't support VLAs.
2419 targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2420 ? diag::err_cuda_vla
2421 : diag::err_vla_unsupported)
2422 << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2423 ? CurrentCUDATarget()
2424 : CFT_InvalidTarget);
2427 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2428 if (!getLangOpts().C99) {
2429 if (T->isVariableArrayType()) {
2430 // Prohibit the use of VLAs during template argument deduction.
2431 if (isSFINAEContext()) {
2432 Diag(Loc, diag::err_vla_in_sfinae);
2435 // Just extwarn about VLAs.
2437 Diag(Loc, diag::ext_vla);
2438 } else if (ASM != ArrayType::Normal || Quals != 0)
2440 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2441 : diag::ext_c99_array_usage) << ASM;
2444 if (T->isVariableArrayType()) {
2445 // Warn about VLAs for -Wvla.
2446 Diag(Loc, diag::warn_vla_used);
2449 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2450 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2451 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2452 if (getLangOpts().OpenCL) {
2453 const QualType ArrType = Context.getBaseElementType(T);
2454 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2455 ArrType->isSamplerT() || ArrType->isImageType()) {
2456 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2464 QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2465 SourceLocation AttrLoc) {
2466 // The base type must be integer (not Boolean or enumeration) or float, and
2467 // can't already be a vector.
2468 if (!CurType->isDependentType() &&
2469 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2470 (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) {
2471 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2475 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2476 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2477 VectorType::GenericVector);
2479 llvm::APSInt VecSize(32);
2480 if (!SizeExpr->isIntegerConstantExpr(VecSize, Context)) {
2481 Diag(AttrLoc, diag::err_attribute_argument_type)
2482 << "vector_size" << AANT_ArgumentIntegerConstant
2483 << SizeExpr->getSourceRange();
2487 if (CurType->isDependentType())
2488 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2489 VectorType::GenericVector);
2491 // vecSize is specified in bytes - convert to bits.
2492 if (!VecSize.isIntN(61)) {
2493 // Bit size will overflow uint64.
2494 Diag(AttrLoc, diag::err_attribute_size_too_large)
2495 << SizeExpr->getSourceRange() << "vector";
2498 uint64_t VectorSizeBits = VecSize.getZExtValue() * 8;
2499 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2501 if (VectorSizeBits == 0) {
2502 Diag(AttrLoc, diag::err_attribute_zero_size)
2503 << SizeExpr->getSourceRange() << "vector";
2507 if (VectorSizeBits % TypeSize) {
2508 Diag(AttrLoc, diag::err_attribute_invalid_size)
2509 << SizeExpr->getSourceRange();
2513 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2514 Diag(AttrLoc, diag::err_attribute_size_too_large)
2515 << SizeExpr->getSourceRange() << "vector";
2519 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2520 VectorType::GenericVector);
2523 /// Build an ext-vector type.
2525 /// Run the required checks for the extended vector type.
2526 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2527 SourceLocation AttrLoc) {
2528 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2529 // in conjunction with complex types (pointers, arrays, functions, etc.).
2531 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2532 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2533 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2534 // of bool aren't allowed.
2535 if ((!T->isDependentType() && !T->isIntegerType() &&
2536 !T->isRealFloatingType()) ||
2537 T->isBooleanType()) {
2538 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2542 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2543 llvm::APSInt vecSize(32);
2544 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2545 Diag(AttrLoc, diag::err_attribute_argument_type)
2546 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2547 << ArraySize->getSourceRange();
2551 if (!vecSize.isIntN(32)) {
2552 Diag(AttrLoc, diag::err_attribute_size_too_large)
2553 << ArraySize->getSourceRange() << "vector";
2556 // Unlike gcc's vector_size attribute, the size is specified as the
2557 // number of elements, not the number of bytes.
2558 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2560 if (vectorSize == 0) {
2561 Diag(AttrLoc, diag::err_attribute_zero_size)
2562 << ArraySize->getSourceRange() << "vector";
2566 return Context.getExtVectorType(T, vectorSize);
2569 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2572 QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2573 SourceLocation AttrLoc) {
2574 assert(Context.getLangOpts().MatrixTypes &&
2575 "Should never build a matrix type when it is disabled");
2577 // Check element type, if it is not dependent.
2578 if (!ElementTy->isDependentType() &&
2579 !MatrixType::isValidElementType(ElementTy)) {
2580 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2584 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2585 NumRows->isValueDependent() || NumCols->isValueDependent())
2586 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2589 // Both row and column values can only be 20 bit wide currently.
2590 llvm::APSInt ValueRows(32), ValueColumns(32);
2592 bool const RowsIsInteger = NumRows->isIntegerConstantExpr(ValueRows, Context);
2593 bool const ColumnsIsInteger =
2594 NumCols->isIntegerConstantExpr(ValueColumns, Context);
2596 auto const RowRange = NumRows->getSourceRange();
2597 auto const ColRange = NumCols->getSourceRange();
2599 // Both are row and column expressions are invalid.
2600 if (!RowsIsInteger && !ColumnsIsInteger) {
2601 Diag(AttrLoc, diag::err_attribute_argument_type)
2602 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2607 // Only the row expression is invalid.
2608 if (!RowsIsInteger) {
2609 Diag(AttrLoc, diag::err_attribute_argument_type)
2610 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2614 // Only the column expression is invalid.
2615 if (!ColumnsIsInteger) {
2616 Diag(AttrLoc, diag::err_attribute_argument_type)
2617 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2621 // Check the matrix dimensions.
2622 unsigned MatrixRows = static_cast<unsigned>(ValueRows.getZExtValue());
2623 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns.getZExtValue());
2624 if (MatrixRows == 0 && MatrixColumns == 0) {
2625 Diag(AttrLoc, diag::err_attribute_zero_size)
2626 << "matrix" << RowRange << ColRange;
2629 if (MatrixRows == 0) {
2630 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2633 if (MatrixColumns == 0) {
2634 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2637 if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2638 Diag(AttrLoc, diag::err_attribute_size_too_large)
2639 << RowRange << "matrix row";
2642 if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2643 Diag(AttrLoc, diag::err_attribute_size_too_large)
2644 << ColRange << "matrix column";
2647 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2650 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2651 if (T->isArrayType() || T->isFunctionType()) {
2652 Diag(Loc, diag::err_func_returning_array_function)
2653 << T->isFunctionType() << T;
2657 // Functions cannot return half FP.
2658 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2659 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2660 FixItHint::CreateInsertion(Loc, "*");
2664 // Methods cannot return interface types. All ObjC objects are
2665 // passed by reference.
2666 if (T->isObjCObjectType()) {
2667 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2668 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2672 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2673 T.hasNonTrivialToPrimitiveCopyCUnion())
2674 checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
2675 NTCUK_Destruct|NTCUK_Copy);
2677 // C++2a [dcl.fct]p12:
2678 // A volatile-qualified return type is deprecated
2679 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2680 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2685 /// Check the extended parameter information. Most of the necessary
2686 /// checking should occur when applying the parameter attribute; the
2687 /// only other checks required are positional restrictions.
2688 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2689 const FunctionProtoType::ExtProtoInfo &EPI,
2690 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2691 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2693 bool hasCheckedSwiftCall = false;
2694 auto checkForSwiftCC = [&](unsigned paramIndex) {
2695 // Only do this once.
2696 if (hasCheckedSwiftCall) return;
2697 hasCheckedSwiftCall = true;
2698 if (EPI.ExtInfo.getCC() == CC_Swift) return;
2699 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2700 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2703 for (size_t paramIndex = 0, numParams = paramTypes.size();
2704 paramIndex != numParams; ++paramIndex) {
2705 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2706 // Nothing interesting to check for orindary-ABI parameters.
2707 case ParameterABI::Ordinary:
2710 // swift_indirect_result parameters must be a prefix of the function
2712 case ParameterABI::SwiftIndirectResult:
2713 checkForSwiftCC(paramIndex);
2714 if (paramIndex != 0 &&
2715 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2716 != ParameterABI::SwiftIndirectResult) {
2717 S.Diag(getParamLoc(paramIndex),
2718 diag::err_swift_indirect_result_not_first);
2722 case ParameterABI::SwiftContext:
2723 checkForSwiftCC(paramIndex);
2726 // swift_error parameters must be preceded by a swift_context parameter.
2727 case ParameterABI::SwiftErrorResult:
2728 checkForSwiftCC(paramIndex);
2729 if (paramIndex == 0 ||
2730 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2731 ParameterABI::SwiftContext) {
2732 S.Diag(getParamLoc(paramIndex),
2733 diag::err_swift_error_result_not_after_swift_context);
2737 llvm_unreachable("bad ABI kind");
2741 QualType Sema::BuildFunctionType(QualType T,
2742 MutableArrayRef<QualType> ParamTypes,
2743 SourceLocation Loc, DeclarationName Entity,
2744 const FunctionProtoType::ExtProtoInfo &EPI) {
2745 bool Invalid = false;
2747 Invalid |= CheckFunctionReturnType(T, Loc);
2749 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2750 // FIXME: Loc is too inprecise here, should use proper locations for args.
2751 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2752 if (ParamType->isVoidType()) {
2753 Diag(Loc, diag::err_param_with_void_type);
2755 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2756 // Disallow half FP arguments.
2757 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2758 FixItHint::CreateInsertion(Loc, "*");
2762 // C++2a [dcl.fct]p4:
2763 // A parameter with volatile-qualified type is deprecated
2764 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2765 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2767 ParamTypes[Idx] = ParamType;
2770 if (EPI.ExtParameterInfos) {
2771 checkExtParameterInfos(*this, ParamTypes, EPI,
2772 [=](unsigned i) { return Loc; });
2775 if (EPI.ExtInfo.getProducesResult()) {
2776 // This is just a warning, so we can't fail to build if we see it.
2777 checkNSReturnsRetainedReturnType(Loc, T);
2783 return Context.getFunctionType(T, ParamTypes, EPI);
2786 /// Build a member pointer type \c T Class::*.
2788 /// \param T the type to which the member pointer refers.
2789 /// \param Class the class type into which the member pointer points.
2790 /// \param Loc the location where this type begins
2791 /// \param Entity the name of the entity that will have this member pointer type
2793 /// \returns a member pointer type, if successful, or a NULL type if there was
2795 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2797 DeclarationName Entity) {
2798 // Verify that we're not building a pointer to pointer to function with
2799 // exception specification.
2800 if (CheckDistantExceptionSpec(T)) {
2801 Diag(Loc, diag::err_distant_exception_spec);
2805 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2806 // with reference type, or "cv void."
2807 if (T->isReferenceType()) {
2808 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2809 << getPrintableNameForEntity(Entity) << T;
2813 if (T->isVoidType()) {
2814 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2815 << getPrintableNameForEntity(Entity);
2819 if (!Class->isDependentType() && !Class->isRecordType()) {
2820 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2824 // Adjust the default free function calling convention to the default method
2825 // calling convention.
2827 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2828 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2829 if (T->isFunctionType())
2830 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2832 return Context.getMemberPointerType(T, Class.getTypePtr());
2835 /// Build a block pointer type.
2837 /// \param T The type to which we'll be building a block pointer.
2839 /// \param Loc The source location, used for diagnostics.
2841 /// \param Entity The name of the entity that involves the block pointer
2844 /// \returns A suitable block pointer type, if there are no
2845 /// errors. Otherwise, returns a NULL type.
2846 QualType Sema::BuildBlockPointerType(QualType T,
2848 DeclarationName Entity) {
2849 if (!T->isFunctionType()) {
2850 Diag(Loc, diag::err_nonfunction_block_type);
2854 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2857 if (getLangOpts().OpenCL)
2858 T = deduceOpenCLPointeeAddrSpace(*this, T);
2860 return Context.getBlockPointerType(T);
2863 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2864 QualType QT = Ty.get();
2866 if (TInfo) *TInfo = nullptr;
2870 TypeSourceInfo *DI = nullptr;
2871 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2872 QT = LIT->getType();
2873 DI = LIT->getTypeSourceInfo();
2876 if (TInfo) *TInfo = DI;
2880 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2881 Qualifiers::ObjCLifetime ownership,
2882 unsigned chunkIndex);
2884 /// Given that this is the declaration of a parameter under ARC,
2885 /// attempt to infer attributes and such for pointer-to-whatever
2887 static void inferARCWriteback(TypeProcessingState &state,
2888 QualType &declSpecType) {
2889 Sema &S = state.getSema();
2890 Declarator &declarator = state.getDeclarator();
2892 // TODO: should we care about decl qualifiers?
2894 // Check whether the declarator has the expected form. We walk
2895 // from the inside out in order to make the block logic work.
2896 unsigned outermostPointerIndex = 0;
2897 bool isBlockPointer = false;
2898 unsigned numPointers = 0;
2899 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2900 unsigned chunkIndex = i;
2901 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2902 switch (chunk.Kind) {
2903 case DeclaratorChunk::Paren:
2907 case DeclaratorChunk::Reference:
2908 case DeclaratorChunk::Pointer:
2909 // Count the number of pointers. Treat references
2910 // interchangeably as pointers; if they're mis-ordered, normal
2911 // type building will discover that.
2912 outermostPointerIndex = chunkIndex;
2916 case DeclaratorChunk::BlockPointer:
2917 // If we have a pointer to block pointer, that's an acceptable
2918 // indirect reference; anything else is not an application of
2920 if (numPointers != 1) return;
2922 outermostPointerIndex = chunkIndex;
2923 isBlockPointer = true;
2925 // We don't care about pointer structure in return values here.
2928 case DeclaratorChunk::Array: // suppress if written (id[])?
2929 case DeclaratorChunk::Function:
2930 case DeclaratorChunk::MemberPointer:
2931 case DeclaratorChunk::Pipe:
2937 // If we have *one* pointer, then we want to throw the qualifier on
2938 // the declaration-specifiers, which means that it needs to be a
2939 // retainable object type.
2940 if (numPointers == 1) {
2941 // If it's not a retainable object type, the rule doesn't apply.
2942 if (!declSpecType->isObjCRetainableType()) return;
2944 // If it already has lifetime, don't do anything.
2945 if (declSpecType.getObjCLifetime()) return;
2947 // Otherwise, modify the type in-place.
2950 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2951 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2953 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2954 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2956 // If we have *two* pointers, then we want to throw the qualifier on
2957 // the outermost pointer.
2958 } else if (numPointers == 2) {
2959 // If we don't have a block pointer, we need to check whether the
2960 // declaration-specifiers gave us something that will turn into a
2961 // retainable object pointer after we slap the first pointer on it.
2962 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2965 // Look for an explicit lifetime attribute there.
2966 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2967 if (chunk.Kind != DeclaratorChunk::Pointer &&
2968 chunk.Kind != DeclaratorChunk::BlockPointer)
2970 for (const ParsedAttr &AL : chunk.getAttrs())
2971 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2974 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2975 outermostPointerIndex);
2977 // Any other number of pointers/references does not trigger the rule.
2980 // TODO: mark whether we did this inference?
2983 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2984 SourceLocation FallbackLoc,
2985 SourceLocation ConstQualLoc,
2986 SourceLocation VolatileQualLoc,
2987 SourceLocation RestrictQualLoc,
2988 SourceLocation AtomicQualLoc,
2989 SourceLocation UnalignedQualLoc) {
2997 } const QualKinds[5] = {
2998 { "const", DeclSpec::TQ_const, ConstQualLoc },
2999 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3000 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3001 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3002 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3005 SmallString<32> QualStr;
3006 unsigned NumQuals = 0;
3008 FixItHint FixIts[5];
3010 // Build a string naming the redundant qualifiers.
3011 for (auto &E : QualKinds) {
3012 if (Quals & E.Mask) {
3013 if (!QualStr.empty()) QualStr += ' ';
3016 // If we have a location for the qualifier, offer a fixit.
3017 SourceLocation QualLoc = E.Loc;
3018 if (QualLoc.isValid()) {
3019 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3020 if (Loc.isInvalid() ||
3021 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
3029 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3030 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3033 // Diagnose pointless type qualifiers on the return type of a function.
3034 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3036 unsigned FunctionChunkIndex) {
3037 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
3038 // FIXME: TypeSourceInfo doesn't preserve location information for
3040 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3041 RetTy.getLocalCVRQualifiers(),
3042 D.getIdentifierLoc());
3046 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3047 End = D.getNumTypeObjects();
3048 OuterChunkIndex != End; ++OuterChunkIndex) {
3049 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3050 switch (OuterChunk.Kind) {
3051 case DeclaratorChunk::Paren:
3054 case DeclaratorChunk::Pointer: {
3055 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3056 S.diagnoseIgnoredQualifiers(
3057 diag::warn_qual_return_type,
3060 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
3061 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
3062 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
3063 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
3064 SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
3068 case DeclaratorChunk::Function:
3069 case DeclaratorChunk::BlockPointer:
3070 case DeclaratorChunk::Reference:
3071 case DeclaratorChunk::Array:
3072 case DeclaratorChunk::MemberPointer:
3073 case DeclaratorChunk::Pipe:
3074 // FIXME: We can't currently provide an accurate source location and a
3075 // fix-it hint for these.
3076 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3077 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3078 RetTy.getCVRQualifiers() | AtomicQual,
3079 D.getIdentifierLoc());
3083 llvm_unreachable("unknown declarator chunk kind");
3086 // If the qualifiers come from a conversion function type, don't diagnose
3087 // them -- they're not necessarily redundant, since such a conversion
3088 // operator can be explicitly called as "x.operator const int()".
3089 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3092 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3093 // which are present there.
3094 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3095 D.getDeclSpec().getTypeQualifiers(),
3096 D.getIdentifierLoc(),
3097 D.getDeclSpec().getConstSpecLoc(),
3098 D.getDeclSpec().getVolatileSpecLoc(),
3099 D.getDeclSpec().getRestrictSpecLoc(),
3100 D.getDeclSpec().getAtomicSpecLoc(),
3101 D.getDeclSpec().getUnalignedSpecLoc());
3104 static void CopyTypeConstraintFromAutoType(Sema &SemaRef, const AutoType *Auto,
3105 AutoTypeLoc AutoLoc,
3106 TemplateTypeParmDecl *TP,
3107 SourceLocation EllipsisLoc) {
3109 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3110 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx)
3111 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3113 SemaRef.AttachTypeConstraint(
3114 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3115 AutoLoc.getNamedConcept(),
3116 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr, TP, EllipsisLoc);
3119 static QualType InventTemplateParameter(
3120 TypeProcessingState &state, QualType T, TypeSourceInfo *TSI, AutoType *Auto,
3121 InventedTemplateParameterInfo &Info) {
3122 Sema &S = state.getSema();
3123 Declarator &D = state.getDeclarator();
3125 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3126 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3127 const bool IsParameterPack = D.hasEllipsis();
3129 // If auto is mentioned in a lambda parameter or abbreviated function
3130 // template context, convert it to a template parameter type.
3132 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3133 // template parameter type. Template parameters are temporarily added
3134 // to the TU until the associated TemplateDecl is created.
3135 TemplateTypeParmDecl *InventedTemplateParam =
3136 TemplateTypeParmDecl::Create(
3137 S.Context, S.Context.getTranslationUnitDecl(),
3138 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3139 /*NameLoc=*/D.getIdentifierLoc(),
3140 TemplateParameterDepth, AutoParameterPosition,
3141 S.InventAbbreviatedTemplateParameterTypeName(
3142 D.getIdentifier(), AutoParameterPosition), false,
3143 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3144 InventedTemplateParam->setImplicit();
3145 Info.TemplateParams.push_back(InventedTemplateParam);
3146 // Attach type constraints
3147 if (Auto->isConstrained()) {
3149 CopyTypeConstraintFromAutoType(
3150 S, Auto, TSI->getTypeLoc().getContainedAutoTypeLoc(),
3151 InventedTemplateParam, D.getEllipsisLoc());
3153 TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3154 TemplateArgumentListInfo TemplateArgsInfo;
3155 if (TemplateId->LAngleLoc.isValid()) {
3156 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3157 TemplateId->NumArgs);
3158 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3160 S.AttachTypeConstraint(
3161 D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3162 DeclarationNameInfo(DeclarationName(TemplateId->Name),
3163 TemplateId->TemplateNameLoc),
3164 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()),
3165 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3166 InventedTemplateParam, D.getEllipsisLoc());
3170 // If TSI is nullptr, this is a constrained declspec auto and the type
3171 // constraint will be attached later in TypeSpecLocFiller
3173 // Replace the 'auto' in the function parameter with this invented
3174 // template type parameter.
3175 // FIXME: Retain some type sugar to indicate that this was written
3177 return state.ReplaceAutoType(
3178 T, QualType(InventedTemplateParam->getTypeForDecl(), 0));
3181 static TypeSourceInfo *
3182 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3183 QualType T, TypeSourceInfo *ReturnTypeInfo);
3185 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3186 TypeSourceInfo *&ReturnTypeInfo) {
3187 Sema &SemaRef = state.getSema();
3188 Declarator &D = state.getDeclarator();
3190 ReturnTypeInfo = nullptr;
3192 // The TagDecl owned by the DeclSpec.
3193 TagDecl *OwnedTagDecl = nullptr;
3195 switch (D.getName().getKind()) {
3196 case UnqualifiedIdKind::IK_ImplicitSelfParam:
3197 case UnqualifiedIdKind::IK_OperatorFunctionId:
3198 case UnqualifiedIdKind::IK_Identifier:
3199 case UnqualifiedIdKind::IK_LiteralOperatorId:
3200 case UnqualifiedIdKind::IK_TemplateId:
3201 T = ConvertDeclSpecToType(state);
3203 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3204 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3205 // Owned declaration is embedded in declarator.
3206 OwnedTagDecl->setEmbeddedInDeclarator(true);
3210 case UnqualifiedIdKind::IK_ConstructorName:
3211 case UnqualifiedIdKind::IK_ConstructorTemplateId:
3212 case UnqualifiedIdKind::IK_DestructorName:
3213 // Constructors and destructors don't have return types. Use
3215 T = SemaRef.Context.VoidTy;
3216 processTypeAttrs(state, T, TAL_DeclSpec,
3217 D.getMutableDeclSpec().getAttributes());
3220 case UnqualifiedIdKind::IK_DeductionGuideName:
3221 // Deduction guides have a trailing return type and no type in their
3222 // decl-specifier sequence. Use a placeholder return type for now.
3223 T = SemaRef.Context.DependentTy;
3226 case UnqualifiedIdKind::IK_ConversionFunctionId:
3227 // The result type of a conversion function is the type that it
3229 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3234 if (!D.getAttributes().empty())
3235 distributeTypeAttrsFromDeclarator(state, T);
3237 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3238 if (DeducedType *Deduced = T->getContainedDeducedType()) {
3239 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3242 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3243 // class template argument deduction)?
3244 bool IsCXXAutoType =
3245 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3246 bool IsDeducedReturnType = false;
3248 switch (D.getContext()) {
3249 case DeclaratorContext::LambdaExprContext:
3250 // Declared return type of a lambda-declarator is implicit and is always
3253 case DeclaratorContext::ObjCParameterContext:
3254 case DeclaratorContext::ObjCResultContext:
3257 case DeclaratorContext::RequiresExprContext:
3260 case DeclaratorContext::PrototypeContext:
3261 case DeclaratorContext::LambdaExprParameterContext: {
3262 InventedTemplateParameterInfo *Info = nullptr;
3263 if (D.getContext() == DeclaratorContext::PrototypeContext) {
3264 // With concepts we allow 'auto' in function parameters.
3265 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3266 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3269 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3272 } else if (D.hasTrailingReturnType()) {
3273 // This might be OK, but we'll need to convert the trailing return
3278 Info = &SemaRef.InventedParameterInfos.back();
3280 // In C++14, generic lambdas allow 'auto' in their parameters.
3281 if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto ||
3282 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3286 Info = SemaRef.getCurLambda();
3287 assert(Info && "No LambdaScopeInfo on the stack!");
3289 T = InventTemplateParameter(state, T, nullptr, Auto, *Info);
3292 case DeclaratorContext::MemberContext: {
3293 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
3294 D.isFunctionDeclarator())
3296 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3297 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3298 Error = 6; // Interface member.
3300 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3301 case TTK_Enum: llvm_unreachable("unhandled tag kind");
3302 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
3303 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
3304 case TTK_Class: Error = 5; /* Class member */ break;
3305 case TTK_Interface: Error = 6; /* Interface member */ break;
3308 if (D.getDeclSpec().isFriendSpecified())
3309 Error = 20; // Friend type
3312 case DeclaratorContext::CXXCatchContext:
3313 case DeclaratorContext::ObjCCatchContext:
3314 Error = 7; // Exception declaration
3316 case DeclaratorContext::TemplateParamContext:
3317 if (isa<DeducedTemplateSpecializationType>(Deduced))
3318 Error = 19; // Template parameter
3319 else if (!SemaRef.getLangOpts().CPlusPlus17)
3320 Error = 8; // Template parameter (until C++17)
3322 case DeclaratorContext::BlockLiteralContext:
3323 Error = 9; // Block literal
3325 case DeclaratorContext::TemplateArgContext:
3326 // Within a template argument list, a deduced template specialization
3327 // type will be reinterpreted as a template template argument.
3328 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3329 !D.getNumTypeObjects() &&
3330 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3333 case DeclaratorContext::TemplateTypeArgContext:
3334 Error = 10; // Template type argument
3336 case DeclaratorContext::AliasDeclContext:
3337 case DeclaratorContext::AliasTemplateContext:
3338 Error = 12; // Type alias
3340 case DeclaratorContext::TrailingReturnContext:
3341 case DeclaratorContext::TrailingReturnVarContext:
3342 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3343 Error = 13; // Function return type
3344 IsDeducedReturnType = true;
3346 case DeclaratorContext::ConversionIdContext:
3347 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3348 Error = 14; // conversion-type-id
3349 IsDeducedReturnType = true;
3351 case DeclaratorContext::FunctionalCastContext:
3352 if (isa<DeducedTemplateSpecializationType>(Deduced))
3355 case DeclaratorContext::TypeNameContext:
3356 Error = 15; // Generic
3358 case DeclaratorContext::FileContext:
3359 case DeclaratorContext::BlockContext:
3360 case DeclaratorContext::ForContext:
3361 case DeclaratorContext::InitStmtContext:
3362 case DeclaratorContext::ConditionContext:
3363 // FIXME: P0091R3 (erroneously) does not permit class template argument
3364 // deduction in conditions, for-init-statements, and other declarations
3365 // that are not simple-declarations.
3367 case DeclaratorContext::CXXNewContext:
3368 // FIXME: P0091R3 does not permit class template argument deduction here,
3369 // but we follow GCC and allow it anyway.
3370 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3371 Error = 17; // 'new' type
3373 case DeclaratorContext::KNRTypeListContext:
3374 Error = 18; // K&R function parameter
3378 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3381 // In Objective-C it is an error to use 'auto' on a function declarator
3382 // (and everywhere for '__auto_type').
3383 if (D.isFunctionDeclarator() &&
3384 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3387 bool HaveTrailing = false;
3389 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
3390 // contains a trailing return type. That is only legal at the outermost
3391 // level. Check all declarator chunks (outermost first) anyway, to give
3392 // better diagnostics.
3393 // We don't support '__auto_type' with trailing return types.
3394 // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
3395 if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
3396 D.hasTrailingReturnType()) {
3397 HaveTrailing = true;
3401 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3402 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3403 AutoRange = D.getName().getSourceRange();
3408 switch (Auto->getKeyword()) {
3409 case AutoTypeKeyword::Auto: Kind = 0; break;
3410 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3411 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3414 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3415 "unknown auto type");
3419 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3420 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3422 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3423 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3424 << QualType(Deduced, 0) << AutoRange;
3425 if (auto *TD = TN.getAsTemplateDecl())
3426 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3428 T = SemaRef.Context.IntTy;
3429 D.setInvalidType(true);
3430 } else if (Auto && !HaveTrailing &&
3431 D.getContext() != DeclaratorContext::LambdaExprContext) {
3432 // If there was a trailing return type, we already got
3433 // warn_cxx98_compat_trailing_return_type in the parser.
3434 SemaRef.Diag(AutoRange.getBegin(),
3436 DeclaratorContext::LambdaExprParameterContext
3437 ? diag::warn_cxx11_compat_generic_lambda
3438 : IsDeducedReturnType
3439 ? diag::warn_cxx11_compat_deduced_return_type
3440 : diag::warn_cxx98_compat_auto_type_specifier)
3445 if (SemaRef.getLangOpts().CPlusPlus &&
3446 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3447 // Check the contexts where C++ forbids the declaration of a new class
3448 // or enumeration in a type-specifier-seq.
3449 unsigned DiagID = 0;
3450 switch (D.getContext()) {
3451 case DeclaratorContext::TrailingReturnContext:
3452 case DeclaratorContext::TrailingReturnVarContext:
3453 // Class and enumeration definitions are syntactically not allowed in
3454 // trailing return types.
3455 llvm_unreachable("parser should not have allowed this");
3457 case DeclaratorContext::FileContext:
3458 case DeclaratorContext::MemberContext:
3459 case DeclaratorContext::BlockContext:
3460 case DeclaratorContext::ForContext:
3461 case DeclaratorContext::InitStmtContext:
3462 case DeclaratorContext::BlockLiteralContext:
3463 case DeclaratorContext::LambdaExprContext:
3464 // C++11 [dcl.type]p3:
3465 // A type-specifier-seq shall not define a class or enumeration unless
3466 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3467 // the declaration of a template-declaration.
3468 case DeclaratorContext::AliasDeclContext:
3470 case DeclaratorContext::AliasTemplateContext:
3471 DiagID = diag::err_type_defined_in_alias_template;
3473 case DeclaratorContext::TypeNameContext:
3474 case DeclaratorContext::FunctionalCastContext:
3475 case DeclaratorContext::ConversionIdContext:
3476 case DeclaratorContext::TemplateParamContext:
3477 case DeclaratorContext::CXXNewContext:
3478 case DeclaratorContext::CXXCatchContext:
3479 case DeclaratorContext::ObjCCatchContext:
3480 case DeclaratorContext::TemplateArgContext:
3481 case DeclaratorContext::TemplateTypeArgContext:
3482 DiagID = diag::err_type_defined_in_type_specifier;
3484 case DeclaratorContext::PrototypeContext:
3485 case DeclaratorContext::LambdaExprParameterContext:
3486 case DeclaratorContext::ObjCParameterContext:
3487 case DeclaratorContext::ObjCResultContext:
3488 case DeclaratorContext::KNRTypeListContext:
3489 case DeclaratorContext::RequiresExprContext:
3491 // Types shall not be defined in return or parameter types.
3492 DiagID = diag::err_type_defined_in_param_type;
3494 case DeclaratorContext::ConditionContext:
3496 // The type-specifier-seq shall not contain typedef and shall not declare
3497 // a new class or enumeration.
3498 DiagID = diag::err_type_defined_in_condition;
3503 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3504 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3505 D.setInvalidType(true);
3509 assert(!T.isNull() && "This function should not return a null type");
3513 /// Produce an appropriate diagnostic for an ambiguity between a function
3514 /// declarator and a C++ direct-initializer.
3515 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3516 DeclaratorChunk &DeclType, QualType RT) {
3517 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3518 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3520 // If the return type is void there is no ambiguity.
3521 if (RT->isVoidType())
3524 // An initializer for a non-class type can have at most one argument.
3525 if (!RT->isRecordType() && FTI.NumParams > 1)
3528 // An initializer for a reference must have exactly one argument.
3529 if (RT->isReferenceType() && FTI.NumParams != 1)
3532 // Only warn if this declarator is declaring a function at block scope, and
3533 // doesn't have a storage class (such as 'extern') specified.
3534 if (!D.isFunctionDeclarator() ||
3535 D.getFunctionDefinitionKind() != FDK_Declaration ||
3536 !S.CurContext->isFunctionOrMethod() ||
3537 D.getDeclSpec().getStorageClassSpec()
3538 != DeclSpec::SCS_unspecified)
3541 // Inside a condition, a direct initializer is not permitted. We allow one to
3542 // be parsed in order to give better diagnostics in condition parsing.
3543 if (D.getContext() == DeclaratorContext::ConditionContext)
3546 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3548 S.Diag(DeclType.Loc,
3549 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3550 : diag::warn_empty_parens_are_function_decl)
3553 // If the declaration looks like:
3556 // and name lookup finds a function named 'f', then the ',' was
3557 // probably intended to be a ';'.
3558 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3559 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3560 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3561 if (Comma.getFileID() != Name.getFileID() ||
3562 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3563 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3564 Sema::LookupOrdinaryName);
3565 if (S.LookupName(Result, S.getCurScope()))
3566 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3567 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3568 << D.getIdentifier();
3569 Result.suppressDiagnostics();
3573 if (FTI.NumParams > 0) {
3574 // For a declaration with parameters, eg. "T var(T());", suggest adding
3575 // parens around the first parameter to turn the declaration into a
3576 // variable declaration.
3577 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3578 SourceLocation B = Range.getBegin();
3579 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3580 // FIXME: Maybe we should suggest adding braces instead of parens
3581 // in C++11 for classes that don't have an initializer_list constructor.
3582 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3583 << FixItHint::CreateInsertion(B, "(")
3584 << FixItHint::CreateInsertion(E, ")");
3586 // For a declaration without parameters, eg. "T var();", suggest replacing
3587 // the parens with an initializer to turn the declaration into a variable
3589 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3591 // Empty parens mean value-initialization, and no parens mean
3592 // default initialization. These are equivalent if the default
3593 // constructor is user-provided or if zero-initialization is a
3595 if (RD && RD->hasDefinition() &&
3596 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3597 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3598 << FixItHint::CreateRemoval(ParenRange);
3601 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3602 if (Init.empty() && S.LangOpts.CPlusPlus11)
3605 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3606 << FixItHint::CreateReplacement(ParenRange, Init);
3611 /// Produce an appropriate diagnostic for a declarator with top-level
3613 static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3614 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3615 assert(Paren.Kind == DeclaratorChunk::Paren &&
3616 "do not have redundant top-level parentheses");
3618 // This is a syntactic check; we're not interested in cases that arise
3619 // during template instantiation.
3620 if (S.inTemplateInstantiation())
3623 // Check whether this could be intended to be a construction of a temporary
3624 // object in C++ via a function-style cast.
3625 bool CouldBeTemporaryObject =
3626 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3627 !D.isInvalidType() && D.getIdentifier() &&
3628 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3629 (T->isRecordType() || T->isDependentType()) &&
3630 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3632 bool StartsWithDeclaratorId = true;
3633 for (auto &C : D.type_objects()) {
3635 case DeclaratorChunk::Paren:
3639 case DeclaratorChunk::Pointer:
3640 StartsWithDeclaratorId = false;
3643 case DeclaratorChunk::Array:
3645 CouldBeTemporaryObject = false;
3648 case DeclaratorChunk::Reference:
3649 // FIXME: Suppress the warning here if there is no initializer; we're
3650 // going to give an error anyway.
3651 // We assume that something like 'T (&x) = y;' is highly likely to not
3652 // be intended to be a temporary object.
3653 CouldBeTemporaryObject = false;
3654 StartsWithDeclaratorId = false;
3657 case DeclaratorChunk::Function:
3658 // In a new-type-id, function chunks require parentheses.
3659 if (D.getContext() == DeclaratorContext::CXXNewContext)
3661 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3662 // redundant-parens warning, but we don't know whether the function
3663 // chunk was syntactically valid as an expression here.
3664 CouldBeTemporaryObject = false;
3667 case DeclaratorChunk::BlockPointer:
3668 case DeclaratorChunk::MemberPointer:
3669 case DeclaratorChunk::Pipe:
3670 // These cannot appear in expressions.
3671 CouldBeTemporaryObject = false;
3672 StartsWithDeclaratorId = false;
3677 // FIXME: If there is an initializer, assume that this is not intended to be
3678 // a construction of a temporary object.
3680 // Check whether the name has already been declared; if not, this is not a
3681 // function-style cast.
3682 if (CouldBeTemporaryObject) {
3683 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3684 Sema::LookupOrdinaryName);
3685 if (!S.LookupName(Result, S.getCurScope()))
3686 CouldBeTemporaryObject = false;
3687 Result.suppressDiagnostics();
3690 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3692 if (!CouldBeTemporaryObject) {
3693 // If we have A (::B), the parentheses affect the meaning of the program.
3694 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3695 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3696 // formally unambiguous.
3697 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3698 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3699 NNS = NNS->getPrefix()) {
3700 if (NNS->getKind() == NestedNameSpecifier::Global)
3705 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3706 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3707 << FixItHint::CreateRemoval(Paren.EndLoc);
3711 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3712 << ParenRange << D.getIdentifier();
3713 auto *RD = T->getAsCXXRecordDecl();
3714 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3715 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3716 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3717 << D.getIdentifier();
3718 // FIXME: A cast to void is probably a better suggestion in cases where it's
3719 // valid (when there is no initializer and we're not in a condition).
3720 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3721 << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
3722 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
3723 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3724 << FixItHint::CreateRemoval(Paren.Loc)
3725 << FixItHint::CreateRemoval(Paren.EndLoc);
3728 /// Helper for figuring out the default CC for a function declarator type. If
3729 /// this is the outermost chunk, then we can determine the CC from the
3730 /// declarator context. If not, then this could be either a member function
3731 /// type or normal function type.
3732 static CallingConv getCCForDeclaratorChunk(
3733 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3734 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3735 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3737 // Check for an explicit CC attribute.
3738 for (const ParsedAttr &AL : AttrList) {
3739 switch (AL.getKind()) {
3740 CALLING_CONV_ATTRS_CASELIST : {
3741 // Ignore attributes that don't validate or can't apply to the
3742 // function type. We'll diagnose the failure to apply them in
3743 // handleFunctionTypeAttr.
3745 if (!S.CheckCallingConvAttr(AL, CC) &&
3746 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3757 bool IsCXXInstanceMethod = false;
3759 if (S.getLangOpts().CPlusPlus) {
3760 // Look inwards through parentheses to see if this chunk will form a
3761 // member pointer type or if we're the declarator. Any type attributes
3762 // between here and there will override the CC we choose here.
3763 unsigned I = ChunkIndex;
3764 bool FoundNonParen = false;
3765 while (I && !FoundNonParen) {
3767 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3768 FoundNonParen = true;
3771 if (FoundNonParen) {
3772 // If we're not the declarator, we're a regular function type unless we're
3773 // in a member pointer.
3774 IsCXXInstanceMethod =
3775 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3776 } else if (D.getContext() == DeclaratorContext::LambdaExprContext) {
3777 // This can only be a call operator for a lambda, which is an instance
3779 IsCXXInstanceMethod = true;
3781 // We're the innermost decl chunk, so must be a function declarator.
3782 assert(D.isFunctionDeclarator());
3784 // If we're inside a record, we're declaring a method, but it could be
3785 // explicitly or implicitly static.
3786 IsCXXInstanceMethod =
3787 D.isFirstDeclarationOfMember() &&
3788 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3789 !D.isStaticMember();
3793 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3794 IsCXXInstanceMethod);
3796 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3797 // and AMDGPU targets, hence it cannot be treated as a calling
3798 // convention attribute. This is the simplest place to infer
3799 // calling convention for OpenCL kernels.
3800 if (S.getLangOpts().OpenCL) {
3801 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3802 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
3803 CC = CC_OpenCLKernel;
3813 /// A simple notion of pointer kinds, which matches up with the various
3814 /// pointer declarators.
3815 enum class SimplePointerKind {
3821 } // end anonymous namespace
3823 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3824 switch (nullability) {
3825 case NullabilityKind::NonNull:
3826 if (!Ident__Nonnull)
3827 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3828 return Ident__Nonnull;
3830 case NullabilityKind::Nullable:
3831 if (!Ident__Nullable)
3832 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3833 return Ident__Nullable;
3835 case NullabilityKind::Unspecified:
3836 if (!Ident__Null_unspecified)
3837 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3838 return Ident__Null_unspecified;
3840 llvm_unreachable("Unknown nullability kind.");
3843 /// Retrieve the identifier "NSError".
3844 IdentifierInfo *Sema::getNSErrorIdent() {
3846 Ident_NSError = PP.getIdentifierInfo("NSError");
3848 return Ident_NSError;
3851 /// Check whether there is a nullability attribute of any kind in the given
3853 static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3854 for (const ParsedAttr &AL : attrs) {
3855 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3856 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3857 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3865 /// Describes the kind of a pointer a declarator describes.
3866 enum class PointerDeclaratorKind {
3869 // Single-level pointer.
3871 // Multi-level pointer (of any pointer kind).
3874 MaybePointerToCFRef,
3878 NSErrorPointerPointer,
3881 /// Describes a declarator chunk wrapping a pointer that marks inference as
3883 // These values must be kept in sync with diagnostics.
3884 enum class PointerWrappingDeclaratorKind {
3885 /// Pointer is top-level.
3887 /// Pointer is an array element.
3889 /// Pointer is the referent type of a C++ reference.
3892 } // end anonymous namespace
3894 /// Classify the given declarator, whose type-specified is \c type, based on
3895 /// what kind of pointer it refers to.
3897 /// This is used to determine the default nullability.
3898 static PointerDeclaratorKind
3899 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
3900 PointerWrappingDeclaratorKind &wrappingKind) {
3901 unsigned numNormalPointers = 0;
3903 // For any dependent type, we consider it a non-pointer.
3904 if (type->isDependentType())
3905 return PointerDeclaratorKind::NonPointer;
3907 // Look through the declarator chunks to identify pointers.
3908 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3909 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3910 switch (chunk.Kind) {
3911 case DeclaratorChunk::Array:
3912 if (numNormalPointers == 0)
3913 wrappingKind = PointerWrappingDeclaratorKind::Array;
3916 case DeclaratorChunk::Function:
3917 case DeclaratorChunk::Pipe:
3920 case DeclaratorChunk::BlockPointer:
3921 case DeclaratorChunk::MemberPointer:
3922 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3923 : PointerDeclaratorKind::SingleLevelPointer;
3925 case DeclaratorChunk::Paren:
3928 case DeclaratorChunk::Reference:
3929 if (numNormalPointers == 0)
3930 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3933 case DeclaratorChunk::Pointer:
3934 ++numNormalPointers;
3935 if (numNormalPointers > 2)
3936 return PointerDeclaratorKind::MultiLevelPointer;
3941 // Then, dig into the type specifier itself.
3942 unsigned numTypeSpecifierPointers = 0;
3944 // Decompose normal pointers.
3945 if (auto ptrType = type->getAs<PointerType>()) {
3946 ++numNormalPointers;
3948 if (numNormalPointers > 2)
3949 return PointerDeclaratorKind::MultiLevelPointer;
3951 type = ptrType->getPointeeType();
3952 ++numTypeSpecifierPointers;
3956 // Decompose block pointers.
3957 if (type->getAs<BlockPointerType>()) {
3958 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3959 : PointerDeclaratorKind::SingleLevelPointer;
3962 // Decompose member pointers.
3963 if (type->getAs<MemberPointerType>()) {
3964 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3965 : PointerDeclaratorKind::SingleLevelPointer;
3968 // Look at Objective-C object pointers.
3969 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3970 ++numNormalPointers;
3971 ++numTypeSpecifierPointers;
3973 // If this is NSError**, report that.
3974 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3975 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3976 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3977 return PointerDeclaratorKind::NSErrorPointerPointer;
3984 // Look at Objective-C class types.
3985 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3986 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3987 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3988 return PointerDeclaratorKind::NSErrorPointerPointer;
3994 // If at this point we haven't seen a pointer, we won't see one.
3995 if (numNormalPointers == 0)
3996 return PointerDeclaratorKind::NonPointer;
3998 if (auto recordType = type->getAs<RecordType>()) {
3999 RecordDecl *recordDecl = recordType->getDecl();
4001 bool isCFError = false;
4003 // If we already know about CFError, test it directly.
4004 isCFError = (S.CFError == recordDecl);
4006 // Check whether this is CFError, which we identify based on its bridge
4007 // to NSError. CFErrorRef used to be declared with "objc_bridge" but is
4008 // now declared with "objc_bridge_mutable", so look for either one of
4009 // the two attributes.
4010 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
4011 IdentifierInfo *bridgedType = nullptr;
4012 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>())
4013 bridgedType = bridgeAttr->getBridgedType();
4014 else if (auto bridgeAttr =
4015 recordDecl->getAttr<ObjCBridgeMutableAttr>())
4016 bridgedType = bridgeAttr->getBridgedType();
4018 if (bridgedType == S.getNSErrorIdent()) {
4019 S.CFError = recordDecl;
4025 // If this is CFErrorRef*, report it as such.
4026 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4027 return PointerDeclaratorKind::CFErrorRefPointer;
4035 switch (numNormalPointers) {
4037 return PointerDeclaratorKind::NonPointer;
4040 return PointerDeclaratorKind::SingleLevelPointer;
4043 return PointerDeclaratorKind::MaybePointerToCFRef;
4046 return PointerDeclaratorKind::MultiLevelPointer;
4050 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4051 SourceLocation loc) {
4052 // If we're anywhere in a function, method, or closure context, don't perform
4053 // completeness checks.
4054 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4055 if (ctx->isFunctionOrMethod())
4058 if (ctx->isFileContext())
4062 // We only care about the expansion location.
4063 loc = S.SourceMgr.getExpansionLoc(loc);
4064 FileID file = S.SourceMgr.getFileID(loc);
4065 if (file.isInvalid())
4068 // Retrieve file information.
4069 bool invalid = false;
4070 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4071 if (invalid || !sloc.isFile())
4074 // We don't want to perform completeness checks on the main file or in
4076 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4077 if (fileInfo.getIncludeLoc().isInvalid())
4079 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4080 S.Diags.getSuppressSystemWarnings()) {
4087 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4088 /// taking into account whitespace before and after.
4089 static void fixItNullability(Sema &S, DiagnosticBuilder &Diag,
4090 SourceLocation PointerLoc,
4091 NullabilityKind Nullability) {
4092 assert(PointerLoc.isValid());
4093 if (PointerLoc.isMacroID())
4096 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4097 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4100 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4104 SmallString<32> InsertionTextBuf{" "};
4105 InsertionTextBuf += getNullabilitySpelling(Nullability);
4106 InsertionTextBuf += " ";
4107 StringRef InsertionText = InsertionTextBuf.str();
4109 if (isWhitespace(*NextChar)) {
4110 InsertionText = InsertionText.drop_back();
4111 } else if (NextChar[-1] == '[') {
4112 if (NextChar[0] == ']')
4113 InsertionText = InsertionText.drop_back().drop_front();
4115 InsertionText = InsertionText.drop_front();
4116 } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
4117 !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
4118 InsertionText = InsertionText.drop_back().drop_front();
4121 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4124 static void emitNullabilityConsistencyWarning(Sema &S,
4125 SimplePointerKind PointerKind,
4126 SourceLocation PointerLoc,
4127 SourceLocation PointerEndLoc) {
4128 assert(PointerLoc.isValid());
4130 if (PointerKind == SimplePointerKind::Array) {
4131 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4133 S.Diag(PointerLoc, diag::warn_nullability_missing)
4134 << static_cast<unsigned>(PointerKind);
4137 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4138 if (FixItLoc.isMacroID())
4141 auto addFixIt = [&](NullabilityKind Nullability) {
4142 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4143 Diag << static_cast<unsigned>(Nullability);
4144 Diag << static_cast<unsigned>(PointerKind);
4145 fixItNullability(S, Diag, FixItLoc, Nullability);
4147 addFixIt(NullabilityKind::Nullable);
4148 addFixIt(NullabilityKind::NonNull);
4151 /// Complains about missing nullability if the file containing \p pointerLoc
4152 /// has other uses of nullability (either the keywords or the \c assume_nonnull
4155 /// If the file has \e not seen other uses of nullability, this particular
4156 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4158 checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4159 SourceLocation pointerLoc,
4160 SourceLocation pointerEndLoc = SourceLocation()) {
4161 // Determine which file we're performing consistency checking for.
4162 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4163 if (file.isInvalid())
4166 // If we haven't seen any type nullability in this file, we won't warn now
4168 FileNullability &fileNullability = S.NullabilityMap[file];
4169 if (!fileNullability.SawTypeNullability) {
4170 // If this is the first pointer declarator in the file, and the appropriate
4171 // warning is on, record it in case we need to diagnose it retroactively.
4172 diag::kind diagKind;
4173 if (pointerKind == SimplePointerKind::Array)
4174 diagKind = diag::warn_nullability_missing_array;
4176 diagKind = diag::warn_nullability_missing;
4178 if (fileNullability.PointerLoc.isInvalid() &&
4179 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4180 fileNullability.PointerLoc = pointerLoc;
4181 fileNullability.PointerEndLoc = pointerEndLoc;
4182 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4188 // Complain about missing nullability.
4189 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4192 /// Marks that a nullability feature has been used in the file containing
4195 /// If this file already had pointer types in it that were missing nullability,
4196 /// the first such instance is retroactively diagnosed.
4198 /// \sa checkNullabilityConsistency
4199 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4200 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4201 if (file.isInvalid())
4204 FileNullability &fileNullability = S.NullabilityMap[file];
4205 if (fileNullability.SawTypeNullability)
4207 fileNullability.SawTypeNullability = true;
4209 // If we haven't seen any type nullability before, now we have. Retroactively
4210 // diagnose the first unannotated pointer, if there was one.
4211 if (fileNullability.PointerLoc.isInvalid())
4214 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4215 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4216 fileNullability.PointerEndLoc);
4219 /// Returns true if any of the declarator chunks before \p endIndex include a
4220 /// level of indirection: array, pointer, reference, or pointer-to-member.
4222 /// Because declarator chunks are stored in outer-to-inner order, testing
4223 /// every chunk before \p endIndex is testing all chunks that embed the current
4224 /// chunk as part of their type.
4226 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4227 /// end index, in which case all chunks are tested.
4228 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4229 unsigned i = endIndex;
4231 // Walk outwards along the declarator chunks.
4233 const DeclaratorChunk &DC = D.getTypeObject(i);
4235 case DeclaratorChunk::Paren:
4237 case DeclaratorChunk::Array:
4238 case DeclaratorChunk::Pointer:
4239 case DeclaratorChunk::Reference:
4240 case DeclaratorChunk::MemberPointer:
4242 case DeclaratorChunk::Function:
4243 case DeclaratorChunk::BlockPointer:
4244 case DeclaratorChunk::Pipe:
4245 // These are invalid anyway, so just ignore.
4252 static bool IsNoDerefableChunk(DeclaratorChunk Chunk) {
4253 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4254 Chunk.Kind == DeclaratorChunk::Array);
4257 template<typename AttrT>
4258 static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4259 AL.setUsedAsTypeAttr();
4260 return ::new (Ctx) AttrT(Ctx, AL);
4263 static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4264 NullabilityKind NK) {
4266 case NullabilityKind::NonNull:
4267 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4269 case NullabilityKind::Nullable:
4270 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4272 case NullabilityKind::Unspecified:
4273 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4275 llvm_unreachable("unknown NullabilityKind");
4278 // Diagnose whether this is a case with the multiple addr spaces.
4279 // Returns true if this is an invalid case.
4280 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4281 // by qualifiers for two or more different address spaces."
4282 static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4284 SourceLocation AttrLoc) {
4285 if (ASOld != LangAS::Default) {
4286 if (ASOld != ASNew) {
4287 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4290 // Emit a warning if they are identical; it's likely unintended.
4292 diag::warn_attribute_address_multiple_identical_qualifiers);
4297 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4298 QualType declSpecType,
4299 TypeSourceInfo *TInfo) {
4300 // The TypeSourceInfo that this function returns will not be a null type.
4301 // If there is an error, this function will fill in a dummy type as fallback.
4302 QualType T = declSpecType;
4303 Declarator &D = state.getDeclarator();
4304 Sema &S = state.getSema();
4305 ASTContext &Context = S.Context;
4306 const LangOptions &LangOpts = S.getLangOpts();
4308 // The name we're declaring, if any.
4309 DeclarationName Name;
4310 if (D.getIdentifier())
4311 Name = D.getIdentifier();
4313 // Does this declaration declare a typedef-name?
4314 bool IsTypedefName =
4315 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4316 D.getContext() == DeclaratorContext::AliasDeclContext ||
4317 D.getContext() == DeclaratorContext::AliasTemplateContext;
4319 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4320 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4321 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4322 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4324 // If T is 'decltype(auto)', the only declarators we can have are parens
4325 // and at most one function declarator if this is a function declaration.
4326 // If T is a deduced class template specialization type, we can have no
4327 // declarator chunks at all.
4328 if (auto *DT = T->getAs<DeducedType>()) {
4329 const AutoType *AT = T->getAs<AutoType>();
4330 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4331 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4332 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4333 unsigned Index = E - I - 1;
4334 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4335 unsigned DiagId = IsClassTemplateDeduction
4336 ? diag::err_deduced_class_template_compound_type
4337 : diag::err_decltype_auto_compound_type;
4338 unsigned DiagKind = 0;
4339 switch (DeclChunk.Kind) {
4340 case DeclaratorChunk::Paren:
4341 // FIXME: Rejecting this is a little silly.
4342 if (IsClassTemplateDeduction) {
4347 case DeclaratorChunk::Function: {
4348 if (IsClassTemplateDeduction) {
4353 if (D.isFunctionDeclarationContext() &&
4354 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4356 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4359 case DeclaratorChunk::Pointer:
4360 case DeclaratorChunk::BlockPointer:
4361 case DeclaratorChunk::MemberPointer:
4364 case DeclaratorChunk::Reference:
4367 case DeclaratorChunk::Array:
4370 case DeclaratorChunk::Pipe:
4374 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4375 D.setInvalidType(true);
4381 // Determine whether we should infer _Nonnull on pointer types.
4382 Optional<NullabilityKind> inferNullability;
4383 bool inferNullabilityCS = false;
4384 bool inferNullabilityInnerOnly = false;
4385 bool inferNullabilityInnerOnlyComplete = false;
4387 // Are we in an assume-nonnull region?
4388 bool inAssumeNonNullRegion = false;
4389 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4390 if (assumeNonNullLoc.isValid()) {
4391 inAssumeNonNullRegion = true;
4392 recordNullabilitySeen(S, assumeNonNullLoc);
4395 // Whether to complain about missing nullability specifiers or not.
4399 /// Complain on the inner pointers (but not the outermost
4402 /// Complain about any pointers that don't have nullability
4403 /// specified or inferred.
4405 } complainAboutMissingNullability = CAMN_No;
4406 unsigned NumPointersRemaining = 0;
4407 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4409 if (IsTypedefName) {
4410 // For typedefs, we do not infer any nullability (the default),
4411 // and we only complain about missing nullability specifiers on
4413 complainAboutMissingNullability = CAMN_InnerPointers;
4415 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4416 !T->getNullability(S.Context)) {
4417 // Note that we allow but don't require nullability on dependent types.
4418 ++NumPointersRemaining;
4421 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4422 DeclaratorChunk &chunk = D.getTypeObject(i);
4423 switch (chunk.Kind) {
4424 case DeclaratorChunk::Array:
4425 case DeclaratorChunk::Function:
4426 case DeclaratorChunk::Pipe:
4429 case DeclaratorChunk::BlockPointer:
4430 case DeclaratorChunk::MemberPointer:
4431 ++NumPointersRemaining;
4434 case DeclaratorChunk::Paren:
4435 case DeclaratorChunk::Reference:
4438 case DeclaratorChunk::Pointer:
4439 ++NumPointersRemaining;
4444 bool isFunctionOrMethod = false;
4445 switch (auto context = state.getDeclarator().getContext()) {
4446 case DeclaratorContext::ObjCParameterContext:
4447 case DeclaratorContext::ObjCResultContext:
4448 case DeclaratorContext::PrototypeContext:
4449 case DeclaratorContext::TrailingReturnContext:
4450 case DeclaratorContext::TrailingReturnVarContext:
4451 isFunctionOrMethod = true;
4454 case DeclaratorContext::MemberContext:
4455 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4456 complainAboutMissingNullability = CAMN_No;
4460 // Weak properties are inferred to be nullable.
4461 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
4462 inferNullability = NullabilityKind::Nullable;
4468 case DeclaratorContext::FileContext:
4469 case DeclaratorContext::KNRTypeListContext: {
4470 complainAboutMissingNullability = CAMN_Yes;
4472 // Nullability inference depends on the type and declarator.
4473 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4474 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4475 case PointerDeclaratorKind::NonPointer:
4476 case PointerDeclaratorKind::MultiLevelPointer:
4477 // Cannot infer nullability.
4480 case PointerDeclaratorKind::SingleLevelPointer:
4481 // Infer _Nonnull if we are in an assumes-nonnull region.
4482 if (inAssumeNonNullRegion) {
4483 complainAboutInferringWithinChunk = wrappingKind;
4484 inferNullability = NullabilityKind::NonNull;
4485 inferNullabilityCS =
4486 (context == DeclaratorContext::ObjCParameterContext ||
4487 context == DeclaratorContext::ObjCResultContext);
4491 case PointerDeclaratorKind::CFErrorRefPointer:
4492 case PointerDeclaratorKind::NSErrorPointerPointer:
4493 // Within a function or method signature, infer _Nullable at both
4495 if (isFunctionOrMethod && inAssumeNonNullRegion)
4496 inferNullability = NullabilityKind::Nullable;
4499 case PointerDeclaratorKind::MaybePointerToCFRef:
4500 if (isFunctionOrMethod) {
4501 // On pointer-to-pointer parameters marked cf_returns_retained or
4502 // cf_returns_not_retained, if the outer pointer is explicit then
4503 // infer the inner pointer as _Nullable.
4504 auto hasCFReturnsAttr =
4505 [](const ParsedAttributesView &AttrList) -> bool {
4506 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4507 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4509 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4510 if (hasCFReturnsAttr(D.getAttributes()) ||
4511 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4512 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4513 inferNullability = NullabilityKind::Nullable;
4514 inferNullabilityInnerOnly = true;
4523 case DeclaratorContext::ConversionIdContext:
4524 complainAboutMissingNullability = CAMN_Yes;
4527 case DeclaratorContext::AliasDeclContext:
4528 case DeclaratorContext::AliasTemplateContext:
4529 case DeclaratorContext::BlockContext:
4530 case DeclaratorContext::BlockLiteralContext:
4531 case DeclaratorContext::ConditionContext:
4532 case DeclaratorContext::CXXCatchContext:
4533 case DeclaratorContext::CXXNewContext:
4534 case DeclaratorContext::ForContext:
4535 case DeclaratorContext::InitStmtContext:
4536 case DeclaratorContext::LambdaExprContext:
4537 case DeclaratorContext::LambdaExprParameterContext:
4538 case DeclaratorContext::ObjCCatchContext:
4539 case DeclaratorContext::TemplateParamContext:
4540 case DeclaratorContext::TemplateArgContext:
4541 case DeclaratorContext::TemplateTypeArgContext:
4542 case DeclaratorContext::TypeNameContext:
4543 case DeclaratorContext::FunctionalCastContext:
4544 case DeclaratorContext::RequiresExprContext:
4545 // Don't infer in these contexts.
4550 // Local function that returns true if its argument looks like a va_list.
4551 auto isVaList = [&S](QualType T) -> bool {
4552 auto *typedefTy = T->getAs<TypedefType>();
4555 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4557 if (typedefTy->getDecl() == vaListTypedef)
4559 if (auto *name = typedefTy->getDecl()->getIdentifier())
4560 if (name->isStr("va_list"))
4562 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4563 } while (typedefTy);
4567 // Local function that checks the nullability for a given pointer declarator.
4568 // Returns true if _Nonnull was inferred.
4569 auto inferPointerNullability =
4570 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4571 SourceLocation pointerEndLoc,
4572 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4573 // We've seen a pointer.
4574 if (NumPointersRemaining > 0)
4575 --NumPointersRemaining;
4577 // If a nullability attribute is present, there's nothing to do.
4578 if (hasNullabilityAttr(attrs))
4581 // If we're supposed to infer nullability, do so now.
4582 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4583 ParsedAttr::Syntax syntax = inferNullabilityCS
4584 ? ParsedAttr::AS_ContextSensitiveKeyword
4585 : ParsedAttr::AS_Keyword;
4586 ParsedAttr *nullabilityAttr = Pool.create(
4587 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4588 nullptr, SourceLocation(), nullptr, 0, syntax);
4590 attrs.addAtEnd(nullabilityAttr);
4592 if (inferNullabilityCS) {
4593 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4594 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4597 if (pointerLoc.isValid() &&
4598 complainAboutInferringWithinChunk !=
4599 PointerWrappingDeclaratorKind::None) {
4601 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4602 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4603 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4606 if (inferNullabilityInnerOnly)
4607 inferNullabilityInnerOnlyComplete = true;
4608 return nullabilityAttr;
4611 // If we're supposed to complain about missing nullability, do so
4612 // now if it's truly missing.
4613 switch (complainAboutMissingNullability) {
4617 case CAMN_InnerPointers:
4618 if (NumPointersRemaining == 0)
4623 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4628 // If the type itself could have nullability but does not, infer pointer
4629 // nullability and perform consistency checking.
4630 if (S.CodeSynthesisContexts.empty()) {
4631 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4632 !T->getNullability(S.Context)) {
4634 // Record that we've seen a pointer, but do nothing else.
4635 if (NumPointersRemaining > 0)
4636 --NumPointersRemaining;
4638 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4639 if (T->isBlockPointerType())
4640 pointerKind = SimplePointerKind::BlockPointer;
4641 else if (T->isMemberPointerType())
4642 pointerKind = SimplePointerKind::MemberPointer;
4644 if (auto *attr = inferPointerNullability(
4645 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4646 D.getDeclSpec().getEndLoc(),
4647 D.getMutableDeclSpec().getAttributes(),
4648 D.getMutableDeclSpec().getAttributePool())) {
4649 T = state.getAttributedType(
4650 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4655 if (complainAboutMissingNullability == CAMN_Yes &&
4656 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4657 D.isPrototypeContext() &&
4658 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4659 checkNullabilityConsistency(S, SimplePointerKind::Array,
4660 D.getDeclSpec().getTypeSpecTypeLoc());
4664 bool ExpectNoDerefChunk =
4665 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4667 // Walk the DeclTypeInfo, building the recursive type as we go.
4668 // DeclTypeInfos are ordered from the identifier out, which is
4669 // opposite of what we want :).
4670 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4671 unsigned chunkIndex = e - i - 1;
4672 state.setCurrentChunkIndex(chunkIndex);
4673 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4674 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4675 switch (DeclType.Kind) {
4676 case DeclaratorChunk::Paren:
4678 warnAboutRedundantParens(S, D, T);
4679 T = S.BuildParenType(T);
4681 case DeclaratorChunk::BlockPointer:
4682 // If blocks are disabled, emit an error.
4683 if (!LangOpts.Blocks)
4684 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4686 // Handle pointer nullability.
4687 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4688 DeclType.EndLoc, DeclType.getAttrs(),
4689 state.getDeclarator().getAttributePool());
4691 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4692 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4693 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4694 // qualified with const.
4695 if (LangOpts.OpenCL)
4696 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4697 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4700 case DeclaratorChunk::Pointer:
4701 // Verify that we're not building a pointer to pointer to function with
4702 // exception specification.
4703 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4704 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4705 D.setInvalidType(true);
4706 // Build the type anyway.
4709 // Handle pointer nullability
4710 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4711 DeclType.EndLoc, DeclType.getAttrs(),
4712 state.getDeclarator().getAttributePool());
4714 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4715 T = Context.getObjCObjectPointerType(T);
4716 if (DeclType.Ptr.TypeQuals)
4717 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4721 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4722 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4723 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4724 if (LangOpts.OpenCL) {
4725 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4726 T->isBlockPointerType()) {
4727 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4728 D.setInvalidType(true);
4732 T = S.BuildPointerType(T, DeclType.Loc, Name);
4733 if (DeclType.Ptr.TypeQuals)
4734 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4736 case DeclaratorChunk::Reference: {
4737 // Verify that we're not building a reference to pointer to function with
4738 // exception specification.
4739 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4740 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4741 D.setInvalidType(true);
4742 // Build the type anyway.
4744 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4746 if (DeclType.Ref.HasRestrict)
4747 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4750 case DeclaratorChunk::Array: {
4751 // Verify that we're not building an array of pointers to function with
4752 // exception specification.
4753 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4754 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4755 D.setInvalidType(true);
4756 // Build the type anyway.
4758 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4759 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4760 ArrayType::ArraySizeModifier ASM;
4762 ASM = ArrayType::Star;
4763 else if (ATI.hasStatic)
4764 ASM = ArrayType::Static;
4766 ASM = ArrayType::Normal;
4767 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4768 // FIXME: This check isn't quite right: it allows star in prototypes
4769 // for function definitions, and disallows some edge cases detailed
4770 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4771 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4772 ASM = ArrayType::Normal;
4773 D.setInvalidType(true);
4776 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4777 // shall appear only in a declaration of a function parameter with an
4779 if (ASM == ArrayType::Static || ATI.TypeQuals) {
4780 if (!(D.isPrototypeContext() ||
4781 D.getContext() == DeclaratorContext::KNRTypeListContext)) {
4782 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4783 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4784 // Remove the 'static' and the type qualifiers.
4785 if (ASM == ArrayType::Static)
4786 ASM = ArrayType::Normal;
4788 D.setInvalidType(true);
4791 // C99 6.7.5.2p1: ... and then only in the outermost array type
4793 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4794 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4795 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4796 if (ASM == ArrayType::Static)
4797 ASM = ArrayType::Normal;
4799 D.setInvalidType(true);
4802 const AutoType *AT = T->getContainedAutoType();
4803 // Allow arrays of auto if we are a generic lambda parameter.
4804 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4806 D.getContext() != DeclaratorContext::LambdaExprParameterContext) {
4807 // We've already diagnosed this for decltype(auto).
4808 if (!AT->isDecltypeAuto())
4809 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4810 << getPrintableNameForEntity(Name) << T;
4815 // Array parameters can be marked nullable as well, although it's not
4816 // necessary if they're marked 'static'.
4817 if (complainAboutMissingNullability == CAMN_Yes &&
4818 !hasNullabilityAttr(DeclType.getAttrs()) &&
4819 ASM != ArrayType::Static &&
4820 D.isPrototypeContext() &&
4821 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4822 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4825 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4826 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4829 case DeclaratorChunk::Function: {
4830 // If the function declarator has a prototype (i.e. it is not () and
4831 // does not have a K&R-style identifier list), then the arguments are part
4832 // of the type, otherwise the argument list is ().
4833 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4834 IsQualifiedFunction =
4835 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
4837 // Check for auto functions and trailing return type and adjust the
4838 // return type accordingly.
4839 if (!D.isInvalidType()) {
4840 // trailing-return-type is only required if we're declaring a function,
4841 // and not, for instance, a pointer to a function.
4842 if (D.getDeclSpec().hasAutoTypeSpec() &&
4843 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4844 if (!S.getLangOpts().CPlusPlus14) {
4845 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4846 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4847 ? diag::err_auto_missing_trailing_return
4848 : diag::err_deduced_return_type);
4850 D.setInvalidType(true);
4852 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4853 diag::warn_cxx11_compat_deduced_return_type);
4855 } else if (FTI.hasTrailingReturnType()) {
4856 // T must be exactly 'auto' at this point. See CWG issue 681.
4857 if (isa<ParenType>(T)) {
4858 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4859 << T << D.getSourceRange();
4860 D.setInvalidType(true);
4861 } else if (D.getName().getKind() ==
4862 UnqualifiedIdKind::IK_DeductionGuideName) {
4863 if (T != Context.DependentTy) {
4864 S.Diag(D.getDeclSpec().getBeginLoc(),
4865 diag::err_deduction_guide_with_complex_decl)
4866 << D.getSourceRange();
4867 D.setInvalidType(true);
4869 } else if (D.getContext() != DeclaratorContext::LambdaExprContext &&
4870 (T.hasQualifiers() || !isa<AutoType>(T) ||
4871 cast<AutoType>(T)->getKeyword() !=
4872 AutoTypeKeyword::Auto ||
4873 cast<AutoType>(T)->isConstrained())) {
4874 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4875 diag::err_trailing_return_without_auto)
4876 << T << D.getDeclSpec().getSourceRange();
4877 D.setInvalidType(true);
4879 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4881 // An error occurred parsing the trailing return type.
4883 D.setInvalidType(true);
4884 } else if (S.getLangOpts().CPlusPlus20)
4885 // Handle cases like: `auto f() -> auto` or `auto f() -> C auto`.
4886 if (AutoType *Auto = T->getContainedAutoType())
4887 if (S.getCurScope()->isFunctionDeclarationScope())
4888 T = InventTemplateParameter(state, T, TInfo, Auto,
4889 S.InventedParameterInfos.back());
4891 // This function type is not the type of the entity being declared,
4892 // so checking the 'auto' is not the responsibility of this chunk.
4896 // C99 6.7.5.3p1: The return type may not be a function or array type.
4897 // For conversion functions, we'll diagnose this particular error later.
4898 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4899 (D.getName().getKind() !=
4900 UnqualifiedIdKind::IK_ConversionFunctionId)) {
4901 unsigned diagID = diag::err_func_returning_array_function;
4902 // Last processing chunk in block context means this function chunk
4903 // represents the block.
4904 if (chunkIndex == 0 &&
4905 D.getContext() == DeclaratorContext::BlockLiteralContext)
4906 diagID = diag::err_block_returning_array_function;
4907 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4909 D.setInvalidType(true);
4912 // Do not allow returning half FP value.
4913 // FIXME: This really should be in BuildFunctionType.
4914 if (T->isHalfType()) {
4915 if (S.getLangOpts().OpenCL) {
4916 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4917 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4918 << T << 0 /*pointer hint*/;
4919 D.setInvalidType(true);
4921 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4922 S.Diag(D.getIdentifierLoc(),
4923 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4924 D.setInvalidType(true);
4928 if (LangOpts.OpenCL) {
4929 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4931 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4933 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4934 << T << 1 /*hint off*/;
4935 D.setInvalidType(true);
4937 // OpenCL doesn't support variadic functions and blocks
4938 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4939 // We also allow here any toolchain reserved identifiers.
4940 if (FTI.isVariadic &&
4941 !(D.getIdentifier() &&
4942 ((D.getIdentifier()->getName() == "printf" &&
4943 (LangOpts.OpenCLCPlusPlus || LangOpts.OpenCLVersion >= 120)) ||
4944 D.getIdentifier()->getName().startswith("__")))) {
4945 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4946 D.setInvalidType(true);
4950 // Methods cannot return interface types. All ObjC objects are
4951 // passed by reference.
4952 if (T->isObjCObjectType()) {
4953 SourceLocation DiagLoc, FixitLoc;
4955 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
4956 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
4958 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4959 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
4961 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4963 << FixItHint::CreateInsertion(FixitLoc, "*");
4965 T = Context.getObjCObjectPointerType(T);
4968 TLB.pushFullCopy(TInfo->getTypeLoc());
4969 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4970 TLoc.setStarLoc(FixitLoc);
4971 TInfo = TLB.getTypeSourceInfo(Context, T);
4974 D.setInvalidType(true);
4977 // cv-qualifiers on return types are pointless except when the type is a
4978 // class type in C++.
4979 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4980 !(S.getLangOpts().CPlusPlus &&
4981 (T->isDependentType() || T->isRecordType()))) {
4982 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4983 D.getFunctionDefinitionKind() == FDK_Definition) {
4984 // [6.9.1/3] qualified void return is invalid on a C
4985 // function definition. Apparently ok on declarations and
4986 // in C++ though (!)
4987 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4989 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4991 // C++2a [dcl.fct]p12:
4992 // A volatile-qualified return type is deprecated
4993 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
4994 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
4997 // Objective-C ARC ownership qualifiers are ignored on the function
4998 // return type (by type canonicalization). Complain if this attribute
4999 // was written here.
5000 if (T.getQualifiers().hasObjCLifetime()) {
5001 SourceLocation AttrLoc;
5002 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5003 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5004 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5005 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5006 AttrLoc = AL.getLoc();
5011 if (AttrLoc.isInvalid()) {
5012 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5013 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5014 AttrLoc = AL.getLoc();
5020 if (AttrLoc.isValid()) {
5021 // The ownership attributes are almost always written via
5023 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5024 if (AttrLoc.isMacroID())
5026 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
5028 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5029 << T.getQualifiers().getObjCLifetime();
5033 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5035 // Types shall not be defined in return or parameter types.
5036 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5037 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5038 << Context.getTypeDeclType(Tag);
5041 // Exception specs are not allowed in typedefs. Complain, but add it
5043 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5044 S.Diag(FTI.getExceptionSpecLocBeg(),
5045 diag::err_exception_spec_in_typedef)
5046 << (D.getContext() == DeclaratorContext::AliasDeclContext ||
5047 D.getContext() == DeclaratorContext::AliasTemplateContext);
5049 // If we see "T var();" or "T var(T());" at block scope, it is probably
5050 // an attempt to initialize a variable, not a function declaration.
5051 if (FTI.isAmbiguous)
5052 warnAboutAmbiguousFunction(S, D, DeclType, T);
5054 FunctionType::ExtInfo EI(
5055 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5057 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
5058 && !LangOpts.OpenCL) {
5059 // Simple void foo(), where the incoming T is the result type.
5060 T = Context.getFunctionNoProtoType(T, EI);
5062 // We allow a zero-parameter variadic function in C if the
5063 // function is marked with the "overloadable" attribute. Scan
5064 // for this attribute now.
5065 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus)
5066 if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable))
5067 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5069 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5070 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5072 S.Diag(FTI.Params[0].IdentLoc,
5073 diag::err_ident_list_in_fn_declaration);
5074 D.setInvalidType(true);
5075 // Recover by creating a K&R-style function type.
5076 T = Context.getFunctionNoProtoType(T, EI);
5080 FunctionProtoType::ExtProtoInfo EPI;
5082 EPI.Variadic = FTI.isVariadic;
5083 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5084 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
5085 EPI.TypeQuals.addCVRUQualifiers(
5086 FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
5088 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
5089 : FTI.RefQualifierIsLValueRef? RQ_LValue
5092 // Otherwise, we have a function with a parameter list that is
5093 // potentially variadic.
5094 SmallVector<QualType, 16> ParamTys;
5095 ParamTys.reserve(FTI.NumParams);
5097 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
5098 ExtParameterInfos(FTI.NumParams);
5099 bool HasAnyInterestingExtParameterInfos = false;
5101 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5102 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5103 QualType ParamTy = Param->getType();
5104 assert(!ParamTy.isNull() && "Couldn't parse type?");
5106 // Look for 'void'. void is allowed only as a single parameter to a
5107 // function with no other parameters (C99 6.7.5.3p10). We record
5108 // int(void) as a FunctionProtoType with an empty parameter list.
5109 if (ParamTy->isVoidType()) {
5110 // If this is something like 'float(int, void)', reject it. 'void'
5111 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5112 // have parameters of incomplete type.
5113 if (FTI.NumParams != 1 || FTI.isVariadic) {
5114 S.Diag(DeclType.Loc, diag::err_void_only_param);
5115 ParamTy = Context.IntTy;
5116 Param->setType(ParamTy);
5117 } else if (FTI.Params[i].Ident) {
5118 // Reject, but continue to parse 'int(void abc)'.
5119 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5120 ParamTy = Context.IntTy;
5121 Param->setType(ParamTy);
5123 // Reject, but continue to parse 'float(const void)'.
5124 if (ParamTy.hasQualifiers())
5125 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5127 // Do not add 'void' to the list.
5130 } else if (ParamTy->isHalfType()) {
5131 // Disallow half FP parameters.
5132 // FIXME: This really should be in BuildFunctionType.
5133 if (S.getLangOpts().OpenCL) {
5134 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
5135 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5138 Param->setInvalidDecl();
5140 } else if (!S.getLangOpts().HalfArgsAndReturns) {
5141 S.Diag(Param->getLocation(),
5142 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5145 } else if (!FTI.hasPrototype) {
5146 if (ParamTy->isPromotableIntegerType()) {
5147 ParamTy = Context.getPromotedIntegerType(ParamTy);
5148 Param->setKNRPromoted(true);
5149 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
5150 if (BTy->getKind() == BuiltinType::Float) {
5151 ParamTy = Context.DoubleTy;
5152 Param->setKNRPromoted(true);
5155 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5156 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5157 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5158 << ParamTy << 1 /*hint off*/;
5162 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5163 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5164 HasAnyInterestingExtParameterInfos = true;
5167 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5168 ExtParameterInfos[i] =
5169 ExtParameterInfos[i].withABI(attr->getABI());
5170 HasAnyInterestingExtParameterInfos = true;
5173 if (Param->hasAttr<PassObjectSizeAttr>()) {
5174 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5175 HasAnyInterestingExtParameterInfos = true;
5178 if (Param->hasAttr<NoEscapeAttr>()) {
5179 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5180 HasAnyInterestingExtParameterInfos = true;
5183 ParamTys.push_back(ParamTy);
5186 if (HasAnyInterestingExtParameterInfos) {
5187 EPI.ExtParameterInfos = ExtParameterInfos.data();
5188 checkExtParameterInfos(S, ParamTys, EPI,
5189 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5192 SmallVector<QualType, 4> Exceptions;
5193 SmallVector<ParsedType, 2> DynamicExceptions;
5194 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5195 Expr *NoexceptExpr = nullptr;
5197 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5198 // FIXME: It's rather inefficient to have to split into two vectors
5200 unsigned N = FTI.getNumExceptions();
5201 DynamicExceptions.reserve(N);
5202 DynamicExceptionRanges.reserve(N);
5203 for (unsigned I = 0; I != N; ++I) {
5204 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5205 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5207 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5208 NoexceptExpr = FTI.NoexceptExpr;
5211 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
5212 FTI.getExceptionSpecType(),
5214 DynamicExceptionRanges,
5219 // FIXME: Set address space from attrs for C++ mode here.
5220 // OpenCLCPlusPlus: A class member function has an address space.
5221 auto IsClassMember = [&]() {
5222 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5223 state.getDeclarator()
5226 ->getKind() == NestedNameSpecifier::TypeSpec) ||
5227 state.getDeclarator().getContext() ==
5228 DeclaratorContext::MemberContext ||
5229 state.getDeclarator().getContext() ==
5230 DeclaratorContext::LambdaExprContext;
5233 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5234 LangAS ASIdx = LangAS::Default;
5235 // Take address space attr if any and mark as invalid to avoid adding
5236 // them later while creating QualType.
5237 if (FTI.MethodQualifiers)
5238 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
5239 LangAS ASIdxNew = attr.asOpenCLLangAS();
5240 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5242 D.setInvalidType(true);
5246 // If a class member function's address space is not set, set it to
5249 (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace()
5251 EPI.TypeQuals.addAddressSpace(AS);
5253 T = Context.getFunctionType(T, ParamTys, EPI);
5257 case DeclaratorChunk::MemberPointer: {
5258 // The scope spec must refer to a class, or be dependent.
5259 CXXScopeSpec &SS = DeclType.Mem.Scope();
5262 // Handle pointer nullability.
5263 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5264 DeclType.EndLoc, DeclType.getAttrs(),
5265 state.getDeclarator().getAttributePool());
5267 if (SS.isInvalid()) {
5268 // Avoid emitting extra errors if we already errored on the scope.
5269 D.setInvalidType(true);
5270 } else if (S.isDependentScopeSpecifier(SS) ||
5271 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
5272 NestedNameSpecifier *NNS = SS.getScopeRep();
5273 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
5274 switch (NNS->getKind()) {
5275 case NestedNameSpecifier::Identifier:
5276 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
5277 NNS->getAsIdentifier());
5280 case NestedNameSpecifier::Namespace:
5281 case NestedNameSpecifier::NamespaceAlias:
5282 case NestedNameSpecifier::Global:
5283 case NestedNameSpecifier::Super:
5284 llvm_unreachable("Nested-name-specifier must name a type");
5286 case NestedNameSpecifier::TypeSpec:
5287 case NestedNameSpecifier::TypeSpecWithTemplate:
5288 ClsType = QualType(NNS->getAsType(), 0);
5289 // Note: if the NNS has a prefix and ClsType is a nondependent
5290 // TemplateSpecializationType, then the NNS prefix is NOT included
5291 // in ClsType; hence we wrap ClsType into an ElaboratedType.
5292 // NOTE: in particular, no wrap occurs if ClsType already is an
5293 // Elaborated, DependentName, or DependentTemplateSpecialization.
5294 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
5295 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
5299 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
5300 diag::err_illegal_decl_mempointer_in_nonclass)
5301 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
5302 << DeclType.Mem.Scope().getRange();
5303 D.setInvalidType(true);
5306 if (!ClsType.isNull())
5307 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
5311 D.setInvalidType(true);
5312 } else if (DeclType.Mem.TypeQuals) {
5313 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5318 case DeclaratorChunk::Pipe: {
5319 T = S.BuildReadPipeType(T, DeclType.Loc);
5320 processTypeAttrs(state, T, TAL_DeclSpec,
5321 D.getMutableDeclSpec().getAttributes());
5327 D.setInvalidType(true);
5331 // See if there are any attributes on this declarator chunk.
5332 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
5334 if (DeclType.Kind != DeclaratorChunk::Paren) {
5335 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5336 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5338 ExpectNoDerefChunk = state.didParseNoDeref();
5342 if (ExpectNoDerefChunk)
5343 S.Diag(state.getDeclarator().getBeginLoc(),
5344 diag::warn_noderef_on_non_pointer_or_array);
5346 // GNU warning -Wstrict-prototypes
5347 // Warn if a function declaration is without a prototype.
5348 // This warning is issued for all kinds of unprototyped function
5349 // declarations (i.e. function type typedef, function pointer etc.)
5351 // The empty list in a function declarator that is not part of a definition
5352 // of that function specifies that no information about the number or types
5353 // of the parameters is supplied.
5354 if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) {
5355 bool IsBlock = false;
5356 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5357 switch (DeclType.Kind) {
5358 case DeclaratorChunk::BlockPointer:
5361 case DeclaratorChunk::Function: {
5362 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5363 // We supress the warning when there's no LParen location, as this
5364 // indicates the declaration was an implicit declaration, which gets
5365 // warned about separately via -Wimplicit-function-declaration.
5366 if (FTI.NumParams == 0 && !FTI.isVariadic && FTI.getLParenLoc().isValid())
5367 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5369 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5379 assert(!T.isNull() && "T must not be null after this point");
5381 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5382 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5383 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5386 // A cv-qualifier-seq shall only be part of the function type
5387 // for a nonstatic member function, the function type to which a pointer
5388 // to member refers, or the top-level function type of a function typedef
5391 // Core issue 547 also allows cv-qualifiers on function types that are
5392 // top-level template type arguments.
5393 enum { NonMember, Member, DeductionGuide } Kind = NonMember;
5394 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5395 Kind = DeductionGuide;
5396 else if (!D.getCXXScopeSpec().isSet()) {
5397 if ((D.getContext() == DeclaratorContext::MemberContext ||
5398 D.getContext() == DeclaratorContext::LambdaExprContext) &&
5399 !D.getDeclSpec().isFriendSpecified())
5402 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
5403 if (!DC || DC->isRecord())
5407 // C++11 [dcl.fct]p6 (w/DR1417):
5408 // An attempt to specify a function type with a cv-qualifier-seq or a
5409 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5410 // - the function type for a non-static member function,
5411 // - the function type to which a pointer to member refers,
5412 // - the top-level function type of a function typedef declaration or
5413 // alias-declaration,
5414 // - the type-id in the default argument of a type-parameter, or
5415 // - the type-id of a template-argument for a type-parameter
5417 // FIXME: Checking this here is insufficient. We accept-invalid on:
5419 // template<typename T> struct S { void f(T); };
5420 // S<int() const> s;
5422 // ... for instance.
5423 if (IsQualifiedFunction &&
5425 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
5427 D.getContext() != DeclaratorContext::TemplateArgContext &&
5428 D.getContext() != DeclaratorContext::TemplateTypeArgContext) {
5429 SourceLocation Loc = D.getBeginLoc();
5430 SourceRange RemovalRange;
5432 if (D.isFunctionDeclarator(I)) {
5433 SmallVector<SourceLocation, 4> RemovalLocs;
5434 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5435 assert(Chunk.Kind == DeclaratorChunk::Function);
5437 if (Chunk.Fun.hasRefQualifier())
5438 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5440 if (Chunk.Fun.hasMethodTypeQualifiers())
5441 Chunk.Fun.MethodQualifiers->forEachQualifier(
5442 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5443 SourceLocation SL) { RemovalLocs.push_back(SL); });
5445 if (!RemovalLocs.empty()) {
5446 llvm::sort(RemovalLocs,
5447 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5448 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5449 Loc = RemovalLocs.front();
5453 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5454 << Kind << D.isFunctionDeclarator() << T
5455 << getFunctionQualifiersAsString(FnTy)
5456 << FixItHint::CreateRemoval(RemovalRange);
5458 // Strip the cv-qualifiers and ref-qualifiers from the type.
5459 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5460 EPI.TypeQuals.removeCVRQualifiers();
5461 EPI.RefQualifier = RQ_None;
5463 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5465 // Rebuild any parens around the identifier in the function type.
5466 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5467 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5469 T = S.BuildParenType(T);
5474 // Apply any undistributed attributes from the declarator.
5475 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5477 // Diagnose any ignored type attributes.
5478 state.diagnoseIgnoredTypeAttrs(T);
5480 // C++0x [dcl.constexpr]p9:
5481 // A constexpr specifier used in an object declaration declares the object
5483 if (D.getDeclSpec().getConstexprSpecifier() == CSK_constexpr &&
5487 // C++2a [dcl.fct]p4:
5488 // A parameter with volatile-qualified type is deprecated
5489 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5490 (D.getContext() == DeclaratorContext::PrototypeContext ||
5491 D.getContext() == DeclaratorContext::LambdaExprParameterContext))
5492 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5494 // If there was an ellipsis in the declarator, the declaration declares a
5495 // parameter pack whose type may be a pack expansion type.
5496 if (D.hasEllipsis()) {
5497 // C++0x [dcl.fct]p13:
5498 // A declarator-id or abstract-declarator containing an ellipsis shall
5499 // only be used in a parameter-declaration. Such a parameter-declaration
5500 // is a parameter pack (14.5.3). [...]
5501 switch (D.getContext()) {
5502 case DeclaratorContext::PrototypeContext:
5503 case DeclaratorContext::LambdaExprParameterContext:
5504 case DeclaratorContext::RequiresExprContext:
5505 // C++0x [dcl.fct]p13:
5506 // [...] When it is part of a parameter-declaration-clause, the
5507 // parameter pack is a function parameter pack (14.5.3). The type T
5508 // of the declarator-id of the function parameter pack shall contain
5509 // a template parameter pack; each template parameter pack in T is
5510 // expanded by the function parameter pack.
5512 // We represent function parameter packs as function parameters whose
5513 // type is a pack expansion.
5514 if (!T->containsUnexpandedParameterPack() &&
5515 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5516 S.Diag(D.getEllipsisLoc(),
5517 diag::err_function_parameter_pack_without_parameter_packs)
5518 << T << D.getSourceRange();
5519 D.setEllipsisLoc(SourceLocation());
5521 T = Context.getPackExpansionType(T, None);
5524 case DeclaratorContext::TemplateParamContext:
5525 // C++0x [temp.param]p15:
5526 // If a template-parameter is a [...] is a parameter-declaration that
5527 // declares a parameter pack (8.3.5), then the template-parameter is a
5528 // template parameter pack (14.5.3).
5530 // Note: core issue 778 clarifies that, if there are any unexpanded
5531 // parameter packs in the type of the non-type template parameter, then
5532 // it expands those parameter packs.
5533 if (T->containsUnexpandedParameterPack())
5534 T = Context.getPackExpansionType(T, None);
5536 S.Diag(D.getEllipsisLoc(),
5537 LangOpts.CPlusPlus11
5538 ? diag::warn_cxx98_compat_variadic_templates
5539 : diag::ext_variadic_templates);
5542 case DeclaratorContext::FileContext:
5543 case DeclaratorContext::KNRTypeListContext:
5544 case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic
5546 case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic
5548 case DeclaratorContext::TypeNameContext:
5549 case DeclaratorContext::FunctionalCastContext:
5550 case DeclaratorContext::CXXNewContext:
5551 case DeclaratorContext::AliasDeclContext:
5552 case DeclaratorContext::AliasTemplateContext:
5553 case DeclaratorContext::MemberContext:
5554 case DeclaratorContext::BlockContext:
5555 case DeclaratorContext::ForContext:
5556 case DeclaratorContext::InitStmtContext:
5557 case DeclaratorContext::ConditionContext:
5558 case DeclaratorContext::CXXCatchContext:
5559 case DeclaratorContext::ObjCCatchContext:
5560 case DeclaratorContext::BlockLiteralContext:
5561 case DeclaratorContext::LambdaExprContext:
5562 case DeclaratorContext::ConversionIdContext:
5563 case DeclaratorContext::TrailingReturnContext:
5564 case DeclaratorContext::TrailingReturnVarContext:
5565 case DeclaratorContext::TemplateArgContext:
5566 case DeclaratorContext::TemplateTypeArgContext:
5567 // FIXME: We may want to allow parameter packs in block-literal contexts
5569 S.Diag(D.getEllipsisLoc(),
5570 diag::err_ellipsis_in_declarator_not_parameter);
5571 D.setEllipsisLoc(SourceLocation());
5576 assert(!T.isNull() && "T must not be null at the end of this function");
5577 if (D.isInvalidType())
5578 return Context.getTrivialTypeSourceInfo(T);
5580 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5583 /// GetTypeForDeclarator - Convert the type for the specified
5584 /// declarator to Type instances.
5586 /// The result of this call will never be null, but the associated
5587 /// type may be a null type if there's an unrecoverable error.
5588 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
5589 // Determine the type of the declarator. Not all forms of declarator
5592 TypeProcessingState state(*this, D);
5594 TypeSourceInfo *ReturnTypeInfo = nullptr;
5595 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5596 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5597 inferARCWriteback(state, T);
5599 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5602 static void transferARCOwnershipToDeclSpec(Sema &S,
5603 QualType &declSpecTy,
5604 Qualifiers::ObjCLifetime ownership) {
5605 if (declSpecTy->isObjCRetainableType() &&
5606 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5608 qs.addObjCLifetime(ownership);
5609 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5613 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5614 Qualifiers::ObjCLifetime ownership,
5615 unsigned chunkIndex) {
5616 Sema &S = state.getSema();
5617 Declarator &D = state.getDeclarator();
5619 // Look for an explicit lifetime attribute.
5620 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5621 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5624 const char *attrStr = nullptr;
5625 switch (ownership) {
5626 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5627 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5628 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5629 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5630 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5633 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5634 Arg->Ident = &S.Context.Idents.get(attrStr);
5635 Arg->Loc = SourceLocation();
5637 ArgsUnion Args(Arg);
5639 // If there wasn't one, add one (with an invalid source location
5640 // so that we don't make an AttributedType for it).
5641 ParsedAttr *attr = D.getAttributePool().create(
5642 &S.Context.Idents.get("objc_ownership"), SourceLocation(),
5643 /*scope*/ nullptr, SourceLocation(),
5644 /*args*/ &Args, 1, ParsedAttr::AS_GNU);
5645 chunk.getAttrs().addAtEnd(attr);
5646 // TODO: mark whether we did this inference?
5649 /// Used for transferring ownership in casts resulting in l-values.
5650 static void transferARCOwnership(TypeProcessingState &state,
5651 QualType &declSpecTy,
5652 Qualifiers::ObjCLifetime ownership) {
5653 Sema &S = state.getSema();
5654 Declarator &D = state.getDeclarator();
5657 bool hasIndirection = false;
5658 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5659 DeclaratorChunk &chunk = D.getTypeObject(i);
5660 switch (chunk.Kind) {
5661 case DeclaratorChunk::Paren:
5665 case DeclaratorChunk::Array:
5666 case DeclaratorChunk::Reference:
5667 case DeclaratorChunk::Pointer:
5669 hasIndirection = true;
5673 case DeclaratorChunk::BlockPointer:
5675 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5678 case DeclaratorChunk::Function:
5679 case DeclaratorChunk::MemberPointer:
5680 case DeclaratorChunk::Pipe:
5688 DeclaratorChunk &chunk = D.getTypeObject(inner);
5689 if (chunk.Kind == DeclaratorChunk::Pointer) {
5690 if (declSpecTy->isObjCRetainableType())
5691 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5692 if (declSpecTy->isObjCObjectType() && hasIndirection)
5693 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5695 assert(chunk.Kind == DeclaratorChunk::Array ||
5696 chunk.Kind == DeclaratorChunk::Reference);
5697 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5701 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
5702 TypeProcessingState state(*this, D);
5704 TypeSourceInfo *ReturnTypeInfo = nullptr;
5705 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5707 if (getLangOpts().ObjC) {
5708 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5709 if (ownership != Qualifiers::OCL_None)
5710 transferARCOwnership(state, declSpecTy, ownership);
5713 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5716 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5717 TypeProcessingState &State) {
5718 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5722 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5724 ASTContext &Context;
5725 TypeProcessingState &State;
5729 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
5731 : SemaRef(S), Context(Context), State(State), DS(DS) {}
5733 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5734 Visit(TL.getModifiedLoc());
5735 fillAttributedTypeLoc(TL, State);
5737 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5738 Visit(TL.getInnerLoc());
5740 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5742 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5743 Visit(TL.getUnqualifiedLoc());
5745 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5746 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5748 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5749 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5750 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5751 // addition field. What we have is good enough for dispay of location
5752 // of 'fixit' on interface name.
5753 TL.setNameEndLoc(DS.getEndLoc());
5755 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5756 TypeSourceInfo *RepTInfo = nullptr;
5757 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5758 TL.copy(RepTInfo->getTypeLoc());
5760 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5761 TypeSourceInfo *RepTInfo = nullptr;
5762 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5763 TL.copy(RepTInfo->getTypeLoc());
5765 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5766 TypeSourceInfo *TInfo = nullptr;
5767 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5769 // If we got no declarator info from previous Sema routines,
5770 // just fill with the typespec loc.
5772 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5776 TypeLoc OldTL = TInfo->getTypeLoc();
5777 if (TInfo->getType()->getAs<ElaboratedType>()) {
5778 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5779 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5780 .castAs<TemplateSpecializationTypeLoc>();
5783 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5784 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
5788 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5789 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
5790 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5791 TL.setParensRange(DS.getTypeofParensRange());
5793 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5794 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
5795 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5796 TL.setParensRange(DS.getTypeofParensRange());
5797 assert(DS.getRepAsType());
5798 TypeSourceInfo *TInfo = nullptr;
5799 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5800 TL.setUnderlyingTInfo(TInfo);
5802 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5803 // FIXME: This holds only because we only have one unary transform.
5804 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
5805 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5806 TL.setParensRange(DS.getTypeofParensRange());
5807 assert(DS.getRepAsType());
5808 TypeSourceInfo *TInfo = nullptr;
5809 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5810 TL.setUnderlyingTInfo(TInfo);
5812 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5813 // By default, use the source location of the type specifier.
5814 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5815 if (TL.needsExtraLocalData()) {
5816 // Set info for the written builtin specifiers.
5817 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5818 // Try to have a meaningful source location.
5819 if (TL.getWrittenSignSpec() != TSS_unspecified)
5820 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5821 if (TL.getWrittenWidthSpec() != TSW_unspecified)
5822 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5825 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5826 ElaboratedTypeKeyword Keyword
5827 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5828 if (DS.getTypeSpecType() == TST_typename) {
5829 TypeSourceInfo *TInfo = nullptr;
5830 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5832 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5836 TL.setElaboratedKeywordLoc(Keyword != ETK_None
5837 ? DS.getTypeSpecTypeLoc()
5838 : SourceLocation());
5839 const CXXScopeSpec& SS = DS.getTypeSpecScope();
5840 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5841 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5843 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5844 assert(DS.getTypeSpecType() == TST_typename);
5845 TypeSourceInfo *TInfo = nullptr;
5846 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5848 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
5850 void VisitDependentTemplateSpecializationTypeLoc(
5851 DependentTemplateSpecializationTypeLoc TL) {
5852 assert(DS.getTypeSpecType() == TST_typename);
5853 TypeSourceInfo *TInfo = nullptr;
5854 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5857 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
5859 void VisitAutoTypeLoc(AutoTypeLoc TL) {
5860 assert(DS.getTypeSpecType() == TST_auto ||
5861 DS.getTypeSpecType() == TST_decltype_auto ||
5862 DS.getTypeSpecType() == TST_auto_type ||
5863 DS.getTypeSpecType() == TST_unspecified);
5864 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5865 if (!DS.isConstrainedAuto())
5867 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
5868 if (DS.getTypeSpecScope().isNotEmpty())
5869 TL.setNestedNameSpecifierLoc(
5870 DS.getTypeSpecScope().getWithLocInContext(Context));
5872 TL.setNestedNameSpecifierLoc(NestedNameSpecifierLoc());
5873 TL.setTemplateKWLoc(TemplateId->TemplateKWLoc);
5874 TL.setConceptNameLoc(TemplateId->TemplateNameLoc);
5875 TL.setFoundDecl(nullptr);
5876 TL.setLAngleLoc(TemplateId->LAngleLoc);
5877 TL.setRAngleLoc(TemplateId->RAngleLoc);
5878 if (TemplateId->NumArgs == 0)
5880 TemplateArgumentListInfo TemplateArgsInfo;
5881 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5882 TemplateId->NumArgs);
5883 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
5884 for (unsigned I = 0; I < TemplateId->NumArgs; ++I)
5885 TL.setArgLocInfo(I, TemplateArgsInfo.arguments()[I].getLocInfo());
5887 void VisitTagTypeLoc(TagTypeLoc TL) {
5888 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
5890 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5891 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
5892 // or an _Atomic qualifier.
5893 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
5894 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5895 TL.setParensRange(DS.getTypeofParensRange());
5897 TypeSourceInfo *TInfo = nullptr;
5898 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5900 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5902 TL.setKWLoc(DS.getAtomicSpecLoc());
5903 // No parens, to indicate this was spelled as an _Atomic qualifier.
5904 TL.setParensRange(SourceRange());
5905 Visit(TL.getValueLoc());
5909 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5910 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5912 TypeSourceInfo *TInfo = nullptr;
5913 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5914 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5917 void VisitExtIntTypeLoc(ExtIntTypeLoc TL) {
5918 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5921 void VisitDependentExtIntTypeLoc(DependentExtIntTypeLoc TL) {
5922 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5925 void VisitTypeLoc(TypeLoc TL) {
5926 // FIXME: add other typespec types and change this to an assert.
5927 TL.initialize(Context, DS.getTypeSpecTypeLoc());
5931 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
5932 ASTContext &Context;
5933 TypeProcessingState &State;
5934 const DeclaratorChunk &Chunk;
5937 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
5938 const DeclaratorChunk &Chunk)
5939 : Context(Context), State(State), Chunk(Chunk) {}
5941 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5942 llvm_unreachable("qualified type locs not expected here!");
5944 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5945 llvm_unreachable("decayed type locs not expected here!");
5948 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5949 fillAttributedTypeLoc(TL, State);
5951 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5954 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5955 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
5956 TL.setCaretLoc(Chunk.Loc);
5958 void VisitPointerTypeLoc(PointerTypeLoc TL) {
5959 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5960 TL.setStarLoc(Chunk.Loc);
5962 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5963 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5964 TL.setStarLoc(Chunk.Loc);
5966 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5967 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
5968 const CXXScopeSpec& SS = Chunk.Mem.Scope();
5969 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
5971 const Type* ClsTy = TL.getClass();
5972 QualType ClsQT = QualType(ClsTy, 0);
5973 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5974 // Now copy source location info into the type loc component.
5975 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5976 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5977 case NestedNameSpecifier::Identifier:
5978 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
5980 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
5981 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
5982 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5983 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5987 case NestedNameSpecifier::TypeSpec:
5988 case NestedNameSpecifier::TypeSpecWithTemplate:
5989 if (isa<ElaboratedType>(ClsTy)) {
5990 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5991 ETLoc.setElaboratedKeywordLoc(SourceLocation());
5992 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5993 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5994 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5996 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
6000 case NestedNameSpecifier::Namespace:
6001 case NestedNameSpecifier::NamespaceAlias:
6002 case NestedNameSpecifier::Global:
6003 case NestedNameSpecifier::Super:
6004 llvm_unreachable("Nested-name-specifier must name a type");
6007 // Finally fill in MemberPointerLocInfo fields.
6008 TL.setStarLoc(SourceLocation::getFromRawEncoding(Chunk.Mem.StarLoc));
6009 TL.setClassTInfo(ClsTInfo);
6011 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6012 assert(Chunk.Kind == DeclaratorChunk::Reference);
6013 // 'Amp' is misleading: this might have been originally
6014 /// spelled with AmpAmp.
6015 TL.setAmpLoc(Chunk.Loc);
6017 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6018 assert(Chunk.Kind == DeclaratorChunk::Reference);
6019 assert(!Chunk.Ref.LValueRef);
6020 TL.setAmpAmpLoc(Chunk.Loc);
6022 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6023 assert(Chunk.Kind == DeclaratorChunk::Array);
6024 TL.setLBracketLoc(Chunk.Loc);
6025 TL.setRBracketLoc(Chunk.EndLoc);
6026 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6028 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6029 assert(Chunk.Kind == DeclaratorChunk::Function);
6030 TL.setLocalRangeBegin(Chunk.Loc);
6031 TL.setLocalRangeEnd(Chunk.EndLoc);
6033 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6034 TL.setLParenLoc(FTI.getLParenLoc());
6035 TL.setRParenLoc(FTI.getRParenLoc());
6036 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6037 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6038 TL.setParam(tpi++, Param);
6040 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
6042 void VisitParenTypeLoc(ParenTypeLoc TL) {
6043 assert(Chunk.Kind == DeclaratorChunk::Paren);
6044 TL.setLParenLoc(Chunk.Loc);
6045 TL.setRParenLoc(Chunk.EndLoc);
6047 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6048 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6049 TL.setKWLoc(Chunk.Loc);
6051 void VisitExtIntTypeLoc(ExtIntTypeLoc TL) {
6052 TL.setNameLoc(Chunk.Loc);
6054 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6055 TL.setExpansionLoc(Chunk.Loc);
6058 void VisitTypeLoc(TypeLoc TL) {
6059 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6062 } // end anonymous namespace
6064 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
6066 switch (Chunk.Kind) {
6067 case DeclaratorChunk::Function:
6068 case DeclaratorChunk::Array:
6069 case DeclaratorChunk::Paren:
6070 case DeclaratorChunk::Pipe:
6071 llvm_unreachable("cannot be _Atomic qualified");
6073 case DeclaratorChunk::Pointer:
6074 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
6077 case DeclaratorChunk::BlockPointer:
6078 case DeclaratorChunk::Reference:
6079 case DeclaratorChunk::MemberPointer:
6080 // FIXME: Provide a source location for the _Atomic keyword.
6085 ATL.setParensRange(SourceRange());
6089 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
6090 const ParsedAttributesView &Attrs) {
6091 for (const ParsedAttr &AL : Attrs) {
6092 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6093 DASTL.setAttrNameLoc(AL.getLoc());
6094 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6095 DASTL.setAttrOperandParensRange(SourceRange());
6101 "no address_space attribute found at the expected location!");
6104 static void fillMatrixTypeLoc(MatrixTypeLoc MTL,
6105 const ParsedAttributesView &Attrs) {
6106 for (const ParsedAttr &AL : Attrs) {
6107 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
6108 MTL.setAttrNameLoc(AL.getLoc());
6109 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
6110 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
6111 MTL.setAttrOperandParensRange(SourceRange());
6116 llvm_unreachable("no matrix_type attribute found at the expected location!");
6119 /// Create and instantiate a TypeSourceInfo with type source information.
6121 /// \param T QualType referring to the type as written in source code.
6123 /// \param ReturnTypeInfo For declarators whose return type does not show
6124 /// up in the normal place in the declaration specifiers (such as a C++
6125 /// conversion function), this pointer will refer to a type source information
6126 /// for that return type.
6127 static TypeSourceInfo *
6128 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6129 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6130 Sema &S = State.getSema();
6131 Declarator &D = State.getDeclarator();
6133 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
6134 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6136 // Handle parameter packs whose type is a pack expansion.
6137 if (isa<PackExpansionType>(T)) {
6138 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6139 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6142 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6143 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6144 // declarator chunk.
6145 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6146 fillAtomicQualLoc(ATL, D.getTypeObject(i));
6147 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6150 while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) {
6152 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6153 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6156 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
6157 fillAttributedTypeLoc(TL, State);
6158 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6161 while (DependentAddressSpaceTypeLoc TL =
6162 CurrTL.getAs<DependentAddressSpaceTypeLoc>()) {
6163 fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
6164 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6167 if (MatrixTypeLoc TL = CurrTL.getAs<MatrixTypeLoc>())
6168 fillMatrixTypeLoc(TL, D.getTypeObject(i).getAttrs());
6170 // FIXME: Ordering here?
6171 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
6172 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6174 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6175 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6178 // If we have different source information for the return type, use
6179 // that. This really only applies to C++ conversion functions.
6180 if (ReturnTypeInfo) {
6181 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6182 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6183 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6185 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6191 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6192 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
6193 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6194 // and Sema during declaration parsing. Try deallocating/caching them when
6195 // it's appropriate, instead of allocating them and keeping them around.
6196 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
6198 new (LocT) LocInfoType(T, TInfo);
6199 assert(LocT->getTypeClass() != T->getTypeClass() &&
6200 "LocInfoType's TypeClass conflicts with an existing Type class");
6201 return ParsedType::make(QualType(LocT, 0));
6204 void LocInfoType::getAsStringInternal(std::string &Str,
6205 const PrintingPolicy &Policy) const {
6206 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6207 " was used directly instead of getting the QualType through"
6208 " GetTypeFromParser");
6211 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
6212 // C99 6.7.6: Type names have no identifier. This is already validated by
6214 assert(D.getIdentifier() == nullptr &&
6215 "Type name should have no identifier!");
6217 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6218 QualType T = TInfo->getType();
6219 if (D.isInvalidType())
6222 // Make sure there are no unused decl attributes on the declarator.
6223 // We don't want to do this for ObjC parameters because we're going
6224 // to apply them to the actual parameter declaration.
6225 // Likewise, we don't want to do this for alias declarations, because
6226 // we are actually going to build a declaration from this eventually.
6227 if (D.getContext() != DeclaratorContext::ObjCParameterContext &&
6228 D.getContext() != DeclaratorContext::AliasDeclContext &&
6229 D.getContext() != DeclaratorContext::AliasTemplateContext)
6230 checkUnusedDeclAttributes(D);
6232 if (getLangOpts().CPlusPlus) {
6233 // Check that there are no default arguments (C++ only).
6234 CheckExtraCXXDefaultArguments(D);
6237 return CreateParsedType(T, TInfo);
6240 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
6241 QualType T = Context.getObjCInstanceType();
6242 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
6243 return CreateParsedType(T, TInfo);
6246 //===----------------------------------------------------------------------===//
6247 // Type Attribute Processing
6248 //===----------------------------------------------------------------------===//
6250 /// Build an AddressSpace index from a constant expression and diagnose any
6251 /// errors related to invalid address_spaces. Returns true on successfully
6252 /// building an AddressSpace index.
6253 static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6254 const Expr *AddrSpace,
6255 SourceLocation AttrLoc) {
6256 if (!AddrSpace->isValueDependent()) {
6257 llvm::APSInt addrSpace(32);
6258 if (!AddrSpace->isIntegerConstantExpr(addrSpace, S.Context)) {
6259 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6260 << "'address_space'" << AANT_ArgumentIntegerConstant
6261 << AddrSpace->getSourceRange();
6266 if (addrSpace.isSigned()) {
6267 if (addrSpace.isNegative()) {
6268 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6269 << AddrSpace->getSourceRange();
6272 addrSpace.setIsSigned(false);
6275 llvm::APSInt max(addrSpace.getBitWidth());
6277 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
6278 if (addrSpace > max) {
6279 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6280 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6285 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6289 // Default value for DependentAddressSpaceTypes
6290 ASIdx = LangAS::Default;
6294 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
6295 /// is uninstantiated. If instantiated it will apply the appropriate address
6296 /// space to the type. This function allows dependent template variables to be
6297 /// used in conjunction with the address_space attribute
6298 QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
6299 SourceLocation AttrLoc) {
6300 if (!AddrSpace->isValueDependent()) {
6301 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6305 return Context.getAddrSpaceQualType(T, ASIdx);
6308 // A check with similar intentions as checking if a type already has an
6309 // address space except for on a dependent types, basically if the
6310 // current type is already a DependentAddressSpaceType then its already
6311 // lined up to have another address space on it and we can't have
6312 // multiple address spaces on the one pointer indirection
6313 if (T->getAs<DependentAddressSpaceType>()) {
6314 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6318 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6321 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
6322 SourceLocation AttrLoc) {
6324 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6326 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6329 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6330 /// specified type. The attribute contains 1 argument, the id of the address
6331 /// space for the type.
6332 static void HandleAddressSpaceTypeAttribute(QualType &Type,
6333 const ParsedAttr &Attr,
6334 TypeProcessingState &State) {
6335 Sema &S = State.getSema();
6337 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6338 // qualified by an address-space qualifier."
6339 if (Type->isFunctionType()) {
6340 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6346 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6348 // Check the attribute arguments.
6349 if (Attr.getNumArgs() != 1) {
6350 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6357 if (Attr.isArgIdent(0)) {
6358 // Special case where the argument is a template id.
6360 SourceLocation TemplateKWLoc;
6362 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6364 ExprResult AddrSpace = S.ActOnIdExpression(
6365 S.getCurScope(), SS, TemplateKWLoc, id, /*HasTrailingLParen=*/false,
6366 /*IsAddressOfOperand=*/false);
6367 if (AddrSpace.isInvalid())
6370 ASArgExpr = static_cast<Expr *>(AddrSpace.get());
6372 ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6376 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6381 ASTContext &Ctx = S.Context;
6383 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6385 // If the expression is not value dependent (not templated), then we can
6386 // apply the address space qualifiers just to the equivalent type.
6387 // Otherwise, we make an AttributedType with the modified and equivalent
6388 // type the same, and wrap it in a DependentAddressSpaceType. When this
6389 // dependent type is resolved, the qualifier is added to the equivalent type
6392 if (!ASArgExpr->isValueDependent()) {
6393 QualType EquivType =
6394 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6395 if (EquivType.isNull()) {
6399 T = State.getAttributedType(ASAttr, Type, EquivType);
6401 T = State.getAttributedType(ASAttr, Type, Type);
6402 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6410 // The keyword-based type attributes imply which address space to use.
6411 ASIdx = Attr.asOpenCLLangAS();
6412 if (ASIdx == LangAS::Default)
6413 llvm_unreachable("Invalid address space");
6415 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6421 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
6425 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
6426 /// attribute on the specified type.
6428 /// Returns 'true' if the attribute was handled.
6429 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6430 ParsedAttr &attr, QualType &type) {
6431 bool NonObjCPointer = false;
6433 if (!type->isDependentType() && !type->isUndeducedType()) {
6434 if (const PointerType *ptr = type->getAs<PointerType>()) {
6435 QualType pointee = ptr->getPointeeType();
6436 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6438 // It is important not to lose the source info that there was an attribute
6439 // applied to non-objc pointer. We will create an attributed type but
6440 // its type will be the same as the original type.
6441 NonObjCPointer = true;
6442 } else if (!type->isObjCRetainableType()) {
6446 // Don't accept an ownership attribute in the declspec if it would
6447 // just be the return type of a block pointer.
6448 if (state.isProcessingDeclSpec()) {
6449 Declarator &D = state.getDeclarator();
6450 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
6451 /*onlyBlockPointers=*/true))
6456 Sema &S = state.getSema();
6457 SourceLocation AttrLoc = attr.getLoc();
6458 if (AttrLoc.isMacroID())
6460 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
6462 if (!attr.isArgIdent(0)) {
6463 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6464 << AANT_ArgumentString;
6469 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6470 Qualifiers::ObjCLifetime lifetime;
6471 if (II->isStr("none"))
6472 lifetime = Qualifiers::OCL_ExplicitNone;
6473 else if (II->isStr("strong"))
6474 lifetime = Qualifiers::OCL_Strong;
6475 else if (II->isStr("weak"))
6476 lifetime = Qualifiers::OCL_Weak;
6477 else if (II->isStr("autoreleasing"))
6478 lifetime = Qualifiers::OCL_Autoreleasing;
6480 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6485 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6486 // outside of ARC mode.
6487 if (!S.getLangOpts().ObjCAutoRefCount &&
6488 lifetime != Qualifiers::OCL_Weak &&
6489 lifetime != Qualifiers::OCL_ExplicitNone) {
6493 SplitQualType underlyingType = type.split();
6495 // Check for redundant/conflicting ownership qualifiers.
6496 if (Qualifiers::ObjCLifetime previousLifetime
6497 = type.getQualifiers().getObjCLifetime()) {
6498 // If it's written directly, that's an error.
6499 if (S.Context.hasDirectOwnershipQualifier(type)) {
6500 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6505 // Otherwise, if the qualifiers actually conflict, pull sugar off
6506 // and remove the ObjCLifetime qualifiers.
6507 if (previousLifetime != lifetime) {
6508 // It's possible to have multiple local ObjCLifetime qualifiers. We
6509 // can't stop after we reach a type that is directly qualified.
6510 const Type *prevTy = nullptr;
6511 while (!prevTy || prevTy != underlyingType.Ty) {
6512 prevTy = underlyingType.Ty;
6513 underlyingType = underlyingType.getSingleStepDesugaredType();
6515 underlyingType.Quals.removeObjCLifetime();
6519 underlyingType.Quals.addObjCLifetime(lifetime);
6521 if (NonObjCPointer) {
6522 StringRef name = attr.getAttrName()->getName();
6524 case Qualifiers::OCL_None:
6525 case Qualifiers::OCL_ExplicitNone:
6527 case Qualifiers::OCL_Strong: name = "__strong"; break;
6528 case Qualifiers::OCL_Weak: name = "__weak"; break;
6529 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6531 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6532 << TDS_ObjCObjOrBlock << type;
6535 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6536 // because having both 'T' and '__unsafe_unretained T' exist in the type
6537 // system causes unfortunate widespread consistency problems. (For example,
6538 // they're not considered compatible types, and we mangle them identicially
6539 // as template arguments.) These problems are all individually fixable,
6540 // but it's easier to just not add the qualifier and instead sniff it out
6541 // in specific places using isObjCInertUnsafeUnretainedType().
6543 // Doing this does means we miss some trivial consistency checks that
6544 // would've triggered in ARC, but that's better than trying to solve all
6545 // the coexistence problems with __unsafe_unretained.
6546 if (!S.getLangOpts().ObjCAutoRefCount &&
6547 lifetime == Qualifiers::OCL_ExplicitNone) {
6548 type = state.getAttributedType(
6549 createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
6554 QualType origType = type;
6555 if (!NonObjCPointer)
6556 type = S.Context.getQualifiedType(underlyingType);
6558 // If we have a valid source location for the attribute, use an
6559 // AttributedType instead.
6560 if (AttrLoc.isValid()) {
6561 type = state.getAttributedType(::new (S.Context)
6562 ObjCOwnershipAttr(S.Context, attr, II),
6566 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6567 unsigned diagnostic, QualType type) {
6568 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
6569 S.DelayedDiagnostics.add(
6570 sema::DelayedDiagnostic::makeForbiddenType(
6571 S.getSourceManager().getExpansionLoc(loc),
6572 diagnostic, type, /*ignored*/ 0));
6574 S.Diag(loc, diagnostic);
6578 // Sometimes, __weak isn't allowed.
6579 if (lifetime == Qualifiers::OCL_Weak &&
6580 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6582 // Use a specialized diagnostic if the runtime just doesn't support them.
6583 unsigned diagnostic =
6584 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6585 : diag::err_arc_weak_no_runtime);
6587 // In any case, delay the diagnostic until we know what we're parsing.
6588 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6594 // Forbid __weak for class objects marked as
6595 // objc_arc_weak_reference_unavailable
6596 if (lifetime == Qualifiers::OCL_Weak) {
6597 if (const ObjCObjectPointerType *ObjT =
6598 type->getAs<ObjCObjectPointerType>()) {
6599 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6600 if (Class->isArcWeakrefUnavailable()) {
6601 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6602 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6603 diag::note_class_declared);
6612 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6613 /// attribute on the specified type. Returns true to indicate that
6614 /// the attribute was handled, false to indicate that the type does
6615 /// not permit the attribute.
6616 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6618 Sema &S = state.getSema();
6620 // Delay if this isn't some kind of pointer.
6621 if (!type->isPointerType() &&
6622 !type->isObjCObjectPointerType() &&
6623 !type->isBlockPointerType())
6626 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
6627 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
6632 // Check the attribute arguments.
6633 if (!attr.isArgIdent(0)) {
6634 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
6635 << attr << AANT_ArgumentString;
6639 Qualifiers::GC GCAttr;
6640 if (attr.getNumArgs() > 1) {
6641 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
6647 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6648 if (II->isStr("weak"))
6649 GCAttr = Qualifiers::Weak;
6650 else if (II->isStr("strong"))
6651 GCAttr = Qualifiers::Strong;
6653 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
6659 QualType origType = type;
6660 type = S.Context.getObjCGCQualType(origType, GCAttr);
6662 // Make an attributed type to preserve the source information.
6663 if (attr.getLoc().isValid())
6664 type = state.getAttributedType(
6665 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
6671 /// A helper class to unwrap a type down to a function for the
6672 /// purposes of applying attributes there.
6675 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
6676 /// if (unwrapped.isFunctionType()) {
6677 /// const FunctionType *fn = unwrapped.get();
6678 /// // change fn somehow
6679 /// T = unwrapped.wrap(fn);
6681 struct FunctionTypeUnwrapper {
6695 const FunctionType *Fn;
6696 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
6698 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
6700 const Type *Ty = T.getTypePtr();
6701 if (isa<FunctionType>(Ty)) {
6702 Fn = cast<FunctionType>(Ty);
6704 } else if (isa<ParenType>(Ty)) {
6705 T = cast<ParenType>(Ty)->getInnerType();
6706 Stack.push_back(Parens);
6707 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
6708 isa<IncompleteArrayType>(Ty)) {
6709 T = cast<ArrayType>(Ty)->getElementType();
6710 Stack.push_back(Array);
6711 } else if (isa<PointerType>(Ty)) {
6712 T = cast<PointerType>(Ty)->getPointeeType();
6713 Stack.push_back(Pointer);
6714 } else if (isa<BlockPointerType>(Ty)) {
6715 T = cast<BlockPointerType>(Ty)->getPointeeType();
6716 Stack.push_back(BlockPointer);
6717 } else if (isa<MemberPointerType>(Ty)) {
6718 T = cast<MemberPointerType>(Ty)->getPointeeType();
6719 Stack.push_back(MemberPointer);
6720 } else if (isa<ReferenceType>(Ty)) {
6721 T = cast<ReferenceType>(Ty)->getPointeeType();
6722 Stack.push_back(Reference);
6723 } else if (isa<AttributedType>(Ty)) {
6724 T = cast<AttributedType>(Ty)->getEquivalentType();
6725 Stack.push_back(Attributed);
6726 } else if (isa<MacroQualifiedType>(Ty)) {
6727 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
6728 Stack.push_back(MacroQualified);
6730 const Type *DTy = Ty->getUnqualifiedDesugaredType();
6736 T = QualType(DTy, 0);
6737 Stack.push_back(Desugar);
6742 bool isFunctionType() const { return (Fn != nullptr); }
6743 const FunctionType *get() const { return Fn; }
6745 QualType wrap(Sema &S, const FunctionType *New) {
6746 // If T wasn't modified from the unwrapped type, do nothing.
6747 if (New == get()) return Original;
6750 return wrap(S.Context, Original, 0);
6754 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
6755 if (I == Stack.size())
6756 return C.getQualifiedType(Fn, Old.getQualifiers());
6758 // Build up the inner type, applying the qualifiers from the old
6759 // type to the new type.
6760 SplitQualType SplitOld = Old.split();
6762 // As a special case, tail-recurse if there are no qualifiers.
6763 if (SplitOld.Quals.empty())
6764 return wrap(C, SplitOld.Ty, I);
6765 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
6768 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
6769 if (I == Stack.size()) return QualType(Fn, 0);
6771 switch (static_cast<WrapKind>(Stack[I++])) {
6773 // This is the point at which we potentially lose source
6775 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
6778 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
6781 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
6782 return C.getParenType(New);
6785 case MacroQualified:
6786 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
6789 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
6790 QualType New = wrap(C, CAT->getElementType(), I);
6791 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
6792 CAT->getSizeModifier(),
6793 CAT->getIndexTypeCVRQualifiers());
6796 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
6797 QualType New = wrap(C, VAT->getElementType(), I);
6798 return C.getVariableArrayType(
6799 New, VAT->getSizeExpr(), VAT->getSizeModifier(),
6800 VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
6803 const auto *IAT = cast<IncompleteArrayType>(Old);
6804 QualType New = wrap(C, IAT->getElementType(), I);
6805 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
6806 IAT->getIndexTypeCVRQualifiers());
6810 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
6811 return C.getPointerType(New);
6814 case BlockPointer: {
6815 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
6816 return C.getBlockPointerType(New);
6819 case MemberPointer: {
6820 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
6821 QualType New = wrap(C, OldMPT->getPointeeType(), I);
6822 return C.getMemberPointerType(New, OldMPT->getClass());
6826 const ReferenceType *OldRef = cast<ReferenceType>(Old);
6827 QualType New = wrap(C, OldRef->getPointeeType(), I);
6828 if (isa<LValueReferenceType>(OldRef))
6829 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
6831 return C.getRValueReferenceType(New);
6835 llvm_unreachable("unknown wrapping kind");
6838 } // end anonymous namespace
6840 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
6841 ParsedAttr &PAttr, QualType &Type) {
6842 Sema &S = State.getSema();
6845 switch (PAttr.getKind()) {
6846 default: llvm_unreachable("Unknown attribute kind");
6847 case ParsedAttr::AT_Ptr32:
6848 A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
6850 case ParsedAttr::AT_Ptr64:
6851 A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
6853 case ParsedAttr::AT_SPtr:
6854 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
6856 case ParsedAttr::AT_UPtr:
6857 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
6861 llvm::SmallSet<attr::Kind, 2> Attrs;
6862 attr::Kind NewAttrKind = A->getKind();
6863 QualType Desugared = Type;
6864 const AttributedType *AT = dyn_cast<AttributedType>(Type);
6866 Attrs.insert(AT->getAttrKind());
6867 Desugared = AT->getModifiedType();
6868 AT = dyn_cast<AttributedType>(Desugared);
6871 // You cannot specify duplicate type attributes, so if the attribute has
6872 // already been applied, flag it.
6873 if (Attrs.count(NewAttrKind)) {
6874 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
6877 Attrs.insert(NewAttrKind);
6879 // You cannot have both __sptr and __uptr on the same type, nor can you
6880 // have __ptr32 and __ptr64.
6881 if (Attrs.count(attr::Ptr32) && Attrs.count(attr::Ptr64)) {
6882 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
6886 } else if (Attrs.count(attr::SPtr) && Attrs.count(attr::UPtr)) {
6887 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
6893 // Pointer type qualifiers can only operate on pointer types, but not
6894 // pointer-to-member types.
6896 // FIXME: Should we really be disallowing this attribute if there is any
6897 // type sugar between it and the pointer (other than attributes)? Eg, this
6898 // disallows the attribute on a parenthesized pointer.
6899 // And if so, should we really allow *any* type attribute?
6900 if (!isa<PointerType>(Desugared)) {
6901 if (Type->isMemberPointerType())
6902 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
6904 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
6908 // Add address space to type based on its attributes.
6909 LangAS ASIdx = LangAS::Default;
6910 uint64_t PtrWidth = S.Context.getTargetInfo().getPointerWidth(0);
6911 if (PtrWidth == 32) {
6912 if (Attrs.count(attr::Ptr64))
6913 ASIdx = LangAS::ptr64;
6914 else if (Attrs.count(attr::UPtr))
6915 ASIdx = LangAS::ptr32_uptr;
6916 } else if (PtrWidth == 64 && Attrs.count(attr::Ptr32)) {
6917 if (Attrs.count(attr::UPtr))
6918 ASIdx = LangAS::ptr32_uptr;
6920 ASIdx = LangAS::ptr32_sptr;
6923 QualType Pointee = Type->getPointeeType();
6924 if (ASIdx != LangAS::Default)
6925 Pointee = S.Context.getAddrSpaceQualType(
6926 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
6927 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
6931 /// Map a nullability attribute kind to a nullability kind.
6932 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
6934 case ParsedAttr::AT_TypeNonNull:
6935 return NullabilityKind::NonNull;
6937 case ParsedAttr::AT_TypeNullable:
6938 return NullabilityKind::Nullable;
6940 case ParsedAttr::AT_TypeNullUnspecified:
6941 return NullabilityKind::Unspecified;
6944 llvm_unreachable("not a nullability attribute kind");
6948 /// Applies a nullability type specifier to the given type, if possible.
6950 /// \param state The type processing state.
6952 /// \param type The type to which the nullability specifier will be
6953 /// added. On success, this type will be updated appropriately.
6955 /// \param attr The attribute as written on the type.
6957 /// \param allowOnArrayType Whether to accept nullability specifiers on an
6958 /// array type (e.g., because it will decay to a pointer).
6960 /// \returns true if a problem has been diagnosed, false on success.
6961 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
6964 bool allowOnArrayType) {
6965 Sema &S = state.getSema();
6967 NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
6968 SourceLocation nullabilityLoc = attr.getLoc();
6969 bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
6971 recordNullabilitySeen(S, nullabilityLoc);
6973 // Check for existing nullability attributes on the type.
6974 QualType desugared = type;
6975 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
6976 // Check whether there is already a null
6977 if (auto existingNullability = attributed->getImmediateNullability()) {
6978 // Duplicated nullability.
6979 if (nullability == *existingNullability) {
6980 S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
6981 << DiagNullabilityKind(nullability, isContextSensitive)
6982 << FixItHint::CreateRemoval(nullabilityLoc);
6987 // Conflicting nullability.
6988 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
6989 << DiagNullabilityKind(nullability, isContextSensitive)
6990 << DiagNullabilityKind(*existingNullability, false);
6994 desugared = attributed->getModifiedType();
6997 // If there is already a different nullability specifier, complain.
6998 // This (unlike the code above) looks through typedefs that might
6999 // have nullability specifiers on them, which means we cannot
7000 // provide a useful Fix-It.
7001 if (auto existingNullability = desugared->getNullability(S.Context)) {
7002 if (nullability != *existingNullability) {
7003 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7004 << DiagNullabilityKind(nullability, isContextSensitive)
7005 << DiagNullabilityKind(*existingNullability, false);
7007 // Try to find the typedef with the existing nullability specifier.
7008 if (auto typedefType = desugared->getAs<TypedefType>()) {
7009 TypedefNameDecl *typedefDecl = typedefType->getDecl();
7010 QualType underlyingType = typedefDecl->getUnderlyingType();
7011 if (auto typedefNullability
7012 = AttributedType::stripOuterNullability(underlyingType)) {
7013 if (*typedefNullability == *existingNullability) {
7014 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7015 << DiagNullabilityKind(*existingNullability, false);
7024 // If this definitely isn't a pointer type, reject the specifier.
7025 if (!desugared->canHaveNullability() &&
7026 !(allowOnArrayType && desugared->isArrayType())) {
7027 S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
7028 << DiagNullabilityKind(nullability, isContextSensitive) << type;
7032 // For the context-sensitive keywords/Objective-C property
7033 // attributes, require that the type be a single-level pointer.
7034 if (isContextSensitive) {
7035 // Make sure that the pointee isn't itself a pointer type.
7036 const Type *pointeeType = nullptr;
7037 if (desugared->isArrayType())
7038 pointeeType = desugared->getArrayElementTypeNoTypeQual();
7039 else if (desugared->isAnyPointerType())
7040 pointeeType = desugared->getPointeeType().getTypePtr();
7042 if (pointeeType && (pointeeType->isAnyPointerType() ||
7043 pointeeType->isObjCObjectPointerType() ||
7044 pointeeType->isMemberPointerType())) {
7045 S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
7046 << DiagNullabilityKind(nullability, true)
7048 S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
7049 << DiagNullabilityKind(nullability, false)
7051 << FixItHint::CreateReplacement(nullabilityLoc,
7052 getNullabilitySpelling(nullability));
7057 // Form the attributed type.
7058 type = state.getAttributedType(
7059 createNullabilityAttr(S.Context, attr, nullability), type, type);
7063 /// Check the application of the Objective-C '__kindof' qualifier to
7065 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7067 Sema &S = state.getSema();
7069 if (isa<ObjCTypeParamType>(type)) {
7070 // Build the attributed type to record where __kindof occurred.
7071 type = state.getAttributedType(
7072 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
7076 // Find out if it's an Objective-C object or object pointer type;
7077 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7078 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7079 : type->getAs<ObjCObjectType>();
7081 // If not, we can't apply __kindof.
7083 // FIXME: Handle dependent types that aren't yet object types.
7084 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7089 // Rebuild the "equivalent" type, which pushes __kindof down into
7091 // There is no need to apply kindof on an unqualified id type.
7092 QualType equivType = S.Context.getObjCObjectType(
7093 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7094 objType->getProtocols(),
7095 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7097 // If we started with an object pointer type, rebuild it.
7099 equivType = S.Context.getObjCObjectPointerType(equivType);
7100 if (auto nullability = type->getNullability(S.Context)) {
7101 // We create a nullability attribute from the __kindof attribute.
7102 // Make sure that will make sense.
7103 assert(attr.getAttributeSpellingListIndex() == 0 &&
7104 "multiple spellings for __kindof?");
7105 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7106 A->setImplicit(true);
7107 equivType = state.getAttributedType(A, equivType, equivType);
7111 // Build the attributed type to record where __kindof occurred.
7112 type = state.getAttributedType(
7113 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
7117 /// Distribute a nullability type attribute that cannot be applied to
7118 /// the type specifier to a pointer, block pointer, or member pointer
7119 /// declarator, complaining if necessary.
7121 /// \returns true if the nullability annotation was distributed, false
7123 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7124 QualType type, ParsedAttr &attr) {
7125 Declarator &declarator = state.getDeclarator();
7127 /// Attempt to move the attribute to the specified chunk.
7128 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7129 // If there is already a nullability attribute there, don't add
7131 if (hasNullabilityAttr(chunk.getAttrs()))
7134 // Complain about the nullability qualifier being in the wrong
7141 PK_MemberFunctionPointer,
7143 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7145 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7146 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7148 auto diag = state.getSema().Diag(attr.getLoc(),
7149 diag::warn_nullability_declspec)
7150 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
7151 attr.isContextSensitiveKeywordAttribute())
7153 << static_cast<unsigned>(pointerKind);
7155 // FIXME: MemberPointer chunks don't carry the location of the *.
7156 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7157 diag << FixItHint::CreateRemoval(attr.getLoc())
7158 << FixItHint::CreateInsertion(
7159 state.getSema().getPreprocessor().getLocForEndOfToken(
7161 " " + attr.getAttrName()->getName().str() + " ");
7164 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7169 // Move it to the outermost pointer, member pointer, or block
7170 // pointer declarator.
7171 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7172 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7173 switch (chunk.Kind) {
7174 case DeclaratorChunk::Pointer:
7175 case DeclaratorChunk::BlockPointer:
7176 case DeclaratorChunk::MemberPointer:
7177 return moveToChunk(chunk, false);
7179 case DeclaratorChunk::Paren:
7180 case DeclaratorChunk::Array:
7183 case DeclaratorChunk::Function:
7184 // Try to move past the return type to a function/block/member
7185 // function pointer.
7186 if (DeclaratorChunk *dest = maybeMovePastReturnType(
7188 /*onlyBlockPointers=*/false)) {
7189 return moveToChunk(*dest, true);
7194 // Don't walk through these.
7195 case DeclaratorChunk::Reference:
7196 case DeclaratorChunk::Pipe:
7204 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
7205 assert(!Attr.isInvalid());
7206 switch (Attr.getKind()) {
7208 llvm_unreachable("not a calling convention attribute");
7209 case ParsedAttr::AT_CDecl:
7210 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7211 case ParsedAttr::AT_FastCall:
7212 return createSimpleAttr<FastCallAttr>(Ctx, Attr);
7213 case ParsedAttr::AT_StdCall:
7214 return createSimpleAttr<StdCallAttr>(Ctx, Attr);
7215 case ParsedAttr::AT_ThisCall:
7216 return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
7217 case ParsedAttr::AT_RegCall:
7218 return createSimpleAttr<RegCallAttr>(Ctx, Attr);
7219 case ParsedAttr::AT_Pascal:
7220 return createSimpleAttr<PascalAttr>(Ctx, Attr);
7221 case ParsedAttr::AT_SwiftCall:
7222 return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
7223 case ParsedAttr::AT_VectorCall:
7224 return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
7225 case ParsedAttr::AT_AArch64VectorPcs:
7226 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
7227 case ParsedAttr::AT_Pcs: {
7228 // The attribute may have had a fixit applied where we treated an
7229 // identifier as a string literal. The contents of the string are valid,
7230 // but the form may not be.
7232 if (Attr.isArgExpr(0))
7233 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7235 Str = Attr.getArgAsIdent(0)->Ident->getName();
7236 PcsAttr::PCSType Type;
7237 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7238 llvm_unreachable("already validated the attribute");
7239 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7241 case ParsedAttr::AT_IntelOclBicc:
7242 return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
7243 case ParsedAttr::AT_MSABI:
7244 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7245 case ParsedAttr::AT_SysVABI:
7246 return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
7247 case ParsedAttr::AT_PreserveMost:
7248 return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
7249 case ParsedAttr::AT_PreserveAll:
7250 return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
7252 llvm_unreachable("unexpected attribute kind!");
7255 /// Process an individual function attribute. Returns true to
7256 /// indicate that the attribute was handled, false if it wasn't.
7257 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7259 Sema &S = state.getSema();
7261 FunctionTypeUnwrapper unwrapped(S, type);
7263 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
7264 if (S.CheckAttrNoArgs(attr))
7267 // Delay if this is not a function type.
7268 if (!unwrapped.isFunctionType())
7271 // Otherwise we can process right away.
7272 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
7273 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7277 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
7278 // Delay if this is not a function type.
7279 if (!unwrapped.isFunctionType())
7282 // Ignore if we don't have CMSE enabled.
7283 if (!S.getLangOpts().Cmse) {
7284 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
7289 // Otherwise we can process right away.
7290 FunctionType::ExtInfo EI =
7291 unwrapped.get()->getExtInfo().withCmseNSCall(true);
7292 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7296 // ns_returns_retained is not always a type attribute, but if we got
7297 // here, we're treating it as one right now.
7298 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
7299 if (attr.getNumArgs()) return true;
7301 // Delay if this is not a function type.
7302 if (!unwrapped.isFunctionType())
7305 // Check whether the return type is reasonable.
7306 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
7307 unwrapped.get()->getReturnType()))
7310 // Only actually change the underlying type in ARC builds.
7311 QualType origType = type;
7312 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
7313 FunctionType::ExtInfo EI
7314 = unwrapped.get()->getExtInfo().withProducesResult(true);
7315 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7317 type = state.getAttributedType(
7318 createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
7323 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
7324 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7327 // Delay if this is not a function type.
7328 if (!unwrapped.isFunctionType())
7331 FunctionType::ExtInfo EI =
7332 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
7333 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7337 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
7338 if (!S.getLangOpts().CFProtectionBranch) {
7339 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
7344 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7347 // If this is not a function type, warning will be asserted by subject
7349 if (!unwrapped.isFunctionType())
7352 FunctionType::ExtInfo EI =
7353 unwrapped.get()->getExtInfo().withNoCfCheck(true);
7354 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7358 if (attr.getKind() == ParsedAttr::AT_Regparm) {
7360 if (S.CheckRegparmAttr(attr, value))
7363 // Delay if this is not a function type.
7364 if (!unwrapped.isFunctionType())
7367 // Diagnose regparm with fastcall.
7368 const FunctionType *fn = unwrapped.get();
7369 CallingConv CC = fn->getCallConv();
7370 if (CC == CC_X86FastCall) {
7371 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7372 << FunctionType::getNameForCallConv(CC)
7378 FunctionType::ExtInfo EI =
7379 unwrapped.get()->getExtInfo().withRegParm(value);
7380 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7384 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
7385 // Delay if this is not a function type.
7386 if (!unwrapped.isFunctionType())
7389 if (S.CheckAttrNoArgs(attr)) {
7394 // Otherwise we can process right away.
7395 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
7397 // MSVC ignores nothrow if it is in conflict with an explicit exception
7399 if (Proto->hasExceptionSpec()) {
7400 switch (Proto->getExceptionSpecType()) {
7402 llvm_unreachable("This doesn't have an exception spec!");
7404 case EST_DynamicNone:
7405 case EST_BasicNoexcept:
7406 case EST_NoexceptTrue:
7408 // Exception spec doesn't conflict with nothrow, so don't warn.
7411 case EST_Uninstantiated:
7412 case EST_DependentNoexcept:
7413 case EST_Unevaluated:
7414 // We don't have enough information to properly determine if there is a
7415 // conflict, so suppress the warning.
7419 case EST_NoexceptFalse:
7420 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
7426 type = unwrapped.wrap(
7428 .getFunctionTypeWithExceptionSpec(
7430 FunctionProtoType::ExceptionSpecInfo{EST_NoThrow})
7431 ->getAs<FunctionType>());
7435 // Delay if the type didn't work out to a function.
7436 if (!unwrapped.isFunctionType()) return false;
7438 // Otherwise, a calling convention.
7440 if (S.CheckCallingConvAttr(attr, CC))
7443 const FunctionType *fn = unwrapped.get();
7444 CallingConv CCOld = fn->getCallConv();
7445 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
7448 // Error out on when there's already an attribute on the type
7449 // and the CCs don't match.
7450 if (S.getCallingConvAttributedType(type)) {
7451 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7452 << FunctionType::getNameForCallConv(CC)
7453 << FunctionType::getNameForCallConv(CCOld);
7459 // Diagnose use of variadic functions with calling conventions that
7460 // don't support them (e.g. because they're callee-cleanup).
7461 // We delay warning about this on unprototyped function declarations
7462 // until after redeclaration checking, just in case we pick up a
7463 // prototype that way. And apparently we also "delay" warning about
7464 // unprototyped function types in general, despite not necessarily having
7465 // much ability to diagnose it later.
7466 if (!supportsVariadicCall(CC)) {
7467 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
7468 if (FnP && FnP->isVariadic()) {
7469 // stdcall and fastcall are ignored with a warning for GCC and MS
7471 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
7472 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
7473 << FunctionType::getNameForCallConv(CC)
7474 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
7477 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
7478 << FunctionType::getNameForCallConv(CC);
7482 // Also diagnose fastcall with regparm.
7483 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
7484 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7485 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
7490 // Modify the CC from the wrapped function type, wrap it all back, and then
7491 // wrap the whole thing in an AttributedType as written. The modified type
7492 // might have a different CC if we ignored the attribute.
7493 QualType Equivalent;
7497 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
7499 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7501 type = state.getAttributedType(CCAttr, type, Equivalent);
7505 bool Sema::hasExplicitCallingConv(QualType T) {
7506 const AttributedType *AT;
7508 // Stop if we'd be stripping off a typedef sugar node to reach the
7510 while ((AT = T->getAs<AttributedType>()) &&
7511 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
7512 if (AT->isCallingConv())
7514 T = AT->getModifiedType();
7519 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
7520 SourceLocation Loc) {
7521 FunctionTypeUnwrapper Unwrapped(*this, T);
7522 const FunctionType *FT = Unwrapped.get();
7523 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
7524 cast<FunctionProtoType>(FT)->isVariadic());
7525 CallingConv CurCC = FT->getCallConv();
7526 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
7531 // MS compiler ignores explicit calling convention attributes on structors. We
7532 // should do the same.
7533 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
7534 // Issue a warning on ignored calling convention -- except of __stdcall.
7535 // Again, this is what MS compiler does.
7536 if (CurCC != CC_X86StdCall)
7537 Diag(Loc, diag::warn_cconv_unsupported)
7538 << FunctionType::getNameForCallConv(CurCC)
7539 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
7540 // Default adjustment.
7542 // Only adjust types with the default convention. For example, on Windows
7543 // we should adjust a __cdecl type to __thiscall for instance methods, and a
7544 // __thiscall type to __cdecl for static methods.
7545 CallingConv DefaultCC =
7546 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
7548 if (CurCC != DefaultCC || DefaultCC == ToCC)
7551 if (hasExplicitCallingConv(T))
7555 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
7556 QualType Wrapped = Unwrapped.wrap(*this, FT);
7557 T = Context.getAdjustedType(T, Wrapped);
7560 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
7561 /// and float scalars, although arrays, pointers, and function return values are
7562 /// allowed in conjunction with this construct. Aggregates with this attribute
7563 /// are invalid, even if they are of the same size as a corresponding scalar.
7564 /// The raw attribute should contain precisely 1 argument, the vector size for
7565 /// the variable, measured in bytes. If curType and rawAttr are well formed,
7566 /// this routine will return a new vector type.
7567 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
7569 // Check the attribute arguments.
7570 if (Attr.getNumArgs() != 1) {
7571 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7578 // Special case where the argument is a template id.
7579 if (Attr.isArgIdent(0)) {
7581 SourceLocation TemplateKWLoc;
7583 Id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
7585 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
7586 Id, /*HasTrailingLParen=*/false,
7587 /*IsAddressOfOperand=*/false);
7589 if (Size.isInvalid())
7591 SizeExpr = Size.get();
7593 SizeExpr = Attr.getArgAsExpr(0);
7596 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
7603 /// Process the OpenCL-like ext_vector_type attribute when it occurs on
7605 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7607 // check the attribute arguments.
7608 if (Attr.getNumArgs() != 1) {
7609 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7616 // Special case where the argument is a template id.
7617 if (Attr.isArgIdent(0)) {
7619 SourceLocation TemplateKWLoc;
7621 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
7623 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
7624 id, /*HasTrailingLParen=*/false,
7625 /*IsAddressOfOperand=*/false);
7626 if (Size.isInvalid())
7629 sizeExpr = Size.get();
7631 sizeExpr = Attr.getArgAsExpr(0);
7634 // Create the vector type.
7635 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
7640 static bool isPermittedNeonBaseType(QualType &Ty,
7641 VectorType::VectorKind VecKind, Sema &S) {
7642 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
7646 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
7648 // Signed poly is mathematically wrong, but has been baked into some ABIs by
7650 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
7651 Triple.getArch() == llvm::Triple::aarch64_32 ||
7652 Triple.getArch() == llvm::Triple::aarch64_be;
7653 if (VecKind == VectorType::NeonPolyVector) {
7654 if (IsPolyUnsigned) {
7655 // AArch64 polynomial vectors are unsigned.
7656 return BTy->getKind() == BuiltinType::UChar ||
7657 BTy->getKind() == BuiltinType::UShort ||
7658 BTy->getKind() == BuiltinType::ULong ||
7659 BTy->getKind() == BuiltinType::ULongLong;
7661 // AArch32 polynomial vectors are signed.
7662 return BTy->getKind() == BuiltinType::SChar ||
7663 BTy->getKind() == BuiltinType::Short ||
7664 BTy->getKind() == BuiltinType::LongLong;
7668 // Non-polynomial vector types: the usual suspects are allowed, as well as
7669 // float64_t on AArch64.
7670 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
7671 BTy->getKind() == BuiltinType::Double)
7674 return BTy->getKind() == BuiltinType::SChar ||
7675 BTy->getKind() == BuiltinType::UChar ||
7676 BTy->getKind() == BuiltinType::Short ||
7677 BTy->getKind() == BuiltinType::UShort ||
7678 BTy->getKind() == BuiltinType::Int ||
7679 BTy->getKind() == BuiltinType::UInt ||
7680 BTy->getKind() == BuiltinType::Long ||
7681 BTy->getKind() == BuiltinType::ULong ||
7682 BTy->getKind() == BuiltinType::LongLong ||
7683 BTy->getKind() == BuiltinType::ULongLong ||
7684 BTy->getKind() == BuiltinType::Float ||
7685 BTy->getKind() == BuiltinType::Half ||
7686 BTy->getKind() == BuiltinType::BFloat16;
7689 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
7690 /// "neon_polyvector_type" attributes are used to create vector types that
7691 /// are mangled according to ARM's ABI. Otherwise, these types are identical
7692 /// to those created with the "vector_size" attribute. Unlike "vector_size"
7693 /// the argument to these Neon attributes is the number of vector elements,
7694 /// not the vector size in bytes. The vector width and element type must
7695 /// match one of the standard Neon vector types.
7696 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7697 Sema &S, VectorType::VectorKind VecKind) {
7698 // Target must have NEON (or MVE, whose vectors are similar enough
7699 // not to need a separate attribute)
7700 if (!S.Context.getTargetInfo().hasFeature("neon") &&
7701 !S.Context.getTargetInfo().hasFeature("mve")) {
7702 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr;
7706 // Check the attribute arguments.
7707 if (Attr.getNumArgs() != 1) {
7708 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7713 // The number of elements must be an ICE.
7714 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
7715 llvm::APSInt numEltsInt(32);
7716 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
7717 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
7718 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
7719 << Attr << AANT_ArgumentIntegerConstant
7720 << numEltsExpr->getSourceRange();
7724 // Only certain element types are supported for Neon vectors.
7725 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
7726 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
7731 // The total size of the vector must be 64 or 128 bits.
7732 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
7733 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
7734 unsigned vecSize = typeSize * numElts;
7735 if (vecSize != 64 && vecSize != 128) {
7736 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
7741 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
7744 static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
7747 const VectorType *VT = dyn_cast<VectorType>(CurType);
7748 if (!VT || VT->getVectorKind() != VectorType::NeonVector) {
7749 State.getSema().Diag(Attr.getLoc(),
7750 diag::err_attribute_arm_mve_polymorphism);
7756 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
7757 State.getSema().Context, Attr),
7761 /// Handle OpenCL Access Qualifier Attribute.
7762 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
7764 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
7765 if (!(CurType->isImageType() || CurType->isPipeType())) {
7766 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
7771 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
7772 QualType BaseTy = TypedefTy->desugar();
7774 std::string PrevAccessQual;
7775 if (BaseTy->isPipeType()) {
7776 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
7777 OpenCLAccessAttr *Attr =
7778 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
7779 PrevAccessQual = Attr->getSpelling();
7781 PrevAccessQual = "read_only";
7783 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
7785 switch (ImgType->getKind()) {
7786 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7787 case BuiltinType::Id: \
7788 PrevAccessQual = #Access; \
7790 #include "clang/Basic/OpenCLImageTypes.def"
7792 llvm_unreachable("Unable to find corresponding image type.");
7795 llvm_unreachable("unexpected type");
7797 StringRef AttrName = Attr.getAttrName()->getName();
7798 if (PrevAccessQual == AttrName.ltrim("_")) {
7799 // Duplicated qualifiers
7800 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
7801 << AttrName << Attr.getRange();
7803 // Contradicting qualifiers
7804 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
7807 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
7808 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
7809 } else if (CurType->isPipeType()) {
7810 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
7811 QualType ElemType = CurType->getAs<PipeType>()->getElementType();
7812 CurType = S.Context.getWritePipeType(ElemType);
7817 /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
7818 static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7820 if (!S.getLangOpts().MatrixTypes) {
7821 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
7825 if (Attr.getNumArgs() != 2) {
7826 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
7831 Expr *RowsExpr = nullptr;
7832 Expr *ColsExpr = nullptr;
7834 // TODO: Refactor parameter extraction into separate function
7835 // Get the number of rows
7836 if (Attr.isArgIdent(0)) {
7838 SourceLocation TemplateKeywordLoc;
7840 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
7841 ExprResult Rows = S.ActOnIdExpression(S.getCurScope(), SS,
7842 TemplateKeywordLoc, id, false, false);
7844 if (Rows.isInvalid())
7845 // TODO: maybe a good error message would be nice here
7847 RowsExpr = Rows.get();
7849 assert(Attr.isArgExpr(0) &&
7850 "Argument to should either be an identity or expression");
7851 RowsExpr = Attr.getArgAsExpr(0);
7854 // Get the number of columns
7855 if (Attr.isArgIdent(1)) {
7857 SourceLocation TemplateKeywordLoc;
7859 id.setIdentifier(Attr.getArgAsIdent(1)->Ident, Attr.getLoc());
7860 ExprResult Columns = S.ActOnIdExpression(
7861 S.getCurScope(), SS, TemplateKeywordLoc, id, false, false);
7863 if (Columns.isInvalid())
7864 // TODO: a good error message would be nice here
7866 RowsExpr = Columns.get();
7868 assert(Attr.isArgExpr(1) &&
7869 "Argument to should either be an identity or expression");
7870 ColsExpr = Attr.getArgAsExpr(1);
7873 // Create the matrix type.
7874 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
7879 static void HandleLifetimeBoundAttr(TypeProcessingState &State,
7882 if (State.getDeclarator().isDeclarationOfFunction()) {
7883 CurType = State.getAttributedType(
7884 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
7887 Attr.diagnoseAppertainsTo(State.getSema(), nullptr);
7891 static bool isAddressSpaceKind(const ParsedAttr &attr) {
7892 auto attrKind = attr.getKind();
7894 return attrKind == ParsedAttr::AT_AddressSpace ||
7895 attrKind == ParsedAttr::AT_OpenCLPrivateAddressSpace ||
7896 attrKind == ParsedAttr::AT_OpenCLGlobalAddressSpace ||
7897 attrKind == ParsedAttr::AT_OpenCLLocalAddressSpace ||
7898 attrKind == ParsedAttr::AT_OpenCLConstantAddressSpace ||
7899 attrKind == ParsedAttr::AT_OpenCLGenericAddressSpace;
7902 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
7903 TypeAttrLocation TAL,
7904 ParsedAttributesView &attrs) {
7905 // Scan through and apply attributes to this type where it makes sense. Some
7906 // attributes (such as __address_space__, __vector_size__, etc) apply to the
7907 // type, but others can be present in the type specifiers even though they
7908 // apply to the decl. Here we apply type attributes and ignore the rest.
7910 // This loop modifies the list pretty frequently, but we still need to make
7911 // sure we visit every element once. Copy the attributes list, and iterate
7913 ParsedAttributesView AttrsCopy{attrs};
7915 state.setParsedNoDeref(false);
7917 for (ParsedAttr &attr : AttrsCopy) {
7919 // Skip attributes that were marked to be invalid.
7920 if (attr.isInvalid())
7923 if (attr.isCXX11Attribute()) {
7924 // [[gnu::...]] attributes are treated as declaration attributes, so may
7925 // not appertain to a DeclaratorChunk. If we handle them as type
7926 // attributes, accept them in that position and diagnose the GCC
7928 if (attr.isGNUScope()) {
7929 bool IsTypeAttr = attr.isTypeAttr();
7930 if (TAL == TAL_DeclChunk) {
7931 state.getSema().Diag(attr.getLoc(),
7933 ? diag::warn_gcc_ignores_type_attr
7934 : diag::warn_cxx11_gnu_attribute_on_type)
7939 } else if (TAL != TAL_DeclChunk && !isAddressSpaceKind(attr)) {
7940 // Otherwise, only consider type processing for a C++11 attribute if
7941 // it's actually been applied to a type.
7942 // We also allow C++11 address_space and
7943 // OpenCL language address space attributes to pass through.
7948 // If this is an attribute we can handle, do so now,
7949 // otherwise, add it to the FnAttrs list for rechaining.
7950 switch (attr.getKind()) {
7952 // A C++11 attribute on a declarator chunk must appertain to a type.
7953 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
7954 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
7956 attr.setUsedAsTypeAttr();
7960 case ParsedAttr::UnknownAttribute:
7961 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
7962 state.getSema().Diag(attr.getLoc(),
7963 diag::warn_unknown_attribute_ignored)
7967 case ParsedAttr::IgnoredAttribute:
7970 case ParsedAttr::AT_MayAlias:
7971 // FIXME: This attribute needs to actually be handled, but if we ignore
7972 // it it breaks large amounts of Linux software.
7973 attr.setUsedAsTypeAttr();
7975 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
7976 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
7977 case ParsedAttr::AT_OpenCLLocalAddressSpace:
7978 case ParsedAttr::AT_OpenCLConstantAddressSpace:
7979 case ParsedAttr::AT_OpenCLGenericAddressSpace:
7980 case ParsedAttr::AT_AddressSpace:
7981 HandleAddressSpaceTypeAttribute(type, attr, state);
7982 attr.setUsedAsTypeAttr();
7984 OBJC_POINTER_TYPE_ATTRS_CASELIST:
7985 if (!handleObjCPointerTypeAttr(state, attr, type))
7986 distributeObjCPointerTypeAttr(state, attr, type);
7987 attr.setUsedAsTypeAttr();
7989 case ParsedAttr::AT_VectorSize:
7990 HandleVectorSizeAttr(type, attr, state.getSema());
7991 attr.setUsedAsTypeAttr();
7993 case ParsedAttr::AT_ExtVectorType:
7994 HandleExtVectorTypeAttr(type, attr, state.getSema());
7995 attr.setUsedAsTypeAttr();
7997 case ParsedAttr::AT_NeonVectorType:
7998 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
7999 VectorType::NeonVector);
8000 attr.setUsedAsTypeAttr();
8002 case ParsedAttr::AT_NeonPolyVectorType:
8003 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8004 VectorType::NeonPolyVector);
8005 attr.setUsedAsTypeAttr();
8007 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
8008 HandleArmMveStrictPolymorphismAttr(state, type, attr);
8009 attr.setUsedAsTypeAttr();
8012 case ParsedAttr::AT_OpenCLAccess:
8013 HandleOpenCLAccessAttr(type, attr, state.getSema());
8014 attr.setUsedAsTypeAttr();
8016 case ParsedAttr::AT_LifetimeBound:
8017 if (TAL == TAL_DeclChunk)
8018 HandleLifetimeBoundAttr(state, type, attr);
8021 case ParsedAttr::AT_NoDeref: {
8022 ASTContext &Ctx = state.getSema().Context;
8023 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
8025 attr.setUsedAsTypeAttr();
8026 state.setParsedNoDeref(true);
8030 case ParsedAttr::AT_MatrixType:
8031 HandleMatrixTypeAttr(type, attr, state.getSema());
8032 attr.setUsedAsTypeAttr();
8035 MS_TYPE_ATTRS_CASELIST:
8036 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
8037 attr.setUsedAsTypeAttr();
8041 NULLABILITY_TYPE_ATTRS_CASELIST:
8042 // Either add nullability here or try to distribute it. We
8043 // don't want to distribute the nullability specifier past any
8044 // dependent type, because that complicates the user model.
8045 if (type->canHaveNullability() || type->isDependentType() ||
8046 type->isArrayType() ||
8047 !distributeNullabilityTypeAttr(state, type, attr)) {
8049 if (TAL == TAL_DeclChunk)
8050 endIndex = state.getCurrentChunkIndex();
8052 endIndex = state.getDeclarator().getNumTypeObjects();
8053 bool allowOnArrayType =
8054 state.getDeclarator().isPrototypeContext() &&
8055 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
8056 if (checkNullabilityTypeSpecifier(
8060 allowOnArrayType)) {
8064 attr.setUsedAsTypeAttr();
8068 case ParsedAttr::AT_ObjCKindOf:
8069 // '__kindof' must be part of the decl-specifiers.
8076 state.getSema().Diag(attr.getLoc(),
8077 diag::err_objc_kindof_wrong_position)
8078 << FixItHint::CreateRemoval(attr.getLoc())
8079 << FixItHint::CreateInsertion(
8080 state.getDeclarator().getDeclSpec().getBeginLoc(),
8085 // Apply it regardless.
8086 if (checkObjCKindOfType(state, type, attr))
8090 case ParsedAttr::AT_NoThrow:
8091 // Exception Specifications aren't generally supported in C mode throughout
8092 // clang, so revert to attribute-based handling for C.
8093 if (!state.getSema().getLangOpts().CPlusPlus)
8096 FUNCTION_TYPE_ATTRS_CASELIST:
8097 attr.setUsedAsTypeAttr();
8099 // Never process function type attributes as part of the
8100 // declaration-specifiers.
8101 if (TAL == TAL_DeclSpec)
8102 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
8104 // Otherwise, handle the possible delays.
8105 else if (!handleFunctionTypeAttr(state, attr, type))
8106 distributeFunctionTypeAttr(state, attr, type);
8108 case ParsedAttr::AT_AcquireHandle: {
8109 if (!type->isFunctionType())
8112 if (attr.getNumArgs() != 1) {
8113 state.getSema().Diag(attr.getLoc(),
8114 diag::err_attribute_wrong_number_arguments)
8120 StringRef HandleType;
8121 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
8123 type = state.getAttributedType(
8124 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
8126 attr.setUsedAsTypeAttr();
8131 // Handle attributes that are defined in a macro. We do not want this to be
8132 // applied to ObjC builtin attributes.
8133 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
8134 !type.getQualifiers().hasObjCLifetime() &&
8135 !type.getQualifiers().hasObjCGCAttr() &&
8136 attr.getKind() != ParsedAttr::AT_ObjCGC &&
8137 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
8138 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
8139 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
8140 state.setExpansionLocForMacroQualifiedType(
8141 cast<MacroQualifiedType>(type.getTypePtr()),
8142 attr.getMacroExpansionLoc());
8146 if (!state.getSema().getLangOpts().OpenCL ||
8147 type.getAddressSpace() != LangAS::Default)
8151 void Sema::completeExprArrayBound(Expr *E) {
8152 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8153 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8154 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
8155 auto *Def = Var->getDefinition();
8157 SourceLocation PointOfInstantiation = E->getExprLoc();
8158 runWithSufficientStackSpace(PointOfInstantiation, [&] {
8159 InstantiateVariableDefinition(PointOfInstantiation, Var);
8161 Def = Var->getDefinition();
8163 // If we don't already have a point of instantiation, and we managed
8164 // to instantiate a definition, this is the point of instantiation.
8165 // Otherwise, we don't request an end-of-TU instantiation, so this is
8166 // not a point of instantiation.
8167 // FIXME: Is this really the right behavior?
8168 if (Var->getPointOfInstantiation().isInvalid() && Def) {
8169 assert(Var->getTemplateSpecializationKind() ==
8170 TSK_ImplicitInstantiation &&
8171 "explicit instantiation with no point of instantiation");
8172 Var->setTemplateSpecializationKind(
8173 Var->getTemplateSpecializationKind(), PointOfInstantiation);
8177 // Update the type to the definition's type both here and within the
8181 QualType T = Def->getType();
8183 // FIXME: Update the type on all intervening expressions.
8187 // We still go on to try to complete the type independently, as it
8188 // may also require instantiations or diagnostics if it remains
8195 /// Ensure that the type of the given expression is complete.
8197 /// This routine checks whether the expression \p E has a complete type. If the
8198 /// expression refers to an instantiable construct, that instantiation is
8199 /// performed as needed to complete its type. Furthermore
8200 /// Sema::RequireCompleteType is called for the expression's type (or in the
8201 /// case of a reference type, the referred-to type).
8203 /// \param E The expression whose type is required to be complete.
8204 /// \param Kind Selects which completeness rules should be applied.
8205 /// \param Diagnoser The object that will emit a diagnostic if the type is
8208 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
8210 bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
8211 TypeDiagnoser &Diagnoser) {
8212 QualType T = E->getType();
8214 // Incomplete array types may be completed by the initializer attached to
8215 // their definitions. For static data members of class templates and for
8216 // variable templates, we need to instantiate the definition to get this
8217 // initializer and complete the type.
8218 if (T->isIncompleteArrayType()) {
8219 completeExprArrayBound(E);
8223 // FIXME: Are there other cases which require instantiating something other
8224 // than the type to complete the type of an expression?
8226 return RequireCompleteType(E->getExprLoc(), T, Kind, Diagnoser);
8229 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
8230 BoundTypeDiagnoser<> Diagnoser(DiagID);
8231 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
8234 /// Ensure that the type T is a complete type.
8236 /// This routine checks whether the type @p T is complete in any
8237 /// context where a complete type is required. If @p T is a complete
8238 /// type, returns false. If @p T is a class template specialization,
8239 /// this routine then attempts to perform class template
8240 /// instantiation. If instantiation fails, or if @p T is incomplete
8241 /// and cannot be completed, issues the diagnostic @p diag (giving it
8242 /// the type @p T) and returns true.
8244 /// @param Loc The location in the source that the incomplete type
8245 /// diagnostic should refer to.
8247 /// @param T The type that this routine is examining for completeness.
8249 /// @param Kind Selects which completeness rules should be applied.
8251 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
8252 /// @c false otherwise.
8253 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
8254 CompleteTypeKind Kind,
8255 TypeDiagnoser &Diagnoser) {
8256 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
8258 if (const TagType *Tag = T->getAs<TagType>()) {
8259 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
8260 Tag->getDecl()->setCompleteDefinitionRequired();
8261 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
8267 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
8268 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
8272 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
8273 // and isolate from other C++ specific checks.
8274 StructuralEquivalenceContext Ctx(
8275 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
8276 StructuralEquivalenceKind::Default,
8277 false /*StrictTypeSpelling*/, true /*Complain*/,
8278 true /*ErrorOnTagTypeMismatch*/);
8279 return Ctx.IsEquivalent(D, Suggested);
8282 /// Determine whether there is any declaration of \p D that was ever a
8283 /// definition (perhaps before module merging) and is currently visible.
8284 /// \param D The definition of the entity.
8285 /// \param Suggested Filled in with the declaration that should be made visible
8286 /// in order to provide a definition of this entity.
8287 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
8288 /// not defined. This only matters for enums with a fixed underlying
8289 /// type, since in all other cases, a type is complete if and only if it
8291 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
8292 bool OnlyNeedComplete) {
8293 // Easy case: if we don't have modules, all declarations are visible.
8294 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
8297 // If this definition was instantiated from a template, map back to the
8298 // pattern from which it was instantiated.
8299 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
8300 // We're in the middle of defining it; this definition should be treated
8303 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
8304 if (auto *Pattern = RD->getTemplateInstantiationPattern())
8306 D = RD->getDefinition();
8307 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
8308 if (auto *Pattern = ED->getTemplateInstantiationPattern())
8310 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
8311 // If the enum has a fixed underlying type, it may have been forward
8312 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
8313 // the enum and assign it the underlying type of `int`. Since we're only
8314 // looking for a complete type (not a definition), any visible declaration
8316 *Suggested = nullptr;
8317 for (auto *Redecl : ED->redecls()) {
8318 if (isVisible(Redecl))
8320 if (Redecl->isThisDeclarationADefinition() ||
8321 (Redecl->isCanonicalDecl() && !*Suggested))
8322 *Suggested = Redecl;
8326 D = ED->getDefinition();
8327 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8328 if (auto *Pattern = FD->getTemplateInstantiationPattern())
8330 D = FD->getDefinition();
8331 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
8332 if (auto *Pattern = VD->getTemplateInstantiationPattern())
8334 D = VD->getDefinition();
8336 assert(D && "missing definition for pattern of instantiated definition");
8340 auto DefinitionIsVisible = [&] {
8341 // The (primary) definition might be in a visible module.
8345 // A visible module might have a merged definition instead.
8346 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D)
8347 : hasVisibleMergedDefinition(D)) {
8348 if (CodeSynthesisContexts.empty() &&
8349 !getLangOpts().ModulesLocalVisibility) {
8350 // Cache the fact that this definition is implicitly visible because
8351 // there is a visible merged definition.
8352 D->setVisibleDespiteOwningModule();
8360 if (DefinitionIsVisible())
8363 // The external source may have additional definitions of this entity that are
8364 // visible, so complete the redeclaration chain now and ask again.
8365 if (auto *Source = Context.getExternalSource()) {
8366 Source->CompleteRedeclChain(D);
8367 return DefinitionIsVisible();
8373 /// Locks in the inheritance model for the given class and all of its bases.
8374 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
8375 RD = RD->getMostRecentNonInjectedDecl();
8376 if (!RD->hasAttr<MSInheritanceAttr>()) {
8377 MSInheritanceModel IM;
8378 bool BestCase = false;
8379 switch (S.MSPointerToMemberRepresentationMethod) {
8380 case LangOptions::PPTMK_BestCase:
8382 IM = RD->calculateInheritanceModel();
8384 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
8385 IM = MSInheritanceModel::Single;
8387 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
8388 IM = MSInheritanceModel::Multiple;
8390 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
8391 IM = MSInheritanceModel::Unspecified;
8395 SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid()
8396 ? S.ImplicitMSInheritanceAttrLoc
8397 : RD->getSourceRange();
8398 RD->addAttr(MSInheritanceAttr::CreateImplicit(
8399 S.getASTContext(), BestCase, Loc, AttributeCommonInfo::AS_Microsoft,
8400 MSInheritanceAttr::Spelling(IM)));
8401 S.Consumer.AssignInheritanceModel(RD);
8405 /// The implementation of RequireCompleteType
8406 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
8407 CompleteTypeKind Kind,
8408 TypeDiagnoser *Diagnoser) {
8409 // FIXME: Add this assertion to make sure we always get instantiation points.
8410 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
8411 // FIXME: Add this assertion to help us flush out problems with
8412 // checking for dependent types and type-dependent expressions.
8414 // assert(!T->isDependentType() &&
8415 // "Can't ask whether a dependent type is complete");
8417 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
8418 if (!MPTy->getClass()->isDependentType()) {
8419 if (getLangOpts().CompleteMemberPointers &&
8420 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
8421 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind,
8422 diag::err_memptr_incomplete))
8425 // We lock in the inheritance model once somebody has asked us to ensure
8426 // that a pointer-to-member type is complete.
8427 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8428 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
8429 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
8434 NamedDecl *Def = nullptr;
8435 bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless);
8436 bool Incomplete = (T->isIncompleteType(&Def) ||
8437 (!AcceptSizeless && T->isSizelessBuiltinType()));
8439 // Check that any necessary explicit specializations are visible. For an
8440 // enum, we just need the declaration, so don't check this.
8441 if (Def && !isa<EnumDecl>(Def))
8442 checkSpecializationVisibility(Loc, Def);
8444 // If we have a complete type, we're done.
8446 // If we know about the definition but it is not visible, complain.
8447 NamedDecl *SuggestedDef = nullptr;
8449 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
8450 // If the user is going to see an error here, recover by making the
8451 // definition visible.
8452 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
8453 if (Diagnoser && SuggestedDef)
8454 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
8455 /*Recover*/TreatAsComplete);
8456 return !TreatAsComplete;
8457 } else if (Def && !TemplateInstCallbacks.empty()) {
8458 CodeSynthesisContext TempInst;
8459 TempInst.Kind = CodeSynthesisContext::Memoization;
8460 TempInst.Template = Def;
8461 TempInst.Entity = Def;
8462 TempInst.PointOfInstantiation = Loc;
8463 atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
8464 atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
8470 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
8471 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
8473 // Give the external source a chance to provide a definition of the type.
8474 // This is kept separate from completing the redeclaration chain so that
8475 // external sources such as LLDB can avoid synthesizing a type definition
8476 // unless it's actually needed.
8478 // Avoid diagnosing invalid decls as incomplete.
8479 if (Def->isInvalidDecl())
8482 // Give the external AST source a chance to complete the type.
8483 if (auto *Source = Context.getExternalSource()) {
8484 if (Tag && Tag->hasExternalLexicalStorage())
8485 Source->CompleteType(Tag);
8486 if (IFace && IFace->hasExternalLexicalStorage())
8487 Source->CompleteType(IFace);
8488 // If the external source completed the type, go through the motions
8489 // again to ensure we're allowed to use the completed type.
8490 if (!T->isIncompleteType())
8491 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
8495 // If we have a class template specialization or a class member of a
8496 // class template specialization, or an array with known size of such,
8497 // try to instantiate it.
8498 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
8499 bool Instantiated = false;
8500 bool Diagnosed = false;
8501 if (RD->isDependentContext()) {
8502 // Don't try to instantiate a dependent class (eg, a member template of
8503 // an instantiated class template specialization).
8504 // FIXME: Can this ever happen?
8505 } else if (auto *ClassTemplateSpec =
8506 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
8507 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
8508 runWithSufficientStackSpace(Loc, [&] {
8509 Diagnosed = InstantiateClassTemplateSpecialization(
8510 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
8511 /*Complain=*/Diagnoser);
8513 Instantiated = true;
8516 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
8517 if (!RD->isBeingDefined() && Pattern) {
8518 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
8519 assert(MSI && "Missing member specialization information?");
8520 // This record was instantiated from a class within a template.
8521 if (MSI->getTemplateSpecializationKind() !=
8522 TSK_ExplicitSpecialization) {
8523 runWithSufficientStackSpace(Loc, [&] {
8524 Diagnosed = InstantiateClass(Loc, RD, Pattern,
8525 getTemplateInstantiationArgs(RD),
8526 TSK_ImplicitInstantiation,
8527 /*Complain=*/Diagnoser);
8529 Instantiated = true;
8535 // Instantiate* might have already complained that the template is not
8536 // defined, if we asked it to.
8537 if (Diagnoser && Diagnosed)
8539 // If we instantiated a definition, check that it's usable, even if
8540 // instantiation produced an error, so that repeated calls to this
8541 // function give consistent answers.
8542 if (!T->isIncompleteType())
8543 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
8547 // FIXME: If we didn't instantiate a definition because of an explicit
8548 // specialization declaration, check that it's visible.
8553 Diagnoser->diagnose(*this, Loc, T);
8555 // If the type was a forward declaration of a class/struct/union
8556 // type, produce a note.
8557 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
8558 Diag(Tag->getLocation(),
8559 Tag->isBeingDefined() ? diag::note_type_being_defined
8560 : diag::note_forward_declaration)
8561 << Context.getTagDeclType(Tag);
8563 // If the Objective-C class was a forward declaration, produce a note.
8564 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
8565 Diag(IFace->getLocation(), diag::note_forward_class);
8567 // If we have external information that we can use to suggest a fix,
8570 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
8575 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
8576 CompleteTypeKind Kind, unsigned DiagID) {
8577 BoundTypeDiagnoser<> Diagnoser(DiagID);
8578 return RequireCompleteType(Loc, T, Kind, Diagnoser);
8581 /// Get diagnostic %select index for tag kind for
8582 /// literal type diagnostic message.
8583 /// WARNING: Indexes apply to particular diagnostics only!
8585 /// \returns diagnostic %select index.
8586 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
8588 case TTK_Struct: return 0;
8589 case TTK_Interface: return 1;
8590 case TTK_Class: return 2;
8591 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
8595 /// Ensure that the type T is a literal type.
8597 /// This routine checks whether the type @p T is a literal type. If @p T is an
8598 /// incomplete type, an attempt is made to complete it. If @p T is a literal
8599 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
8600 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
8601 /// it the type @p T), along with notes explaining why the type is not a
8602 /// literal type, and returns true.
8604 /// @param Loc The location in the source that the non-literal type
8605 /// diagnostic should refer to.
8607 /// @param T The type that this routine is examining for literalness.
8609 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
8611 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
8612 /// @c false otherwise.
8613 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
8614 TypeDiagnoser &Diagnoser) {
8615 assert(!T->isDependentType() && "type should not be dependent");
8617 QualType ElemType = Context.getBaseElementType(T);
8618 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
8619 T->isLiteralType(Context))
8622 Diagnoser.diagnose(*this, Loc, T);
8624 if (T->isVariableArrayType())
8627 const RecordType *RT = ElemType->getAs<RecordType>();
8631 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
8633 // A partially-defined class type can't be a literal type, because a literal
8634 // class type must have a trivial destructor (which can't be checked until
8635 // the class definition is complete).
8636 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
8639 // [expr.prim.lambda]p3:
8640 // This class type is [not] a literal type.
8641 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
8642 Diag(RD->getLocation(), diag::note_non_literal_lambda);
8646 // If the class has virtual base classes, then it's not an aggregate, and
8647 // cannot have any constexpr constructors or a trivial default constructor,
8648 // so is non-literal. This is better to diagnose than the resulting absence
8649 // of constexpr constructors.
8650 if (RD->getNumVBases()) {
8651 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
8652 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
8653 for (const auto &I : RD->vbases())
8654 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
8655 << I.getSourceRange();
8656 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
8657 !RD->hasTrivialDefaultConstructor()) {
8658 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
8659 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
8660 for (const auto &I : RD->bases()) {
8661 if (!I.getType()->isLiteralType(Context)) {
8662 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
8663 << RD << I.getType() << I.getSourceRange();
8667 for (const auto *I : RD->fields()) {
8668 if (!I->getType()->isLiteralType(Context) ||
8669 I->getType().isVolatileQualified()) {
8670 Diag(I->getLocation(), diag::note_non_literal_field)
8671 << RD << I << I->getType()
8672 << I->getType().isVolatileQualified();
8676 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
8677 : !RD->hasTrivialDestructor()) {
8678 // All fields and bases are of literal types, so have trivial or constexpr
8679 // destructors. If this class's destructor is non-trivial / non-constexpr,
8680 // it must be user-declared.
8681 CXXDestructorDecl *Dtor = RD->getDestructor();
8682 assert(Dtor && "class has literal fields and bases but no dtor?");
8686 if (getLangOpts().CPlusPlus20) {
8687 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
8690 Diag(Dtor->getLocation(), Dtor->isUserProvided()
8691 ? diag::note_non_literal_user_provided_dtor
8692 : diag::note_non_literal_nontrivial_dtor)
8694 if (!Dtor->isUserProvided())
8695 SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
8703 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
8704 BoundTypeDiagnoser<> Diagnoser(DiagID);
8705 return RequireLiteralType(Loc, T, Diagnoser);
8708 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
8709 /// by the nested-name-specifier contained in SS, and that is (re)declared by
8710 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
8711 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
8712 const CXXScopeSpec &SS, QualType T,
8713 TagDecl *OwnedTagDecl) {
8716 NestedNameSpecifier *NNS;
8718 NNS = SS.getScopeRep();
8720 if (Keyword == ETK_None)
8724 return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl);
8727 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
8728 assert(!E->hasPlaceholderType() && "unexpected placeholder");
8730 if (!getLangOpts().CPlusPlus && E->refersToBitField())
8731 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
8733 if (!E->isTypeDependent()) {
8734 QualType T = E->getType();
8735 if (const TagType *TT = T->getAs<TagType>())
8736 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
8738 return Context.getTypeOfExprType(E);
8741 /// getDecltypeForExpr - Given an expr, will return the decltype for
8742 /// that expression, according to the rules in C++11
8743 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
8744 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
8745 if (E->isTypeDependent())
8746 return S.Context.DependentTy;
8748 // C++11 [dcl.type.simple]p4:
8749 // The type denoted by decltype(e) is defined as follows:
8751 // - if e is an unparenthesized id-expression or an unparenthesized class
8752 // member access (5.2.5), decltype(e) is the type of the entity named
8753 // by e. If there is no such entity, or if e names a set of overloaded
8754 // functions, the program is ill-formed;
8756 // We apply the same rules for Objective-C ivar and property references.
8757 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8758 const ValueDecl *VD = DRE->getDecl();
8759 return VD->getType();
8760 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8761 if (const ValueDecl *VD = ME->getMemberDecl())
8762 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
8763 return VD->getType();
8764 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
8765 return IR->getDecl()->getType();
8766 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
8767 if (PR->isExplicitProperty())
8768 return PR->getExplicitProperty()->getType();
8769 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
8770 return PE->getType();
8773 // C++11 [expr.lambda.prim]p18:
8774 // Every occurrence of decltype((x)) where x is a possibly
8775 // parenthesized id-expression that names an entity of automatic
8776 // storage duration is treated as if x were transformed into an
8777 // access to a corresponding data member of the closure type that
8778 // would have been declared if x were an odr-use of the denoted
8780 using namespace sema;
8781 if (S.getCurLambda()) {
8782 if (isa<ParenExpr>(E)) {
8783 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8784 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8785 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
8787 return S.Context.getLValueReferenceType(T);
8794 // C++11 [dcl.type.simple]p4:
8796 QualType T = E->getType();
8797 switch (E->getValueKind()) {
8798 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
8800 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
8801 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
8803 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
8804 // - otherwise, decltype(e) is the type of e.
8805 case VK_RValue: break;
8811 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
8812 bool AsUnevaluated) {
8813 assert(!E->hasPlaceholderType() && "unexpected placeholder");
8815 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
8816 E->HasSideEffects(Context, false)) {
8817 // The expression operand for decltype is in an unevaluated expression
8818 // context, so side effects could result in unintended consequences.
8819 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8822 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
8825 QualType Sema::BuildUnaryTransformType(QualType BaseType,
8826 UnaryTransformType::UTTKind UKind,
8827 SourceLocation Loc) {
8829 case UnaryTransformType::EnumUnderlyingType:
8830 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
8831 Diag(Loc, diag::err_only_enums_have_underlying_types);
8834 QualType Underlying = BaseType;
8835 if (!BaseType->isDependentType()) {
8836 // The enum could be incomplete if we're parsing its definition or
8837 // recovering from an error.
8838 NamedDecl *FwdDecl = nullptr;
8839 if (BaseType->isIncompleteType(&FwdDecl)) {
8840 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
8841 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
8845 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
8846 assert(ED && "EnumType has no EnumDecl");
8848 DiagnoseUseOfDecl(ED, Loc);
8850 Underlying = ED->getIntegerType();
8851 assert(!Underlying.isNull());
8853 return Context.getUnaryTransformType(BaseType, Underlying,
8854 UnaryTransformType::EnumUnderlyingType);
8857 llvm_unreachable("unknown unary transform type");
8860 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
8861 if (!T->isDependentType()) {
8862 // FIXME: It isn't entirely clear whether incomplete atomic types
8863 // are allowed or not; for simplicity, ban them for the moment.
8864 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
8867 int DisallowedKind = -1;
8868 if (T->isArrayType())
8870 else if (T->isFunctionType())
8872 else if (T->isReferenceType())
8874 else if (T->isAtomicType())
8876 else if (T.hasQualifiers())
8878 else if (T->isSizelessType())
8880 else if (!T.isTriviallyCopyableType(Context))
8881 // Some other non-trivially-copyable type (probably a C++ class)
8883 else if (T->isExtIntType()) {
8887 if (DisallowedKind != -1) {
8888 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
8892 // FIXME: Do we need any handling for ARC here?
8895 // Build the pointer type.
8896 return Context.getAtomicType(T);