1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements type-related semantic analysis.
12 //===----------------------------------------------------------------------===//
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.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/ScopeInfo.h"
31 #include "clang/Sema/SemaInternal.h"
32 #include "clang/Sema/Template.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/StringSwitch.h"
36 #include "llvm/Support/ErrorHandling.h"
38 using namespace clang;
40 enum TypeDiagSelector {
46 /// isOmittedBlockReturnType - Return true if this declarator is missing a
47 /// return type because this is a omitted return type on a block literal.
48 static bool isOmittedBlockReturnType(const Declarator &D) {
49 if (D.getContext() != Declarator::BlockLiteralContext ||
50 D.getDeclSpec().hasTypeSpecifier())
53 if (D.getNumTypeObjects() == 0)
54 return true; // ^{ ... }
56 if (D.getNumTypeObjects() == 1 &&
57 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
58 return true; // ^(int X, float Y) { ... }
63 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
64 /// doesn't apply to the given type.
65 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
67 TypeDiagSelector WhichType;
68 bool useExpansionLoc = true;
69 switch (attr.getKind()) {
70 case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break;
71 case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
73 // Assume everything else was a function attribute.
74 WhichType = TDS_Function;
75 useExpansionLoc = false;
79 SourceLocation loc = attr.getLoc();
80 StringRef name = attr.getName()->getName();
82 // The GC attributes are usually written with macros; special-case them.
83 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
85 if (useExpansionLoc && loc.isMacroID() && II) {
86 if (II->isStr("strong")) {
87 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
88 } else if (II->isStr("weak")) {
89 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
93 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
97 // objc_gc applies to Objective-C pointers or, otherwise, to the
98 // smallest available pointer type (i.e. 'void*' in 'void**').
99 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
100 case AttributeList::AT_ObjCGC: \
101 case AttributeList::AT_ObjCOwnership
103 // Calling convention attributes.
104 #define CALLING_CONV_ATTRS_CASELIST \
105 case AttributeList::AT_CDecl: \
106 case AttributeList::AT_FastCall: \
107 case AttributeList::AT_StdCall: \
108 case AttributeList::AT_ThisCall: \
109 case AttributeList::AT_RegCall: \
110 case AttributeList::AT_Pascal: \
111 case AttributeList::AT_SwiftCall: \
112 case AttributeList::AT_VectorCall: \
113 case AttributeList::AT_MSABI: \
114 case AttributeList::AT_SysVABI: \
115 case AttributeList::AT_Pcs: \
116 case AttributeList::AT_IntelOclBicc: \
117 case AttributeList::AT_PreserveMost: \
118 case AttributeList::AT_PreserveAll
120 // Function type attributes.
121 #define FUNCTION_TYPE_ATTRS_CASELIST \
122 case AttributeList::AT_NoReturn: \
123 case AttributeList::AT_Regparm: \
124 case AttributeList::AT_AnyX86NoCallerSavedRegisters: \
125 CALLING_CONV_ATTRS_CASELIST
127 // Microsoft-specific type qualifiers.
128 #define MS_TYPE_ATTRS_CASELIST \
129 case AttributeList::AT_Ptr32: \
130 case AttributeList::AT_Ptr64: \
131 case AttributeList::AT_SPtr: \
132 case AttributeList::AT_UPtr
134 // Nullability qualifiers.
135 #define NULLABILITY_TYPE_ATTRS_CASELIST \
136 case AttributeList::AT_TypeNonNull: \
137 case AttributeList::AT_TypeNullable: \
138 case AttributeList::AT_TypeNullUnspecified
141 /// An object which stores processing state for the entire
142 /// GetTypeForDeclarator process.
143 class TypeProcessingState {
146 /// The declarator being processed.
147 Declarator &declarator;
149 /// The index of the declarator chunk we're currently processing.
150 /// May be the total number of valid chunks, indicating the
154 /// Whether there are non-trivial modifications to the decl spec.
157 /// Whether we saved the attributes in the decl spec.
160 /// The original set of attributes on the DeclSpec.
161 SmallVector<AttributeList*, 2> savedAttrs;
163 /// A list of attributes to diagnose the uselessness of when the
164 /// processing is complete.
165 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
168 TypeProcessingState(Sema &sema, Declarator &declarator)
169 : sema(sema), declarator(declarator),
170 chunkIndex(declarator.getNumTypeObjects()),
171 trivial(true), hasSavedAttrs(false) {}
173 Sema &getSema() const {
177 Declarator &getDeclarator() const {
181 bool isProcessingDeclSpec() const {
182 return chunkIndex == declarator.getNumTypeObjects();
185 unsigned getCurrentChunkIndex() const {
189 void setCurrentChunkIndex(unsigned idx) {
190 assert(idx <= declarator.getNumTypeObjects());
194 AttributeList *&getCurrentAttrListRef() const {
195 if (isProcessingDeclSpec())
196 return getMutableDeclSpec().getAttributes().getListRef();
197 return declarator.getTypeObject(chunkIndex).getAttrListRef();
200 /// Save the current set of attributes on the DeclSpec.
201 void saveDeclSpecAttrs() {
202 // Don't try to save them multiple times.
203 if (hasSavedAttrs) return;
205 DeclSpec &spec = getMutableDeclSpec();
206 for (AttributeList *attr = spec.getAttributes().getList(); attr;
207 attr = attr->getNext())
208 savedAttrs.push_back(attr);
209 trivial &= savedAttrs.empty();
210 hasSavedAttrs = true;
213 /// Record that we had nowhere to put the given type attribute.
214 /// We will diagnose such attributes later.
215 void addIgnoredTypeAttr(AttributeList &attr) {
216 ignoredTypeAttrs.push_back(&attr);
219 /// Diagnose all the ignored type attributes, given that the
220 /// declarator worked out to the given type.
221 void diagnoseIgnoredTypeAttrs(QualType type) const {
222 for (auto *Attr : ignoredTypeAttrs)
223 diagnoseBadTypeAttribute(getSema(), *Attr, type);
226 ~TypeProcessingState() {
229 restoreDeclSpecAttrs();
233 DeclSpec &getMutableDeclSpec() const {
234 return const_cast<DeclSpec&>(declarator.getDeclSpec());
237 void restoreDeclSpecAttrs() {
238 assert(hasSavedAttrs);
240 if (savedAttrs.empty()) {
241 getMutableDeclSpec().getAttributes().set(nullptr);
245 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
246 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
247 savedAttrs[i]->setNext(savedAttrs[i+1]);
248 savedAttrs.back()->setNext(nullptr);
251 } // end anonymous namespace
253 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
258 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
260 head = attr.getNext();
264 AttributeList *cur = head;
266 assert(cur && cur->getNext() && "ran out of attrs?");
267 if (cur->getNext() == &attr) {
268 cur->setNext(attr.getNext());
271 cur = cur->getNext();
275 static void moveAttrFromListToList(AttributeList &attr,
276 AttributeList *&fromList,
277 AttributeList *&toList) {
278 spliceAttrOutOfList(attr, fromList);
279 spliceAttrIntoList(attr, toList);
282 /// The location of a type attribute.
283 enum TypeAttrLocation {
284 /// The attribute is in the decl-specifier-seq.
286 /// The attribute is part of a DeclaratorChunk.
288 /// The attribute is immediately after the declaration's name.
292 static void processTypeAttrs(TypeProcessingState &state,
293 QualType &type, TypeAttrLocation TAL,
294 AttributeList *attrs);
296 static bool handleFunctionTypeAttr(TypeProcessingState &state,
300 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
304 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
305 AttributeList &attr, QualType &type);
307 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
308 AttributeList &attr, QualType &type);
310 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
311 AttributeList &attr, QualType &type) {
312 if (attr.getKind() == AttributeList::AT_ObjCGC)
313 return handleObjCGCTypeAttr(state, attr, type);
314 assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
315 return handleObjCOwnershipTypeAttr(state, attr, type);
318 /// Given the index of a declarator chunk, check whether that chunk
319 /// directly specifies the return type of a function and, if so, find
320 /// an appropriate place for it.
322 /// \param i - a notional index which the search will start
323 /// immediately inside
325 /// \param onlyBlockPointers Whether we should only look into block
326 /// pointer types (vs. all pointer types).
327 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
329 bool onlyBlockPointers) {
330 assert(i <= declarator.getNumTypeObjects());
332 DeclaratorChunk *result = nullptr;
334 // First, look inwards past parens for a function declarator.
335 for (; i != 0; --i) {
336 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
337 switch (fnChunk.Kind) {
338 case DeclaratorChunk::Paren:
341 // If we find anything except a function, bail out.
342 case DeclaratorChunk::Pointer:
343 case DeclaratorChunk::BlockPointer:
344 case DeclaratorChunk::Array:
345 case DeclaratorChunk::Reference:
346 case DeclaratorChunk::MemberPointer:
347 case DeclaratorChunk::Pipe:
350 // If we do find a function declarator, scan inwards from that,
351 // looking for a (block-)pointer declarator.
352 case DeclaratorChunk::Function:
353 for (--i; i != 0; --i) {
354 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
355 switch (ptrChunk.Kind) {
356 case DeclaratorChunk::Paren:
357 case DeclaratorChunk::Array:
358 case DeclaratorChunk::Function:
359 case DeclaratorChunk::Reference:
360 case DeclaratorChunk::Pipe:
363 case DeclaratorChunk::MemberPointer:
364 case DeclaratorChunk::Pointer:
365 if (onlyBlockPointers)
370 case DeclaratorChunk::BlockPointer:
374 llvm_unreachable("bad declarator chunk kind");
377 // If we run out of declarators doing that, we're done.
380 llvm_unreachable("bad declarator chunk kind");
382 // Okay, reconsider from our new point.
386 // Ran out of chunks, bail out.
390 /// Given that an objc_gc attribute was written somewhere on a
391 /// declaration *other* than on the declarator itself (for which, use
392 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
393 /// didn't apply in whatever position it was written in, try to move
394 /// it to a more appropriate position.
395 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
398 Declarator &declarator = state.getDeclarator();
400 // Move it to the outermost normal or block pointer declarator.
401 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
402 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
403 switch (chunk.Kind) {
404 case DeclaratorChunk::Pointer:
405 case DeclaratorChunk::BlockPointer: {
406 // But don't move an ARC ownership attribute to the return type
408 DeclaratorChunk *destChunk = nullptr;
409 if (state.isProcessingDeclSpec() &&
410 attr.getKind() == AttributeList::AT_ObjCOwnership)
411 destChunk = maybeMovePastReturnType(declarator, i - 1,
412 /*onlyBlockPointers=*/true);
413 if (!destChunk) destChunk = &chunk;
415 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
416 destChunk->getAttrListRef());
420 case DeclaratorChunk::Paren:
421 case DeclaratorChunk::Array:
424 // We may be starting at the return type of a block.
425 case DeclaratorChunk::Function:
426 if (state.isProcessingDeclSpec() &&
427 attr.getKind() == AttributeList::AT_ObjCOwnership) {
428 if (DeclaratorChunk *dest = maybeMovePastReturnType(
430 /*onlyBlockPointers=*/true)) {
431 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
432 dest->getAttrListRef());
438 // Don't walk through these.
439 case DeclaratorChunk::Reference:
440 case DeclaratorChunk::MemberPointer:
441 case DeclaratorChunk::Pipe:
447 diagnoseBadTypeAttribute(state.getSema(), attr, type);
450 /// Distribute an objc_gc type attribute that was written on the
453 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
455 QualType &declSpecType) {
456 Declarator &declarator = state.getDeclarator();
458 // objc_gc goes on the innermost pointer to something that's not a
460 unsigned innermost = -1U;
461 bool considerDeclSpec = true;
462 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
463 DeclaratorChunk &chunk = declarator.getTypeObject(i);
464 switch (chunk.Kind) {
465 case DeclaratorChunk::Pointer:
466 case DeclaratorChunk::BlockPointer:
470 case DeclaratorChunk::Reference:
471 case DeclaratorChunk::MemberPointer:
472 case DeclaratorChunk::Paren:
473 case DeclaratorChunk::Array:
474 case DeclaratorChunk::Pipe:
477 case DeclaratorChunk::Function:
478 considerDeclSpec = false;
484 // That might actually be the decl spec if we weren't blocked by
485 // anything in the declarator.
486 if (considerDeclSpec) {
487 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
488 // Splice the attribute into the decl spec. Prevents the
489 // attribute from being applied multiple times and gives
490 // the source-location-filler something to work with.
491 state.saveDeclSpecAttrs();
492 moveAttrFromListToList(attr, declarator.getAttrListRef(),
493 declarator.getMutableDeclSpec().getAttributes().getListRef());
498 // Otherwise, if we found an appropriate chunk, splice the attribute
500 if (innermost != -1U) {
501 moveAttrFromListToList(attr, declarator.getAttrListRef(),
502 declarator.getTypeObject(innermost).getAttrListRef());
506 // Otherwise, diagnose when we're done building the type.
507 spliceAttrOutOfList(attr, declarator.getAttrListRef());
508 state.addIgnoredTypeAttr(attr);
511 /// A function type attribute was written somewhere in a declaration
512 /// *other* than on the declarator itself or in the decl spec. Given
513 /// that it didn't apply in whatever position it was written in, try
514 /// to move it to a more appropriate position.
515 static void distributeFunctionTypeAttr(TypeProcessingState &state,
518 Declarator &declarator = state.getDeclarator();
520 // Try to push the attribute from the return type of a function to
521 // the function itself.
522 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
523 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
524 switch (chunk.Kind) {
525 case DeclaratorChunk::Function:
526 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
527 chunk.getAttrListRef());
530 case DeclaratorChunk::Paren:
531 case DeclaratorChunk::Pointer:
532 case DeclaratorChunk::BlockPointer:
533 case DeclaratorChunk::Array:
534 case DeclaratorChunk::Reference:
535 case DeclaratorChunk::MemberPointer:
536 case DeclaratorChunk::Pipe:
541 diagnoseBadTypeAttribute(state.getSema(), attr, type);
544 /// Try to distribute a function type attribute to the innermost
545 /// function chunk or type. Returns true if the attribute was
546 /// distributed, false if no location was found.
548 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
550 AttributeList *&attrList,
551 QualType &declSpecType) {
552 Declarator &declarator = state.getDeclarator();
554 // Put it on the innermost function chunk, if there is one.
555 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
556 DeclaratorChunk &chunk = declarator.getTypeObject(i);
557 if (chunk.Kind != DeclaratorChunk::Function) continue;
559 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
563 return handleFunctionTypeAttr(state, attr, declSpecType);
566 /// A function type attribute was written in the decl spec. Try to
567 /// apply it somewhere.
569 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
571 QualType &declSpecType) {
572 state.saveDeclSpecAttrs();
574 // C++11 attributes before the decl specifiers actually appertain to
575 // the declarators. Move them straight there. We don't support the
576 // 'put them wherever you like' semantics we allow for GNU attributes.
577 if (attr.isCXX11Attribute()) {
578 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
579 state.getDeclarator().getAttrListRef());
583 // Try to distribute to the innermost.
584 if (distributeFunctionTypeAttrToInnermost(state, attr,
585 state.getCurrentAttrListRef(),
589 // If that failed, diagnose the bad attribute when the declarator is
591 state.addIgnoredTypeAttr(attr);
594 /// A function type attribute was written on the declarator. Try to
595 /// apply it somewhere.
597 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
599 QualType &declSpecType) {
600 Declarator &declarator = state.getDeclarator();
602 // Try to distribute to the innermost.
603 if (distributeFunctionTypeAttrToInnermost(state, attr,
604 declarator.getAttrListRef(),
608 // If that failed, diagnose the bad attribute when the declarator is
610 spliceAttrOutOfList(attr, declarator.getAttrListRef());
611 state.addIgnoredTypeAttr(attr);
614 /// \brief Given that there are attributes written on the declarator
615 /// itself, try to distribute any type attributes to the appropriate
616 /// declarator chunk.
618 /// These are attributes like the following:
621 /// but not necessarily this:
623 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
624 QualType &declSpecType) {
625 // Collect all the type attributes from the declarator itself.
626 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
627 AttributeList *attr = state.getDeclarator().getAttributes();
630 next = attr->getNext();
632 // Do not distribute C++11 attributes. They have strict rules for what
633 // they appertain to.
634 if (attr->isCXX11Attribute())
637 switch (attr->getKind()) {
638 OBJC_POINTER_TYPE_ATTRS_CASELIST:
639 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
642 case AttributeList::AT_NSReturnsRetained:
643 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
647 FUNCTION_TYPE_ATTRS_CASELIST:
648 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
651 MS_TYPE_ATTRS_CASELIST:
652 // Microsoft type attributes cannot go after the declarator-id.
655 NULLABILITY_TYPE_ATTRS_CASELIST:
656 // Nullability specifiers cannot go after the declarator-id.
658 // Objective-C __kindof does not get distributed.
659 case AttributeList::AT_ObjCKindOf:
665 } while ((attr = next));
668 /// Add a synthetic '()' to a block-literal declarator if it is
669 /// required, given the return type.
670 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
671 QualType declSpecType) {
672 Declarator &declarator = state.getDeclarator();
674 // First, check whether the declarator would produce a function,
675 // i.e. whether the innermost semantic chunk is a function.
676 if (declarator.isFunctionDeclarator()) {
677 // If so, make that declarator a prototyped declarator.
678 declarator.getFunctionTypeInfo().hasPrototype = true;
682 // If there are any type objects, the type as written won't name a
683 // function, regardless of the decl spec type. This is because a
684 // block signature declarator is always an abstract-declarator, and
685 // abstract-declarators can't just be parentheses chunks. Therefore
686 // we need to build a function chunk unless there are no type
687 // objects and the decl spec type is a function.
688 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
691 // Note that there *are* cases with invalid declarators where
692 // declarators consist solely of parentheses. In general, these
693 // occur only in failed efforts to make function declarators, so
694 // faking up the function chunk is still the right thing to do.
696 // Otherwise, we need to fake up a function declarator.
697 SourceLocation loc = declarator.getLocStart();
699 // ...and *prepend* it to the declarator.
700 SourceLocation NoLoc;
701 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
703 /*IsAmbiguous=*/false,
707 /*EllipsisLoc=*/NoLoc,
710 /*RefQualifierIsLvalueRef=*/true,
711 /*RefQualifierLoc=*/NoLoc,
712 /*ConstQualifierLoc=*/NoLoc,
713 /*VolatileQualifierLoc=*/NoLoc,
714 /*RestrictQualifierLoc=*/NoLoc,
715 /*MutableLoc=*/NoLoc, EST_None,
716 /*ESpecRange=*/SourceRange(),
717 /*Exceptions=*/nullptr,
718 /*ExceptionRanges=*/nullptr,
720 /*NoexceptExpr=*/nullptr,
721 /*ExceptionSpecTokens=*/nullptr,
722 /*DeclsInPrototype=*/None,
723 loc, loc, declarator));
725 // For consistency, make sure the state still has us as processing
727 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
728 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
731 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
736 // If this occurs outside a template instantiation, warn the user about
737 // it; they probably didn't mean to specify a redundant qualifier.
738 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
739 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
740 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
741 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
742 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
743 if (!(RemoveTQs & Qual.first))
746 if (!S.inTemplateInstantiation()) {
747 if (TypeQuals & Qual.first)
748 S.Diag(Qual.second, DiagID)
749 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
750 << FixItHint::CreateRemoval(Qual.second);
753 TypeQuals &= ~Qual.first;
757 /// Return true if this is omitted block return type. Also check type
758 /// attributes and type qualifiers when returning true.
759 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
761 if (!isOmittedBlockReturnType(declarator))
764 // Warn if we see type attributes for omitted return type on a block literal.
765 AttributeList *&attrs =
766 declarator.getMutableDeclSpec().getAttributes().getListRef();
767 AttributeList *prev = nullptr;
768 for (AttributeList *cur = attrs; cur; cur = cur->getNext()) {
769 AttributeList &attr = *cur;
770 // Skip attributes that were marked to be invalid or non-type
772 if (attr.isInvalid() || !attr.isTypeAttr()) {
776 S.Diag(attr.getLoc(),
777 diag::warn_block_literal_attributes_on_omitted_return_type)
779 // Remove cur from the list.
781 prev->setNext(cur->getNext());
784 attrs = cur->getNext();
788 // Warn if we see type qualifiers for omitted return type on a block literal.
789 const DeclSpec &DS = declarator.getDeclSpec();
790 unsigned TypeQuals = DS.getTypeQualifiers();
791 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
792 diag::warn_block_literal_qualifiers_on_omitted_return_type);
793 declarator.getMutableDeclSpec().ClearTypeQualifiers();
798 /// Apply Objective-C type arguments to the given type.
799 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
800 ArrayRef<TypeSourceInfo *> typeArgs,
801 SourceRange typeArgsRange,
802 bool failOnError = false) {
803 // We can only apply type arguments to an Objective-C class type.
804 const auto *objcObjectType = type->getAs<ObjCObjectType>();
805 if (!objcObjectType || !objcObjectType->getInterface()) {
806 S.Diag(loc, diag::err_objc_type_args_non_class)
815 // The class type must be parameterized.
816 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
817 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
819 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
820 << objcClass->getDeclName()
821 << FixItHint::CreateRemoval(typeArgsRange);
829 // The type must not already be specialized.
830 if (objcObjectType->isSpecialized()) {
831 S.Diag(loc, diag::err_objc_type_args_specialized_class)
833 << FixItHint::CreateRemoval(typeArgsRange);
841 // Check the type arguments.
842 SmallVector<QualType, 4> finalTypeArgs;
843 unsigned numTypeParams = typeParams->size();
844 bool anyPackExpansions = false;
845 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
846 TypeSourceInfo *typeArgInfo = typeArgs[i];
847 QualType typeArg = typeArgInfo->getType();
849 // Type arguments cannot have explicit qualifiers or nullability.
850 // We ignore indirect sources of these, e.g. behind typedefs or
851 // template arguments.
852 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
853 bool diagnosed = false;
854 SourceRange rangeToRemove;
855 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
856 rangeToRemove = attr.getLocalSourceRange();
857 if (attr.getTypePtr()->getImmediateNullability()) {
858 typeArg = attr.getTypePtr()->getModifiedType();
859 S.Diag(attr.getLocStart(),
860 diag::err_objc_type_arg_explicit_nullability)
861 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
867 S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified)
868 << typeArg << typeArg.getQualifiers().getAsString()
869 << FixItHint::CreateRemoval(rangeToRemove);
873 // Remove qualifiers even if they're non-local.
874 typeArg = typeArg.getUnqualifiedType();
876 finalTypeArgs.push_back(typeArg);
878 if (typeArg->getAs<PackExpansionType>())
879 anyPackExpansions = true;
881 // Find the corresponding type parameter, if there is one.
882 ObjCTypeParamDecl *typeParam = nullptr;
883 if (!anyPackExpansions) {
884 if (i < numTypeParams) {
885 typeParam = typeParams->begin()[i];
887 // Too many arguments.
888 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
890 << objcClass->getDeclName()
891 << (unsigned)typeArgs.size()
893 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
903 // Objective-C object pointer types must be substitutable for the bounds.
904 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
905 // If we don't have a type parameter to match against, assume
906 // everything is fine. There was a prior pack expansion that
907 // means we won't be able to match anything.
909 assert(anyPackExpansions && "Too many arguments?");
913 // Retrieve the bound.
914 QualType bound = typeParam->getUnderlyingType();
915 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
917 // Determine whether the type argument is substitutable for the bound.
918 if (typeArgObjC->isObjCIdType()) {
919 // When the type argument is 'id', the only acceptable type
920 // parameter bound is 'id'.
921 if (boundObjC->isObjCIdType())
923 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
924 // Otherwise, we follow the assignability rules.
928 // Diagnose the mismatch.
929 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
930 diag::err_objc_type_arg_does_not_match_bound)
931 << typeArg << bound << typeParam->getDeclName();
932 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
933 << typeParam->getDeclName();
941 // Block pointer types are permitted for unqualified 'id' bounds.
942 if (typeArg->isBlockPointerType()) {
943 // If we don't have a type parameter to match against, assume
944 // everything is fine. There was a prior pack expansion that
945 // means we won't be able to match anything.
947 assert(anyPackExpansions && "Too many arguments?");
951 // Retrieve the bound.
952 QualType bound = typeParam->getUnderlyingType();
953 if (bound->isBlockCompatibleObjCPointerType(S.Context))
956 // Diagnose the mismatch.
957 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
958 diag::err_objc_type_arg_does_not_match_bound)
959 << typeArg << bound << typeParam->getDeclName();
960 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
961 << typeParam->getDeclName();
969 // Dependent types will be checked at instantiation time.
970 if (typeArg->isDependentType()) {
974 // Diagnose non-id-compatible type arguments.
975 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
976 diag::err_objc_type_arg_not_id_compatible)
978 << typeArgInfo->getTypeLoc().getSourceRange();
986 // Make sure we didn't have the wrong number of arguments.
987 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
988 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
989 << (typeArgs.size() < typeParams->size())
990 << objcClass->getDeclName()
991 << (unsigned)finalTypeArgs.size()
992 << (unsigned)numTypeParams;
993 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1002 // Success. Form the specialized type.
1003 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1006 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1007 SourceLocation ProtocolLAngleLoc,
1008 ArrayRef<ObjCProtocolDecl *> Protocols,
1009 ArrayRef<SourceLocation> ProtocolLocs,
1010 SourceLocation ProtocolRAngleLoc,
1012 QualType Result = QualType(Decl->getTypeForDecl(), 0);
1013 if (!Protocols.empty()) {
1015 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1018 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1019 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1020 if (FailOnError) Result = QualType();
1022 if (FailOnError && Result.isNull())
1029 QualType Sema::BuildObjCObjectType(QualType BaseType,
1031 SourceLocation TypeArgsLAngleLoc,
1032 ArrayRef<TypeSourceInfo *> TypeArgs,
1033 SourceLocation TypeArgsRAngleLoc,
1034 SourceLocation ProtocolLAngleLoc,
1035 ArrayRef<ObjCProtocolDecl *> Protocols,
1036 ArrayRef<SourceLocation> ProtocolLocs,
1037 SourceLocation ProtocolRAngleLoc,
1039 QualType Result = BaseType;
1040 if (!TypeArgs.empty()) {
1041 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1042 SourceRange(TypeArgsLAngleLoc,
1045 if (FailOnError && Result.isNull())
1049 if (!Protocols.empty()) {
1051 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1054 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1055 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1056 if (FailOnError) Result = QualType();
1058 if (FailOnError && Result.isNull())
1065 TypeResult Sema::actOnObjCProtocolQualifierType(
1066 SourceLocation lAngleLoc,
1067 ArrayRef<Decl *> protocols,
1068 ArrayRef<SourceLocation> protocolLocs,
1069 SourceLocation rAngleLoc) {
1070 // Form id<protocol-list>.
1071 QualType Result = Context.getObjCObjectType(
1072 Context.ObjCBuiltinIdTy, { },
1074 (ObjCProtocolDecl * const *)protocols.data(),
1077 Result = Context.getObjCObjectPointerType(Result);
1079 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1080 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1082 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1083 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1085 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1086 .castAs<ObjCObjectTypeLoc>();
1087 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1088 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1090 // No type arguments.
1091 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1092 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1094 // Fill in protocol qualifiers.
1095 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1096 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1097 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1098 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1100 // We're done. Return the completed type to the parser.
1101 return CreateParsedType(Result, ResultTInfo);
1104 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1107 ParsedType BaseType,
1108 SourceLocation TypeArgsLAngleLoc,
1109 ArrayRef<ParsedType> TypeArgs,
1110 SourceLocation TypeArgsRAngleLoc,
1111 SourceLocation ProtocolLAngleLoc,
1112 ArrayRef<Decl *> Protocols,
1113 ArrayRef<SourceLocation> ProtocolLocs,
1114 SourceLocation ProtocolRAngleLoc) {
1115 TypeSourceInfo *BaseTypeInfo = nullptr;
1116 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1120 // Handle missing type-source info.
1122 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1124 // Extract type arguments.
1125 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1126 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1127 TypeSourceInfo *TypeArgInfo = nullptr;
1128 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1129 if (TypeArg.isNull()) {
1130 ActualTypeArgInfos.clear();
1134 assert(TypeArgInfo && "No type source info?");
1135 ActualTypeArgInfos.push_back(TypeArgInfo);
1138 // Build the object type.
1139 QualType Result = BuildObjCObjectType(
1140 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1141 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1143 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1145 ProtocolLocs, ProtocolRAngleLoc,
1146 /*FailOnError=*/false);
1151 // Create source information for this type.
1152 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1153 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1155 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1156 // object pointer type. Fill in source information for it.
1157 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1158 // The '*' is implicit.
1159 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1160 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1163 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1164 // Protocol qualifier information.
1165 if (OTPTL.getNumProtocols() > 0) {
1166 assert(OTPTL.getNumProtocols() == Protocols.size());
1167 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1168 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1169 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1170 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1173 // We're done. Return the completed type to the parser.
1174 return CreateParsedType(Result, ResultTInfo);
1177 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1179 // Type argument information.
1180 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1181 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1182 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1183 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1184 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1185 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1187 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1188 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1191 // Protocol qualifier information.
1192 if (ObjCObjectTL.getNumProtocols() > 0) {
1193 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1194 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1195 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1196 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1197 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1199 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1200 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1204 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1205 if (ObjCObjectTL.getType() == T)
1206 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1208 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1210 // We're done. Return the completed type to the parser.
1211 return CreateParsedType(Result, ResultTInfo);
1214 static OpenCLAccessAttr::Spelling getImageAccess(const AttributeList *Attrs) {
1216 const AttributeList *Next = Attrs;
1218 const AttributeList &Attr = *Next;
1219 Next = Attr.getNext();
1220 if (Attr.getKind() == AttributeList::AT_OpenCLAccess) {
1221 return static_cast<OpenCLAccessAttr::Spelling>(
1222 Attr.getSemanticSpelling());
1226 return OpenCLAccessAttr::Keyword_read_only;
1229 /// \brief Convert the specified declspec to the appropriate type
1231 /// \param state Specifies the declarator containing the declaration specifier
1232 /// to be converted, along with other associated processing state.
1233 /// \returns The type described by the declaration specifiers. This function
1234 /// never returns null.
1235 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1236 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1239 Sema &S = state.getSema();
1240 Declarator &declarator = state.getDeclarator();
1241 const DeclSpec &DS = declarator.getDeclSpec();
1242 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1243 if (DeclLoc.isInvalid())
1244 DeclLoc = DS.getLocStart();
1246 ASTContext &Context = S.Context;
1249 switch (DS.getTypeSpecType()) {
1250 case DeclSpec::TST_void:
1251 Result = Context.VoidTy;
1253 case DeclSpec::TST_char:
1254 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1255 Result = Context.CharTy;
1256 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1257 Result = Context.SignedCharTy;
1259 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1260 "Unknown TSS value");
1261 Result = Context.UnsignedCharTy;
1264 case DeclSpec::TST_wchar:
1265 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1266 Result = Context.WCharTy;
1267 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1268 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1269 << DS.getSpecifierName(DS.getTypeSpecType(),
1270 Context.getPrintingPolicy());
1271 Result = Context.getSignedWCharType();
1273 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1274 "Unknown TSS value");
1275 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1276 << DS.getSpecifierName(DS.getTypeSpecType(),
1277 Context.getPrintingPolicy());
1278 Result = Context.getUnsignedWCharType();
1281 case DeclSpec::TST_char16:
1282 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1283 "Unknown TSS value");
1284 Result = Context.Char16Ty;
1286 case DeclSpec::TST_char32:
1287 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1288 "Unknown TSS value");
1289 Result = Context.Char32Ty;
1291 case DeclSpec::TST_unspecified:
1292 // If this is a missing declspec in a block literal return context, then it
1293 // is inferred from the return statements inside the block.
1294 // The declspec is always missing in a lambda expr context; it is either
1295 // specified with a trailing return type or inferred.
1296 if (S.getLangOpts().CPlusPlus14 &&
1297 declarator.getContext() == Declarator::LambdaExprContext) {
1298 // In C++1y, a lambda's implicit return type is 'auto'.
1299 Result = Context.getAutoDeductType();
1301 } else if (declarator.getContext() == Declarator::LambdaExprContext ||
1302 checkOmittedBlockReturnType(S, declarator,
1303 Context.DependentTy)) {
1304 Result = Context.DependentTy;
1308 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1309 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1310 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1311 // Note that the one exception to this is function definitions, which are
1312 // allowed to be completely missing a declspec. This is handled in the
1313 // parser already though by it pretending to have seen an 'int' in this
1315 if (S.getLangOpts().ImplicitInt) {
1316 // In C89 mode, we only warn if there is a completely missing declspec
1317 // when one is not allowed.
1319 S.Diag(DeclLoc, diag::ext_missing_declspec)
1320 << DS.getSourceRange()
1321 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
1323 } else if (!DS.hasTypeSpecifier()) {
1324 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1325 // "At least one type specifier shall be given in the declaration
1326 // specifiers in each declaration, and in the specifier-qualifier list in
1327 // each struct declaration and type name."
1328 if (S.getLangOpts().CPlusPlus) {
1329 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1330 << DS.getSourceRange();
1332 // When this occurs in C++ code, often something is very broken with the
1333 // value being declared, poison it as invalid so we don't get chains of
1335 declarator.setInvalidType(true);
1336 } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1337 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1338 << DS.getSourceRange();
1339 declarator.setInvalidType(true);
1341 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1342 << DS.getSourceRange();
1347 case DeclSpec::TST_int: {
1348 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
1349 switch (DS.getTypeSpecWidth()) {
1350 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1351 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
1352 case DeclSpec::TSW_long: Result = Context.LongTy; break;
1353 case DeclSpec::TSW_longlong:
1354 Result = Context.LongLongTy;
1356 // 'long long' is a C99 or C++11 feature.
1357 if (!S.getLangOpts().C99) {
1358 if (S.getLangOpts().CPlusPlus)
1359 S.Diag(DS.getTypeSpecWidthLoc(),
1360 S.getLangOpts().CPlusPlus11 ?
1361 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1363 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1368 switch (DS.getTypeSpecWidth()) {
1369 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1370 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
1371 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
1372 case DeclSpec::TSW_longlong:
1373 Result = Context.UnsignedLongLongTy;
1375 // 'long long' is a C99 or C++11 feature.
1376 if (!S.getLangOpts().C99) {
1377 if (S.getLangOpts().CPlusPlus)
1378 S.Diag(DS.getTypeSpecWidthLoc(),
1379 S.getLangOpts().CPlusPlus11 ?
1380 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1382 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1389 case DeclSpec::TST_int128:
1390 if (!S.Context.getTargetInfo().hasInt128Type())
1391 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1393 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1394 Result = Context.UnsignedInt128Ty;
1396 Result = Context.Int128Ty;
1398 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1399 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1400 case DeclSpec::TST_double:
1401 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1402 Result = Context.LongDoubleTy;
1404 Result = Context.DoubleTy;
1406 case DeclSpec::TST_float128:
1407 if (!S.Context.getTargetInfo().hasFloat128Type())
1408 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1410 Result = Context.Float128Ty;
1412 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1414 case DeclSpec::TST_decimal32: // _Decimal32
1415 case DeclSpec::TST_decimal64: // _Decimal64
1416 case DeclSpec::TST_decimal128: // _Decimal128
1417 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1418 Result = Context.IntTy;
1419 declarator.setInvalidType(true);
1421 case DeclSpec::TST_class:
1422 case DeclSpec::TST_enum:
1423 case DeclSpec::TST_union:
1424 case DeclSpec::TST_struct:
1425 case DeclSpec::TST_interface: {
1426 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
1428 // This can happen in C++ with ambiguous lookups.
1429 Result = Context.IntTy;
1430 declarator.setInvalidType(true);
1434 // If the type is deprecated or unavailable, diagnose it.
1435 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1437 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1438 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1440 // TypeQuals handled by caller.
1441 Result = Context.getTypeDeclType(D);
1443 // In both C and C++, make an ElaboratedType.
1444 ElaboratedTypeKeyword Keyword
1445 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1446 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
1449 case DeclSpec::TST_typename: {
1450 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1451 DS.getTypeSpecSign() == 0 &&
1452 "Can't handle qualifiers on typedef names yet!");
1453 Result = S.GetTypeFromParser(DS.getRepAsType());
1454 if (Result.isNull()) {
1455 declarator.setInvalidType(true);
1458 // TypeQuals handled by caller.
1461 case DeclSpec::TST_typeofType:
1462 // FIXME: Preserve type source info.
1463 Result = S.GetTypeFromParser(DS.getRepAsType());
1464 assert(!Result.isNull() && "Didn't get a type for typeof?");
1465 if (!Result->isDependentType())
1466 if (const TagType *TT = Result->getAs<TagType>())
1467 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1468 // TypeQuals handled by caller.
1469 Result = Context.getTypeOfType(Result);
1471 case DeclSpec::TST_typeofExpr: {
1472 Expr *E = DS.getRepAsExpr();
1473 assert(E && "Didn't get an expression for typeof?");
1474 // TypeQuals handled by caller.
1475 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1476 if (Result.isNull()) {
1477 Result = Context.IntTy;
1478 declarator.setInvalidType(true);
1482 case DeclSpec::TST_decltype: {
1483 Expr *E = DS.getRepAsExpr();
1484 assert(E && "Didn't get an expression for decltype?");
1485 // TypeQuals handled by caller.
1486 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1487 if (Result.isNull()) {
1488 Result = Context.IntTy;
1489 declarator.setInvalidType(true);
1493 case DeclSpec::TST_underlyingType:
1494 Result = S.GetTypeFromParser(DS.getRepAsType());
1495 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1496 Result = S.BuildUnaryTransformType(Result,
1497 UnaryTransformType::EnumUnderlyingType,
1498 DS.getTypeSpecTypeLoc());
1499 if (Result.isNull()) {
1500 Result = Context.IntTy;
1501 declarator.setInvalidType(true);
1505 case DeclSpec::TST_auto:
1506 Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1509 case DeclSpec::TST_auto_type:
1510 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1513 case DeclSpec::TST_decltype_auto:
1514 Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1515 /*IsDependent*/ false);
1518 case DeclSpec::TST_unknown_anytype:
1519 Result = Context.UnknownAnyTy;
1522 case DeclSpec::TST_atomic:
1523 Result = S.GetTypeFromParser(DS.getRepAsType());
1524 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1525 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1526 if (Result.isNull()) {
1527 Result = Context.IntTy;
1528 declarator.setInvalidType(true);
1532 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1533 case DeclSpec::TST_##ImgType##_t: \
1534 switch (getImageAccess(DS.getAttributes().getList())) { \
1535 case OpenCLAccessAttr::Keyword_write_only: \
1536 Result = Context.Id##WOTy; break; \
1537 case OpenCLAccessAttr::Keyword_read_write: \
1538 Result = Context.Id##RWTy; break; \
1539 case OpenCLAccessAttr::Keyword_read_only: \
1540 Result = Context.Id##ROTy; break; \
1543 #include "clang/Basic/OpenCLImageTypes.def"
1545 case DeclSpec::TST_error:
1546 Result = Context.IntTy;
1547 declarator.setInvalidType(true);
1551 if (S.getLangOpts().OpenCL &&
1552 S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
1553 declarator.setInvalidType(true);
1555 // Handle complex types.
1556 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1557 if (S.getLangOpts().Freestanding)
1558 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1559 Result = Context.getComplexType(Result);
1560 } else if (DS.isTypeAltiVecVector()) {
1561 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1562 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1563 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1564 if (DS.isTypeAltiVecPixel())
1565 VecKind = VectorType::AltiVecPixel;
1566 else if (DS.isTypeAltiVecBool())
1567 VecKind = VectorType::AltiVecBool;
1568 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1571 // FIXME: Imaginary.
1572 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1573 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1575 // Before we process any type attributes, synthesize a block literal
1576 // function declarator if necessary.
1577 if (declarator.getContext() == Declarator::BlockLiteralContext)
1578 maybeSynthesizeBlockSignature(state, Result);
1580 // Apply any type attributes from the decl spec. This may cause the
1581 // list of type attributes to be temporarily saved while the type
1582 // attributes are pushed around.
1583 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1584 if (!DS.isTypeSpecPipe())
1585 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList());
1587 // Apply const/volatile/restrict qualifiers to T.
1588 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1589 // Warn about CV qualifiers on function types.
1591 // If the specification of a function type includes any type qualifiers,
1592 // the behavior is undefined.
1593 // C++11 [dcl.fct]p7:
1594 // The effect of a cv-qualifier-seq in a function declarator is not the
1595 // same as adding cv-qualification on top of the function type. In the
1596 // latter case, the cv-qualifiers are ignored.
1597 if (TypeQuals && Result->isFunctionType()) {
1598 diagnoseAndRemoveTypeQualifiers(
1599 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1600 S.getLangOpts().CPlusPlus
1601 ? diag::warn_typecheck_function_qualifiers_ignored
1602 : diag::warn_typecheck_function_qualifiers_unspecified);
1603 // No diagnostic for 'restrict' or '_Atomic' applied to a
1604 // function type; we'll diagnose those later, in BuildQualifiedType.
1607 // C++11 [dcl.ref]p1:
1608 // Cv-qualified references are ill-formed except when the
1609 // cv-qualifiers are introduced through the use of a typedef-name
1610 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1612 // There don't appear to be any other contexts in which a cv-qualified
1613 // reference type could be formed, so the 'ill-formed' clause here appears
1615 if (TypeQuals && Result->isReferenceType()) {
1616 diagnoseAndRemoveTypeQualifiers(
1617 S, DS, TypeQuals, Result,
1618 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1619 diag::warn_typecheck_reference_qualifiers);
1622 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1623 // than once in the same specifier-list or qualifier-list, either directly
1624 // or via one or more typedefs."
1625 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1626 && TypeQuals & Result.getCVRQualifiers()) {
1627 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1628 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1632 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1633 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1637 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1638 // produce a warning in this case.
1641 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1643 // If adding qualifiers fails, just use the unqualified type.
1644 if (Qualified.isNull())
1645 declarator.setInvalidType(true);
1650 assert(!Result.isNull() && "This function should not return a null type");
1654 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1656 return Entity.getAsString();
1661 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1662 Qualifiers Qs, const DeclSpec *DS) {
1666 // Ignore any attempt to form a cv-qualified reference.
1667 if (T->isReferenceType()) {
1669 Qs.removeVolatile();
1672 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1673 // object or incomplete types shall not be restrict-qualified."
1674 if (Qs.hasRestrict()) {
1675 unsigned DiagID = 0;
1678 if (T->isAnyPointerType() || T->isReferenceType() ||
1679 T->isMemberPointerType()) {
1681 if (T->isObjCObjectPointerType())
1683 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1684 EltTy = PTy->getPointeeType();
1686 EltTy = T->getPointeeType();
1688 // If we have a pointer or reference, the pointee must have an object
1690 if (!EltTy->isIncompleteOrObjectType()) {
1691 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1694 } else if (!T->isDependentType()) {
1695 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1700 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1701 Qs.removeRestrict();
1705 return Context.getQualifiedType(T, Qs);
1708 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1709 unsigned CVRAU, const DeclSpec *DS) {
1713 // Ignore any attempt to form a cv-qualified reference.
1714 if (T->isReferenceType())
1716 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1718 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1720 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1723 // If the same qualifier appears more than once in the same
1724 // specifier-qualifier-list, either directly or via one or more typedefs,
1725 // the behavior is the same as if it appeared only once.
1727 // It's not specified what happens when the _Atomic qualifier is applied to
1728 // a type specified with the _Atomic specifier, but we assume that this
1729 // should be treated as if the _Atomic qualifier appeared multiple times.
1730 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1732 // If other qualifiers appear along with the _Atomic qualifier in a
1733 // specifier-qualifier-list, the resulting type is the so-qualified
1736 // Don't need to worry about array types here, since _Atomic can't be
1737 // applied to such types.
1738 SplitQualType Split = T.getSplitUnqualifiedType();
1739 T = BuildAtomicType(QualType(Split.Ty, 0),
1740 DS ? DS->getAtomicSpecLoc() : Loc);
1743 Split.Quals.addCVRQualifiers(CVR);
1744 return BuildQualifiedType(T, Loc, Split.Quals);
1747 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1748 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1749 return BuildQualifiedType(T, Loc, Q, DS);
1752 /// \brief Build a paren type including \p T.
1753 QualType Sema::BuildParenType(QualType T) {
1754 return Context.getParenType(T);
1757 /// Given that we're building a pointer or reference to the given
1758 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1761 // Bail out if retention is unrequired or already specified.
1762 if (!type->isObjCLifetimeType() ||
1763 type.getObjCLifetime() != Qualifiers::OCL_None)
1766 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1768 // If the object type is const-qualified, we can safely use
1769 // __unsafe_unretained. This is safe (because there are no read
1770 // barriers), and it'll be safe to coerce anything but __weak* to
1771 // the resulting type.
1772 if (type.isConstQualified()) {
1773 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1775 // Otherwise, check whether the static type does not require
1776 // retaining. This currently only triggers for Class (possibly
1777 // protocol-qualifed, and arrays thereof).
1778 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1779 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1781 // If we are in an unevaluated context, like sizeof, skip adding a
1783 } else if (S.isUnevaluatedContext()) {
1786 // If that failed, give an error and recover using __strong. __strong
1787 // is the option most likely to prevent spurious second-order diagnostics,
1788 // like when binding a reference to a field.
1790 // These types can show up in private ivars in system headers, so
1791 // we need this to not be an error in those cases. Instead we
1793 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1794 S.DelayedDiagnostics.add(
1795 sema::DelayedDiagnostic::makeForbiddenType(loc,
1796 diag::err_arc_indirect_no_ownership, type, isReference));
1798 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1800 implicitLifetime = Qualifiers::OCL_Strong;
1802 assert(implicitLifetime && "didn't infer any lifetime!");
1805 qs.addObjCLifetime(implicitLifetime);
1806 return S.Context.getQualifiedType(type, qs);
1809 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1811 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1813 switch (FnTy->getRefQualifier()) {
1834 /// Kinds of declarator that cannot contain a qualified function type.
1836 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1837 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1838 /// at the topmost level of a type.
1840 /// Parens and member pointers are permitted. We don't diagnose array and
1841 /// function declarators, because they don't allow function types at all.
1843 /// The values of this enum are used in diagnostics.
1844 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1845 } // end anonymous namespace
1847 /// Check whether the type T is a qualified function type, and if it is,
1848 /// diagnose that it cannot be contained within the given kind of declarator.
1849 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1850 QualifiedFunctionKind QFK) {
1851 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1852 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1853 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1856 S.Diag(Loc, diag::err_compound_qualified_function_type)
1857 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1858 << getFunctionQualifiersAsString(FPT);
1862 /// \brief Build a pointer type.
1864 /// \param T The type to which we'll be building a pointer.
1866 /// \param Loc The location of the entity whose type involves this
1867 /// pointer type or, if there is no such entity, the location of the
1868 /// type that will have pointer type.
1870 /// \param Entity The name of the entity that involves the pointer
1873 /// \returns A suitable pointer type, if there are no
1874 /// errors. Otherwise, returns a NULL type.
1875 QualType Sema::BuildPointerType(QualType T,
1876 SourceLocation Loc, DeclarationName Entity) {
1877 if (T->isReferenceType()) {
1878 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1879 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1880 << getPrintableNameForEntity(Entity) << T;
1884 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1887 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1889 // In ARC, it is forbidden to build pointers to unqualified pointers.
1890 if (getLangOpts().ObjCAutoRefCount)
1891 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1893 // Build the pointer type.
1894 return Context.getPointerType(T);
1897 /// \brief Build a reference type.
1899 /// \param T The type to which we'll be building a reference.
1901 /// \param Loc The location of the entity whose type involves this
1902 /// reference type or, if there is no such entity, the location of the
1903 /// type that will have reference type.
1905 /// \param Entity The name of the entity that involves the reference
1908 /// \returns A suitable reference type, if there are no
1909 /// errors. Otherwise, returns a NULL type.
1910 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1912 DeclarationName Entity) {
1913 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1914 "Unresolved overloaded function type");
1916 // C++0x [dcl.ref]p6:
1917 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1918 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1919 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1920 // the type "lvalue reference to T", while an attempt to create the type
1921 // "rvalue reference to cv TR" creates the type TR.
1922 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1924 // C++ [dcl.ref]p4: There shall be no references to references.
1926 // According to C++ DR 106, references to references are only
1927 // diagnosed when they are written directly (e.g., "int & &"),
1928 // but not when they happen via a typedef:
1930 // typedef int& intref;
1931 // typedef intref& intref2;
1933 // Parser::ParseDeclaratorInternal diagnoses the case where
1934 // references are written directly; here, we handle the
1935 // collapsing of references-to-references as described in C++0x.
1936 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1939 // A declarator that specifies the type "reference to cv void"
1941 if (T->isVoidType()) {
1942 Diag(Loc, diag::err_reference_to_void);
1946 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1949 // In ARC, it is forbidden to build references to unqualified pointers.
1950 if (getLangOpts().ObjCAutoRefCount)
1951 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1953 // Handle restrict on references.
1955 return Context.getLValueReferenceType(T, SpelledAsLValue);
1956 return Context.getRValueReferenceType(T);
1959 /// \brief Build a Read-only Pipe type.
1961 /// \param T The type to which we'll be building a Pipe.
1963 /// \param Loc We do not use it for now.
1965 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1967 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
1968 return Context.getReadPipeType(T);
1971 /// \brief Build a Write-only Pipe type.
1973 /// \param T The type to which we'll be building a Pipe.
1975 /// \param Loc We do not use it for now.
1977 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1979 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
1980 return Context.getWritePipeType(T);
1983 /// Check whether the specified array size makes the array type a VLA. If so,
1984 /// return true, if not, return the size of the array in SizeVal.
1985 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1986 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1987 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1988 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1990 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1992 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1995 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
1996 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2000 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2001 S.LangOpts.GNUMode ||
2002 S.LangOpts.OpenCL).isInvalid();
2005 /// \brief Build an array type.
2007 /// \param T The type of each element in the array.
2009 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2011 /// \param ArraySize Expression describing the size of the array.
2013 /// \param Brackets The range from the opening '[' to the closing ']'.
2015 /// \param Entity The name of the entity that involves the array
2018 /// \returns A suitable array type, if there are no errors. Otherwise,
2019 /// returns a NULL type.
2020 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2021 Expr *ArraySize, unsigned Quals,
2022 SourceRange Brackets, DeclarationName Entity) {
2024 SourceLocation Loc = Brackets.getBegin();
2025 if (getLangOpts().CPlusPlus) {
2026 // C++ [dcl.array]p1:
2027 // T is called the array element type; this type shall not be a reference
2028 // type, the (possibly cv-qualified) type void, a function type or an
2029 // abstract class type.
2031 // C++ [dcl.array]p3:
2032 // When several "array of" specifications are adjacent, [...] only the
2033 // first of the constant expressions that specify the bounds of the arrays
2036 // Note: function types are handled in the common path with C.
2037 if (T->isReferenceType()) {
2038 Diag(Loc, diag::err_illegal_decl_array_of_references)
2039 << getPrintableNameForEntity(Entity) << T;
2043 if (T->isVoidType() || T->isIncompleteArrayType()) {
2044 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2048 if (RequireNonAbstractType(Brackets.getBegin(), T,
2049 diag::err_array_of_abstract_type))
2052 // Mentioning a member pointer type for an array type causes us to lock in
2053 // an inheritance model, even if it's inside an unused typedef.
2054 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2055 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2056 if (!MPTy->getClass()->isDependentType())
2057 (void)isCompleteType(Loc, T);
2060 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2061 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2062 if (RequireCompleteType(Loc, T,
2063 diag::err_illegal_decl_array_incomplete_type))
2067 if (T->isFunctionType()) {
2068 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2069 << getPrintableNameForEntity(Entity) << T;
2073 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2074 // If the element type is a struct or union that contains a variadic
2075 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2076 if (EltTy->getDecl()->hasFlexibleArrayMember())
2077 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2078 } else if (T->isObjCObjectType()) {
2079 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2083 // Do placeholder conversions on the array size expression.
2084 if (ArraySize && ArraySize->hasPlaceholderType()) {
2085 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2086 if (Result.isInvalid()) return QualType();
2087 ArraySize = Result.get();
2090 // Do lvalue-to-rvalue conversions on the array size expression.
2091 if (ArraySize && !ArraySize->isRValue()) {
2092 ExprResult Result = DefaultLvalueConversion(ArraySize);
2093 if (Result.isInvalid())
2096 ArraySize = Result.get();
2099 // C99 6.7.5.2p1: The size expression shall have integer type.
2100 // C++11 allows contextual conversions to such types.
2101 if (!getLangOpts().CPlusPlus11 &&
2102 ArraySize && !ArraySize->isTypeDependent() &&
2103 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2104 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2105 << ArraySize->getType() << ArraySize->getSourceRange();
2109 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2111 if (ASM == ArrayType::Star)
2112 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2114 T = Context.getIncompleteArrayType(T, ASM, Quals);
2115 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2116 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2117 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2118 !T->isConstantSizeType()) ||
2119 isArraySizeVLA(*this, ArraySize, ConstVal)) {
2120 // Even in C++11, don't allow contextual conversions in the array bound
2122 if (getLangOpts().CPlusPlus11 &&
2123 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2124 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2125 << ArraySize->getType() << ArraySize->getSourceRange();
2129 // C99: an array with an element type that has a non-constant-size is a VLA.
2130 // C99: an array with a non-ICE size is a VLA. We accept any expression
2131 // that we can fold to a non-zero positive value as an extension.
2132 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2134 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2135 // have a value greater than zero.
2136 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2138 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2139 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2141 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2142 << ArraySize->getSourceRange();
2145 if (ConstVal == 0) {
2146 // GCC accepts zero sized static arrays. We allow them when
2147 // we're not in a SFINAE context.
2148 Diag(ArraySize->getLocStart(),
2149 isSFINAEContext()? diag::err_typecheck_zero_array_size
2150 : diag::ext_typecheck_zero_array_size)
2151 << ArraySize->getSourceRange();
2153 if (ASM == ArrayType::Static) {
2154 Diag(ArraySize->getLocStart(),
2155 diag::warn_typecheck_zero_static_array_size)
2156 << ArraySize->getSourceRange();
2157 ASM = ArrayType::Normal;
2159 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2160 !T->isIncompleteType() && !T->isUndeducedType()) {
2161 // Is the array too large?
2162 unsigned ActiveSizeBits
2163 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2164 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2165 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2166 << ConstVal.toString(10)
2167 << ArraySize->getSourceRange();
2172 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2175 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2176 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2177 Diag(Loc, diag::err_opencl_vla);
2180 // CUDA device code doesn't support VLAs.
2181 if (getLangOpts().CUDA && T->isVariableArrayType())
2182 CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget();
2184 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2185 if (!getLangOpts().C99) {
2186 if (T->isVariableArrayType()) {
2187 // Prohibit the use of VLAs during template argument deduction.
2188 if (isSFINAEContext()) {
2189 Diag(Loc, diag::err_vla_in_sfinae);
2192 // Just extwarn about VLAs.
2194 Diag(Loc, diag::ext_vla);
2195 } else if (ASM != ArrayType::Normal || Quals != 0)
2197 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2198 : diag::ext_c99_array_usage) << ASM;
2201 if (T->isVariableArrayType()) {
2202 // Warn about VLAs for -Wvla.
2203 Diag(Loc, diag::warn_vla_used);
2206 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2207 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2208 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2209 if (getLangOpts().OpenCL) {
2210 const QualType ArrType = Context.getBaseElementType(T);
2211 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2212 ArrType->isSamplerT() || ArrType->isImageType()) {
2213 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2221 /// \brief Build an ext-vector type.
2223 /// Run the required checks for the extended vector type.
2224 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2225 SourceLocation AttrLoc) {
2226 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2227 // in conjunction with complex types (pointers, arrays, functions, etc.).
2229 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2230 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2231 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2232 // of bool aren't allowed.
2233 if ((!T->isDependentType() && !T->isIntegerType() &&
2234 !T->isRealFloatingType()) ||
2235 T->isBooleanType()) {
2236 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2240 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2241 llvm::APSInt vecSize(32);
2242 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2243 Diag(AttrLoc, diag::err_attribute_argument_type)
2244 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2245 << ArraySize->getSourceRange();
2249 // Unlike gcc's vector_size attribute, the size is specified as the
2250 // number of elements, not the number of bytes.
2251 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2253 if (vectorSize == 0) {
2254 Diag(AttrLoc, diag::err_attribute_zero_size)
2255 << ArraySize->getSourceRange();
2259 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2260 Diag(AttrLoc, diag::err_attribute_size_too_large)
2261 << ArraySize->getSourceRange();
2265 return Context.getExtVectorType(T, vectorSize);
2268 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2271 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2272 if (T->isArrayType() || T->isFunctionType()) {
2273 Diag(Loc, diag::err_func_returning_array_function)
2274 << T->isFunctionType() << T;
2278 // Functions cannot return half FP.
2279 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2280 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2281 FixItHint::CreateInsertion(Loc, "*");
2285 // Methods cannot return interface types. All ObjC objects are
2286 // passed by reference.
2287 if (T->isObjCObjectType()) {
2288 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2289 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2296 /// Check the extended parameter information. Most of the necessary
2297 /// checking should occur when applying the parameter attribute; the
2298 /// only other checks required are positional restrictions.
2299 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2300 const FunctionProtoType::ExtProtoInfo &EPI,
2301 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2302 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2304 bool hasCheckedSwiftCall = false;
2305 auto checkForSwiftCC = [&](unsigned paramIndex) {
2306 // Only do this once.
2307 if (hasCheckedSwiftCall) return;
2308 hasCheckedSwiftCall = true;
2309 if (EPI.ExtInfo.getCC() == CC_Swift) return;
2310 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2311 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2314 for (size_t paramIndex = 0, numParams = paramTypes.size();
2315 paramIndex != numParams; ++paramIndex) {
2316 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2317 // Nothing interesting to check for orindary-ABI parameters.
2318 case ParameterABI::Ordinary:
2321 // swift_indirect_result parameters must be a prefix of the function
2323 case ParameterABI::SwiftIndirectResult:
2324 checkForSwiftCC(paramIndex);
2325 if (paramIndex != 0 &&
2326 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2327 != ParameterABI::SwiftIndirectResult) {
2328 S.Diag(getParamLoc(paramIndex),
2329 diag::err_swift_indirect_result_not_first);
2333 case ParameterABI::SwiftContext:
2334 checkForSwiftCC(paramIndex);
2337 // swift_error parameters must be preceded by a swift_context parameter.
2338 case ParameterABI::SwiftErrorResult:
2339 checkForSwiftCC(paramIndex);
2340 if (paramIndex == 0 ||
2341 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2342 ParameterABI::SwiftContext) {
2343 S.Diag(getParamLoc(paramIndex),
2344 diag::err_swift_error_result_not_after_swift_context);
2348 llvm_unreachable("bad ABI kind");
2352 QualType Sema::BuildFunctionType(QualType T,
2353 MutableArrayRef<QualType> ParamTypes,
2354 SourceLocation Loc, DeclarationName Entity,
2355 const FunctionProtoType::ExtProtoInfo &EPI) {
2356 bool Invalid = false;
2358 Invalid |= CheckFunctionReturnType(T, Loc);
2360 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2361 // FIXME: Loc is too inprecise here, should use proper locations for args.
2362 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2363 if (ParamType->isVoidType()) {
2364 Diag(Loc, diag::err_param_with_void_type);
2366 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2367 // Disallow half FP arguments.
2368 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2369 FixItHint::CreateInsertion(Loc, "*");
2373 ParamTypes[Idx] = ParamType;
2376 if (EPI.ExtParameterInfos) {
2377 checkExtParameterInfos(*this, ParamTypes, EPI,
2378 [=](unsigned i) { return Loc; });
2384 return Context.getFunctionType(T, ParamTypes, EPI);
2387 /// \brief Build a member pointer type \c T Class::*.
2389 /// \param T the type to which the member pointer refers.
2390 /// \param Class the class type into which the member pointer points.
2391 /// \param Loc the location where this type begins
2392 /// \param Entity the name of the entity that will have this member pointer type
2394 /// \returns a member pointer type, if successful, or a NULL type if there was
2396 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2398 DeclarationName Entity) {
2399 // Verify that we're not building a pointer to pointer to function with
2400 // exception specification.
2401 if (CheckDistantExceptionSpec(T)) {
2402 Diag(Loc, diag::err_distant_exception_spec);
2406 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2407 // with reference type, or "cv void."
2408 if (T->isReferenceType()) {
2409 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2410 << getPrintableNameForEntity(Entity) << T;
2414 if (T->isVoidType()) {
2415 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2416 << getPrintableNameForEntity(Entity);
2420 if (!Class->isDependentType() && !Class->isRecordType()) {
2421 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2425 // Adjust the default free function calling convention to the default method
2426 // calling convention.
2428 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2429 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2430 if (T->isFunctionType())
2431 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2433 return Context.getMemberPointerType(T, Class.getTypePtr());
2436 /// \brief Build a block pointer type.
2438 /// \param T The type to which we'll be building a block pointer.
2440 /// \param Loc The source location, used for diagnostics.
2442 /// \param Entity The name of the entity that involves the block pointer
2445 /// \returns A suitable block pointer type, if there are no
2446 /// errors. Otherwise, returns a NULL type.
2447 QualType Sema::BuildBlockPointerType(QualType T,
2449 DeclarationName Entity) {
2450 if (!T->isFunctionType()) {
2451 Diag(Loc, diag::err_nonfunction_block_type);
2455 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2458 return Context.getBlockPointerType(T);
2461 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2462 QualType QT = Ty.get();
2464 if (TInfo) *TInfo = nullptr;
2468 TypeSourceInfo *DI = nullptr;
2469 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2470 QT = LIT->getType();
2471 DI = LIT->getTypeSourceInfo();
2474 if (TInfo) *TInfo = DI;
2478 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2479 Qualifiers::ObjCLifetime ownership,
2480 unsigned chunkIndex);
2482 /// Given that this is the declaration of a parameter under ARC,
2483 /// attempt to infer attributes and such for pointer-to-whatever
2485 static void inferARCWriteback(TypeProcessingState &state,
2486 QualType &declSpecType) {
2487 Sema &S = state.getSema();
2488 Declarator &declarator = state.getDeclarator();
2490 // TODO: should we care about decl qualifiers?
2492 // Check whether the declarator has the expected form. We walk
2493 // from the inside out in order to make the block logic work.
2494 unsigned outermostPointerIndex = 0;
2495 bool isBlockPointer = false;
2496 unsigned numPointers = 0;
2497 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2498 unsigned chunkIndex = i;
2499 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2500 switch (chunk.Kind) {
2501 case DeclaratorChunk::Paren:
2505 case DeclaratorChunk::Reference:
2506 case DeclaratorChunk::Pointer:
2507 // Count the number of pointers. Treat references
2508 // interchangeably as pointers; if they're mis-ordered, normal
2509 // type building will discover that.
2510 outermostPointerIndex = chunkIndex;
2514 case DeclaratorChunk::BlockPointer:
2515 // If we have a pointer to block pointer, that's an acceptable
2516 // indirect reference; anything else is not an application of
2518 if (numPointers != 1) return;
2520 outermostPointerIndex = chunkIndex;
2521 isBlockPointer = true;
2523 // We don't care about pointer structure in return values here.
2526 case DeclaratorChunk::Array: // suppress if written (id[])?
2527 case DeclaratorChunk::Function:
2528 case DeclaratorChunk::MemberPointer:
2529 case DeclaratorChunk::Pipe:
2535 // If we have *one* pointer, then we want to throw the qualifier on
2536 // the declaration-specifiers, which means that it needs to be a
2537 // retainable object type.
2538 if (numPointers == 1) {
2539 // If it's not a retainable object type, the rule doesn't apply.
2540 if (!declSpecType->isObjCRetainableType()) return;
2542 // If it already has lifetime, don't do anything.
2543 if (declSpecType.getObjCLifetime()) return;
2545 // Otherwise, modify the type in-place.
2548 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2549 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2551 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2552 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2554 // If we have *two* pointers, then we want to throw the qualifier on
2555 // the outermost pointer.
2556 } else if (numPointers == 2) {
2557 // If we don't have a block pointer, we need to check whether the
2558 // declaration-specifiers gave us something that will turn into a
2559 // retainable object pointer after we slap the first pointer on it.
2560 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2563 // Look for an explicit lifetime attribute there.
2564 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2565 if (chunk.Kind != DeclaratorChunk::Pointer &&
2566 chunk.Kind != DeclaratorChunk::BlockPointer)
2568 for (const AttributeList *attr = chunk.getAttrs(); attr;
2569 attr = attr->getNext())
2570 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2573 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2574 outermostPointerIndex);
2576 // Any other number of pointers/references does not trigger the rule.
2579 // TODO: mark whether we did this inference?
2582 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2583 SourceLocation FallbackLoc,
2584 SourceLocation ConstQualLoc,
2585 SourceLocation VolatileQualLoc,
2586 SourceLocation RestrictQualLoc,
2587 SourceLocation AtomicQualLoc,
2588 SourceLocation UnalignedQualLoc) {
2596 } const QualKinds[5] = {
2597 { "const", DeclSpec::TQ_const, ConstQualLoc },
2598 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2599 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2600 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2601 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2604 SmallString<32> QualStr;
2605 unsigned NumQuals = 0;
2607 FixItHint FixIts[5];
2609 // Build a string naming the redundant qualifiers.
2610 for (auto &E : QualKinds) {
2611 if (Quals & E.Mask) {
2612 if (!QualStr.empty()) QualStr += ' ';
2615 // If we have a location for the qualifier, offer a fixit.
2616 SourceLocation QualLoc = E.Loc;
2617 if (QualLoc.isValid()) {
2618 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2619 if (Loc.isInvalid() ||
2620 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2628 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2629 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2632 // Diagnose pointless type qualifiers on the return type of a function.
2633 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2635 unsigned FunctionChunkIndex) {
2636 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2637 // FIXME: TypeSourceInfo doesn't preserve location information for
2639 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2640 RetTy.getLocalCVRQualifiers(),
2641 D.getIdentifierLoc());
2645 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2646 End = D.getNumTypeObjects();
2647 OuterChunkIndex != End; ++OuterChunkIndex) {
2648 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2649 switch (OuterChunk.Kind) {
2650 case DeclaratorChunk::Paren:
2653 case DeclaratorChunk::Pointer: {
2654 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2655 S.diagnoseIgnoredQualifiers(
2656 diag::warn_qual_return_type,
2659 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2660 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2661 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2662 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
2663 SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
2667 case DeclaratorChunk::Function:
2668 case DeclaratorChunk::BlockPointer:
2669 case DeclaratorChunk::Reference:
2670 case DeclaratorChunk::Array:
2671 case DeclaratorChunk::MemberPointer:
2672 case DeclaratorChunk::Pipe:
2673 // FIXME: We can't currently provide an accurate source location and a
2674 // fix-it hint for these.
2675 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2676 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2677 RetTy.getCVRQualifiers() | AtomicQual,
2678 D.getIdentifierLoc());
2682 llvm_unreachable("unknown declarator chunk kind");
2685 // If the qualifiers come from a conversion function type, don't diagnose
2686 // them -- they're not necessarily redundant, since such a conversion
2687 // operator can be explicitly called as "x.operator const int()".
2688 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2691 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2692 // which are present there.
2693 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2694 D.getDeclSpec().getTypeQualifiers(),
2695 D.getIdentifierLoc(),
2696 D.getDeclSpec().getConstSpecLoc(),
2697 D.getDeclSpec().getVolatileSpecLoc(),
2698 D.getDeclSpec().getRestrictSpecLoc(),
2699 D.getDeclSpec().getAtomicSpecLoc(),
2700 D.getDeclSpec().getUnalignedSpecLoc());
2703 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2704 TypeSourceInfo *&ReturnTypeInfo) {
2705 Sema &SemaRef = state.getSema();
2706 Declarator &D = state.getDeclarator();
2708 ReturnTypeInfo = nullptr;
2710 // The TagDecl owned by the DeclSpec.
2711 TagDecl *OwnedTagDecl = nullptr;
2713 switch (D.getName().getKind()) {
2714 case UnqualifiedId::IK_ImplicitSelfParam:
2715 case UnqualifiedId::IK_OperatorFunctionId:
2716 case UnqualifiedId::IK_Identifier:
2717 case UnqualifiedId::IK_LiteralOperatorId:
2718 case UnqualifiedId::IK_TemplateId:
2719 T = ConvertDeclSpecToType(state);
2721 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2722 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2723 // Owned declaration is embedded in declarator.
2724 OwnedTagDecl->setEmbeddedInDeclarator(true);
2728 case UnqualifiedId::IK_ConstructorName:
2729 case UnqualifiedId::IK_ConstructorTemplateId:
2730 case UnqualifiedId::IK_DestructorName:
2731 // Constructors and destructors don't have return types. Use
2733 T = SemaRef.Context.VoidTy;
2734 processTypeAttrs(state, T, TAL_DeclSpec,
2735 D.getDeclSpec().getAttributes().getList());
2738 case UnqualifiedId::IK_DeductionGuideName:
2739 // Deduction guides have a trailing return type and no type in their
2740 // decl-specifier sequence. Use a placeholder return type for now.
2741 T = SemaRef.Context.DependentTy;
2744 case UnqualifiedId::IK_ConversionFunctionId:
2745 // The result type of a conversion function is the type that it
2747 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2752 if (D.getAttributes())
2753 distributeTypeAttrsFromDeclarator(state, T);
2755 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2756 if (DeducedType *Deduced = T->getContainedDeducedType()) {
2757 AutoType *Auto = dyn_cast<AutoType>(Deduced);
2760 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
2761 // class template argument deduction)?
2762 bool IsCXXAutoType =
2763 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
2765 switch (D.getContext()) {
2766 case Declarator::LambdaExprContext:
2767 // Declared return type of a lambda-declarator is implicit and is always
2770 case Declarator::ObjCParameterContext:
2771 case Declarator::ObjCResultContext:
2772 case Declarator::PrototypeContext:
2775 case Declarator::LambdaExprParameterContext:
2776 // In C++14, generic lambdas allow 'auto' in their parameters.
2777 if (!SemaRef.getLangOpts().CPlusPlus14 ||
2778 !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto)
2781 // If auto is mentioned in a lambda parameter context, convert it to a
2782 // template parameter type.
2783 sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda();
2784 assert(LSI && "No LambdaScopeInfo on the stack!");
2785 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
2786 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
2787 const bool IsParameterPack = D.hasEllipsis();
2789 // Create the TemplateTypeParmDecl here to retrieve the corresponding
2790 // template parameter type. Template parameters are temporarily added
2791 // to the TU until the associated TemplateDecl is created.
2792 TemplateTypeParmDecl *CorrespondingTemplateParam =
2793 TemplateTypeParmDecl::Create(
2794 SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(),
2795 /*KeyLoc*/SourceLocation(), /*NameLoc*/D.getLocStart(),
2796 TemplateParameterDepth, AutoParameterPosition,
2797 /*Identifier*/nullptr, false, IsParameterPack);
2798 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
2799 // Replace the 'auto' in the function parameter with this invented
2800 // template type parameter.
2801 // FIXME: Retain some type sugar to indicate that this was written
2803 T = SemaRef.ReplaceAutoType(
2804 T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
2807 case Declarator::MemberContext: {
2808 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2809 D.isFunctionDeclarator())
2811 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2812 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2813 case TTK_Enum: llvm_unreachable("unhandled tag kind");
2814 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2815 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
2816 case TTK_Class: Error = 5; /* Class member */ break;
2817 case TTK_Interface: Error = 6; /* Interface member */ break;
2819 if (D.getDeclSpec().isFriendSpecified())
2820 Error = 20; // Friend type
2823 case Declarator::CXXCatchContext:
2824 case Declarator::ObjCCatchContext:
2825 Error = 7; // Exception declaration
2827 case Declarator::TemplateParamContext:
2828 if (isa<DeducedTemplateSpecializationType>(Deduced))
2829 Error = 19; // Template parameter
2830 else if (!SemaRef.getLangOpts().CPlusPlus1z)
2831 Error = 8; // Template parameter (until C++1z)
2833 case Declarator::BlockLiteralContext:
2834 Error = 9; // Block literal
2836 case Declarator::TemplateTypeArgContext:
2837 Error = 10; // Template type argument
2839 case Declarator::AliasDeclContext:
2840 case Declarator::AliasTemplateContext:
2841 Error = 12; // Type alias
2843 case Declarator::TrailingReturnContext:
2844 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2845 Error = 13; // Function return type
2847 case Declarator::ConversionIdContext:
2848 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2849 Error = 14; // conversion-type-id
2851 case Declarator::FunctionalCastContext:
2852 if (isa<DeducedTemplateSpecializationType>(Deduced))
2855 case Declarator::TypeNameContext:
2856 Error = 15; // Generic
2858 case Declarator::FileContext:
2859 case Declarator::BlockContext:
2860 case Declarator::ForContext:
2861 case Declarator::InitStmtContext:
2862 case Declarator::ConditionContext:
2863 // FIXME: P0091R3 (erroneously) does not permit class template argument
2864 // deduction in conditions, for-init-statements, and other declarations
2865 // that are not simple-declarations.
2867 case Declarator::CXXNewContext:
2868 // FIXME: P0091R3 does not permit class template argument deduction here,
2869 // but we follow GCC and allow it anyway.
2870 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
2871 Error = 17; // 'new' type
2873 case Declarator::KNRTypeListContext:
2874 Error = 18; // K&R function parameter
2878 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2881 // In Objective-C it is an error to use 'auto' on a function declarator
2882 // (and everywhere for '__auto_type').
2883 if (D.isFunctionDeclarator() &&
2884 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
2887 bool HaveTrailing = false;
2889 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2890 // contains a trailing return type. That is only legal at the outermost
2891 // level. Check all declarator chunks (outermost first) anyway, to give
2892 // better diagnostics.
2893 // We don't support '__auto_type' with trailing return types.
2894 // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
2895 if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
2896 D.hasTrailingReturnType()) {
2897 HaveTrailing = true;
2901 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2902 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2903 AutoRange = D.getName().getSourceRange();
2908 switch (Auto->getKeyword()) {
2909 case AutoTypeKeyword::Auto: Kind = 0; break;
2910 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
2911 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
2914 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
2915 "unknown auto type");
2919 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
2920 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
2922 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2923 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
2924 << QualType(Deduced, 0) << AutoRange;
2925 if (auto *TD = TN.getAsTemplateDecl())
2926 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
2928 T = SemaRef.Context.IntTy;
2929 D.setInvalidType(true);
2930 } else if (!HaveTrailing) {
2931 // If there was a trailing return type, we already got
2932 // warn_cxx98_compat_trailing_return_type in the parser.
2933 SemaRef.Diag(AutoRange.getBegin(),
2934 diag::warn_cxx98_compat_auto_type_specifier)
2939 if (SemaRef.getLangOpts().CPlusPlus &&
2940 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2941 // Check the contexts where C++ forbids the declaration of a new class
2942 // or enumeration in a type-specifier-seq.
2943 unsigned DiagID = 0;
2944 switch (D.getContext()) {
2945 case Declarator::TrailingReturnContext:
2946 // Class and enumeration definitions are syntactically not allowed in
2947 // trailing return types.
2948 llvm_unreachable("parser should not have allowed this");
2950 case Declarator::FileContext:
2951 case Declarator::MemberContext:
2952 case Declarator::BlockContext:
2953 case Declarator::ForContext:
2954 case Declarator::InitStmtContext:
2955 case Declarator::BlockLiteralContext:
2956 case Declarator::LambdaExprContext:
2957 // C++11 [dcl.type]p3:
2958 // A type-specifier-seq shall not define a class or enumeration unless
2959 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2960 // the declaration of a template-declaration.
2961 case Declarator::AliasDeclContext:
2963 case Declarator::AliasTemplateContext:
2964 DiagID = diag::err_type_defined_in_alias_template;
2966 case Declarator::TypeNameContext:
2967 case Declarator::FunctionalCastContext:
2968 case Declarator::ConversionIdContext:
2969 case Declarator::TemplateParamContext:
2970 case Declarator::CXXNewContext:
2971 case Declarator::CXXCatchContext:
2972 case Declarator::ObjCCatchContext:
2973 case Declarator::TemplateTypeArgContext:
2974 DiagID = diag::err_type_defined_in_type_specifier;
2976 case Declarator::PrototypeContext:
2977 case Declarator::LambdaExprParameterContext:
2978 case Declarator::ObjCParameterContext:
2979 case Declarator::ObjCResultContext:
2980 case Declarator::KNRTypeListContext:
2982 // Types shall not be defined in return or parameter types.
2983 DiagID = diag::err_type_defined_in_param_type;
2985 case Declarator::ConditionContext:
2987 // The type-specifier-seq shall not contain typedef and shall not declare
2988 // a new class or enumeration.
2989 DiagID = diag::err_type_defined_in_condition;
2994 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
2995 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2996 D.setInvalidType(true);
3000 assert(!T.isNull() && "This function should not return a null type");
3004 /// Produce an appropriate diagnostic for an ambiguity between a function
3005 /// declarator and a C++ direct-initializer.
3006 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3007 DeclaratorChunk &DeclType, QualType RT) {
3008 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3009 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3011 // If the return type is void there is no ambiguity.
3012 if (RT->isVoidType())
3015 // An initializer for a non-class type can have at most one argument.
3016 if (!RT->isRecordType() && FTI.NumParams > 1)
3019 // An initializer for a reference must have exactly one argument.
3020 if (RT->isReferenceType() && FTI.NumParams != 1)
3023 // Only warn if this declarator is declaring a function at block scope, and
3024 // doesn't have a storage class (such as 'extern') specified.
3025 if (!D.isFunctionDeclarator() ||
3026 D.getFunctionDefinitionKind() != FDK_Declaration ||
3027 !S.CurContext->isFunctionOrMethod() ||
3028 D.getDeclSpec().getStorageClassSpec()
3029 != DeclSpec::SCS_unspecified)
3032 // Inside a condition, a direct initializer is not permitted. We allow one to
3033 // be parsed in order to give better diagnostics in condition parsing.
3034 if (D.getContext() == Declarator::ConditionContext)
3037 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3039 S.Diag(DeclType.Loc,
3040 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3041 : diag::warn_empty_parens_are_function_decl)
3044 // If the declaration looks like:
3047 // and name lookup finds a function named 'f', then the ',' was
3048 // probably intended to be a ';'.
3049 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3050 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3051 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3052 if (Comma.getFileID() != Name.getFileID() ||
3053 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3054 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3055 Sema::LookupOrdinaryName);
3056 if (S.LookupName(Result, S.getCurScope()))
3057 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3058 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3059 << D.getIdentifier();
3063 if (FTI.NumParams > 0) {
3064 // For a declaration with parameters, eg. "T var(T());", suggest adding
3065 // parens around the first parameter to turn the declaration into a
3066 // variable declaration.
3067 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3068 SourceLocation B = Range.getBegin();
3069 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3070 // FIXME: Maybe we should suggest adding braces instead of parens
3071 // in C++11 for classes that don't have an initializer_list constructor.
3072 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3073 << FixItHint::CreateInsertion(B, "(")
3074 << FixItHint::CreateInsertion(E, ")");
3076 // For a declaration without parameters, eg. "T var();", suggest replacing
3077 // the parens with an initializer to turn the declaration into a variable
3079 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3081 // Empty parens mean value-initialization, and no parens mean
3082 // default initialization. These are equivalent if the default
3083 // constructor is user-provided or if zero-initialization is a
3085 if (RD && RD->hasDefinition() &&
3086 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3087 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3088 << FixItHint::CreateRemoval(ParenRange);
3091 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3092 if (Init.empty() && S.LangOpts.CPlusPlus11)
3095 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3096 << FixItHint::CreateReplacement(ParenRange, Init);
3101 /// Helper for figuring out the default CC for a function declarator type. If
3102 /// this is the outermost chunk, then we can determine the CC from the
3103 /// declarator context. If not, then this could be either a member function
3104 /// type or normal function type.
3106 getCCForDeclaratorChunk(Sema &S, Declarator &D,
3107 const DeclaratorChunk::FunctionTypeInfo &FTI,
3108 unsigned ChunkIndex) {
3109 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3111 // Check for an explicit CC attribute.
3112 for (auto Attr = FTI.AttrList; Attr; Attr = Attr->getNext()) {
3113 switch (Attr->getKind()) {
3114 CALLING_CONV_ATTRS_CASELIST: {
3115 // Ignore attributes that don't validate or can't apply to the
3116 // function type. We'll diagnose the failure to apply them in
3117 // handleFunctionTypeAttr.
3119 if (!S.CheckCallingConvAttr(*Attr, CC) &&
3120 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3131 bool IsCXXInstanceMethod = false;
3133 if (S.getLangOpts().CPlusPlus) {
3134 // Look inwards through parentheses to see if this chunk will form a
3135 // member pointer type or if we're the declarator. Any type attributes
3136 // between here and there will override the CC we choose here.
3137 unsigned I = ChunkIndex;
3138 bool FoundNonParen = false;
3139 while (I && !FoundNonParen) {
3141 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3142 FoundNonParen = true;
3145 if (FoundNonParen) {
3146 // If we're not the declarator, we're a regular function type unless we're
3147 // in a member pointer.
3148 IsCXXInstanceMethod =
3149 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3150 } else if (D.getContext() == Declarator::LambdaExprContext) {
3151 // This can only be a call operator for a lambda, which is an instance
3153 IsCXXInstanceMethod = true;
3155 // We're the innermost decl chunk, so must be a function declarator.
3156 assert(D.isFunctionDeclarator());
3158 // If we're inside a record, we're declaring a method, but it could be
3159 // explicitly or implicitly static.
3160 IsCXXInstanceMethod =
3161 D.isFirstDeclarationOfMember() &&
3162 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3163 !D.isStaticMember();
3167 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3168 IsCXXInstanceMethod);
3170 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3171 // and AMDGPU targets, hence it cannot be treated as a calling
3172 // convention attribute. This is the simplest place to infer
3173 // calling convention for OpenCL kernels.
3174 if (S.getLangOpts().OpenCL) {
3175 for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
3176 Attr; Attr = Attr->getNext()) {
3177 if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
3178 llvm::Triple::ArchType arch = S.Context.getTargetInfo().getTriple().getArch();
3179 if (arch == llvm::Triple::spir || arch == llvm::Triple::spir64 ||
3180 arch == llvm::Triple::amdgcn || arch == llvm::Triple::r600) {
3181 CC = CC_OpenCLKernel;
3192 /// A simple notion of pointer kinds, which matches up with the various
3193 /// pointer declarators.
3194 enum class SimplePointerKind {
3200 } // end anonymous namespace
3202 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3203 switch (nullability) {
3204 case NullabilityKind::NonNull:
3205 if (!Ident__Nonnull)
3206 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3207 return Ident__Nonnull;
3209 case NullabilityKind::Nullable:
3210 if (!Ident__Nullable)
3211 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3212 return Ident__Nullable;
3214 case NullabilityKind::Unspecified:
3215 if (!Ident__Null_unspecified)
3216 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3217 return Ident__Null_unspecified;
3219 llvm_unreachable("Unknown nullability kind.");
3222 /// Retrieve the identifier "NSError".
3223 IdentifierInfo *Sema::getNSErrorIdent() {
3225 Ident_NSError = PP.getIdentifierInfo("NSError");
3227 return Ident_NSError;
3230 /// Check whether there is a nullability attribute of any kind in the given
3232 static bool hasNullabilityAttr(const AttributeList *attrs) {
3233 for (const AttributeList *attr = attrs; attr;
3234 attr = attr->getNext()) {
3235 if (attr->getKind() == AttributeList::AT_TypeNonNull ||
3236 attr->getKind() == AttributeList::AT_TypeNullable ||
3237 attr->getKind() == AttributeList::AT_TypeNullUnspecified)
3245 /// Describes the kind of a pointer a declarator describes.
3246 enum class PointerDeclaratorKind {
3249 // Single-level pointer.
3251 // Multi-level pointer (of any pointer kind).
3254 MaybePointerToCFRef,
3258 NSErrorPointerPointer,
3261 /// Describes a declarator chunk wrapping a pointer that marks inference as
3263 // These values must be kept in sync with diagnostics.
3264 enum class PointerWrappingDeclaratorKind {
3265 /// Pointer is top-level.
3267 /// Pointer is an array element.
3269 /// Pointer is the referent type of a C++ reference.
3272 } // end anonymous namespace
3274 /// Classify the given declarator, whose type-specified is \c type, based on
3275 /// what kind of pointer it refers to.
3277 /// This is used to determine the default nullability.
3278 static PointerDeclaratorKind
3279 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
3280 PointerWrappingDeclaratorKind &wrappingKind) {
3281 unsigned numNormalPointers = 0;
3283 // For any dependent type, we consider it a non-pointer.
3284 if (type->isDependentType())
3285 return PointerDeclaratorKind::NonPointer;
3287 // Look through the declarator chunks to identify pointers.
3288 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3289 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3290 switch (chunk.Kind) {
3291 case DeclaratorChunk::Array:
3292 if (numNormalPointers == 0)
3293 wrappingKind = PointerWrappingDeclaratorKind::Array;
3296 case DeclaratorChunk::Function:
3297 case DeclaratorChunk::Pipe:
3300 case DeclaratorChunk::BlockPointer:
3301 case DeclaratorChunk::MemberPointer:
3302 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3303 : PointerDeclaratorKind::SingleLevelPointer;
3305 case DeclaratorChunk::Paren:
3308 case DeclaratorChunk::Reference:
3309 if (numNormalPointers == 0)
3310 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3313 case DeclaratorChunk::Pointer:
3314 ++numNormalPointers;
3315 if (numNormalPointers > 2)
3316 return PointerDeclaratorKind::MultiLevelPointer;
3321 // Then, dig into the type specifier itself.
3322 unsigned numTypeSpecifierPointers = 0;
3324 // Decompose normal pointers.
3325 if (auto ptrType = type->getAs<PointerType>()) {
3326 ++numNormalPointers;
3328 if (numNormalPointers > 2)
3329 return PointerDeclaratorKind::MultiLevelPointer;
3331 type = ptrType->getPointeeType();
3332 ++numTypeSpecifierPointers;
3336 // Decompose block pointers.
3337 if (type->getAs<BlockPointerType>()) {
3338 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3339 : PointerDeclaratorKind::SingleLevelPointer;
3342 // Decompose member pointers.
3343 if (type->getAs<MemberPointerType>()) {
3344 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3345 : PointerDeclaratorKind::SingleLevelPointer;
3348 // Look at Objective-C object pointers.
3349 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3350 ++numNormalPointers;
3351 ++numTypeSpecifierPointers;
3353 // If this is NSError**, report that.
3354 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3355 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3356 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3357 return PointerDeclaratorKind::NSErrorPointerPointer;
3364 // Look at Objective-C class types.
3365 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3366 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3367 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3368 return PointerDeclaratorKind::NSErrorPointerPointer;;
3374 // If at this point we haven't seen a pointer, we won't see one.
3375 if (numNormalPointers == 0)
3376 return PointerDeclaratorKind::NonPointer;
3378 if (auto recordType = type->getAs<RecordType>()) {
3379 RecordDecl *recordDecl = recordType->getDecl();
3381 bool isCFError = false;
3383 // If we already know about CFError, test it directly.
3384 isCFError = (S.CFError == recordDecl);
3386 // Check whether this is CFError, which we identify based on its bridge
3388 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3389 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) {
3390 if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) {
3391 S.CFError = recordDecl;
3398 // If this is CFErrorRef*, report it as such.
3399 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3400 return PointerDeclaratorKind::CFErrorRefPointer;
3408 switch (numNormalPointers) {
3410 return PointerDeclaratorKind::NonPointer;
3413 return PointerDeclaratorKind::SingleLevelPointer;
3416 return PointerDeclaratorKind::MaybePointerToCFRef;
3419 return PointerDeclaratorKind::MultiLevelPointer;
3423 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
3424 SourceLocation loc) {
3425 // If we're anywhere in a function, method, or closure context, don't perform
3426 // completeness checks.
3427 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3428 if (ctx->isFunctionOrMethod())
3431 if (ctx->isFileContext())
3435 // We only care about the expansion location.
3436 loc = S.SourceMgr.getExpansionLoc(loc);
3437 FileID file = S.SourceMgr.getFileID(loc);
3438 if (file.isInvalid())
3441 // Retrieve file information.
3442 bool invalid = false;
3443 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3444 if (invalid || !sloc.isFile())
3447 // We don't want to perform completeness checks on the main file or in
3449 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3450 if (fileInfo.getIncludeLoc().isInvalid())
3452 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3453 S.Diags.getSuppressSystemWarnings()) {
3460 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
3461 /// taking into account whitespace before and after.
3462 static void fixItNullability(Sema &S, DiagnosticBuilder &Diag,
3463 SourceLocation PointerLoc,
3464 NullabilityKind Nullability) {
3465 assert(PointerLoc.isValid());
3466 if (PointerLoc.isMacroID())
3469 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
3470 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
3473 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
3477 SmallString<32> InsertionTextBuf{" "};
3478 InsertionTextBuf += getNullabilitySpelling(Nullability);
3479 InsertionTextBuf += " ";
3480 StringRef InsertionText = InsertionTextBuf.str();
3482 if (isWhitespace(*NextChar)) {
3483 InsertionText = InsertionText.drop_back();
3484 } else if (NextChar[-1] == '[') {
3485 if (NextChar[0] == ']')
3486 InsertionText = InsertionText.drop_back().drop_front();
3488 InsertionText = InsertionText.drop_front();
3489 } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
3490 !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
3491 InsertionText = InsertionText.drop_back().drop_front();
3494 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
3497 static void emitNullabilityConsistencyWarning(Sema &S,
3498 SimplePointerKind PointerKind,
3499 SourceLocation PointerLoc) {
3500 assert(PointerLoc.isValid());
3502 if (PointerKind == SimplePointerKind::Array) {
3503 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
3505 S.Diag(PointerLoc, diag::warn_nullability_missing)
3506 << static_cast<unsigned>(PointerKind);
3509 if (PointerLoc.isMacroID())
3512 auto addFixIt = [&](NullabilityKind Nullability) {
3513 auto Diag = S.Diag(PointerLoc, diag::note_nullability_fix_it);
3514 Diag << static_cast<unsigned>(Nullability);
3515 Diag << static_cast<unsigned>(PointerKind);
3516 fixItNullability(S, Diag, PointerLoc, Nullability);
3518 addFixIt(NullabilityKind::Nullable);
3519 addFixIt(NullabilityKind::NonNull);
3522 /// Complains about missing nullability if the file containing \p pointerLoc
3523 /// has other uses of nullability (either the keywords or the \c assume_nonnull
3526 /// If the file has \e not seen other uses of nullability, this particular
3527 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
3528 static void checkNullabilityConsistency(Sema &S,
3529 SimplePointerKind pointerKind,
3530 SourceLocation pointerLoc) {
3531 // Determine which file we're performing consistency checking for.
3532 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3533 if (file.isInvalid())
3536 // If we haven't seen any type nullability in this file, we won't warn now
3538 FileNullability &fileNullability = S.NullabilityMap[file];
3539 if (!fileNullability.SawTypeNullability) {
3540 // If this is the first pointer declarator in the file, and the appropriate
3541 // warning is on, record it in case we need to diagnose it retroactively.
3542 diag::kind diagKind;
3543 if (pointerKind == SimplePointerKind::Array)
3544 diagKind = diag::warn_nullability_missing_array;
3546 diagKind = diag::warn_nullability_missing;
3548 if (fileNullability.PointerLoc.isInvalid() &&
3549 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
3550 fileNullability.PointerLoc = pointerLoc;
3551 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3557 // Complain about missing nullability.
3558 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc);
3561 /// Marks that a nullability feature has been used in the file containing
3564 /// If this file already had pointer types in it that were missing nullability,
3565 /// the first such instance is retroactively diagnosed.
3567 /// \sa checkNullabilityConsistency
3568 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
3569 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
3570 if (file.isInvalid())
3573 FileNullability &fileNullability = S.NullabilityMap[file];
3574 if (fileNullability.SawTypeNullability)
3576 fileNullability.SawTypeNullability = true;
3578 // If we haven't seen any type nullability before, now we have. Retroactively
3579 // diagnose the first unannotated pointer, if there was one.
3580 if (fileNullability.PointerLoc.isInvalid())
3583 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
3584 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc);
3587 /// Returns true if any of the declarator chunks before \p endIndex include a
3588 /// level of indirection: array, pointer, reference, or pointer-to-member.
3590 /// Because declarator chunks are stored in outer-to-inner order, testing
3591 /// every chunk before \p endIndex is testing all chunks that embed the current
3592 /// chunk as part of their type.
3594 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
3595 /// end index, in which case all chunks are tested.
3596 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
3597 unsigned i = endIndex;
3599 // Walk outwards along the declarator chunks.
3601 const DeclaratorChunk &DC = D.getTypeObject(i);
3603 case DeclaratorChunk::Paren:
3605 case DeclaratorChunk::Array:
3606 case DeclaratorChunk::Pointer:
3607 case DeclaratorChunk::Reference:
3608 case DeclaratorChunk::MemberPointer:
3610 case DeclaratorChunk::Function:
3611 case DeclaratorChunk::BlockPointer:
3612 case DeclaratorChunk::Pipe:
3613 // These are invalid anyway, so just ignore.
3620 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3621 QualType declSpecType,
3622 TypeSourceInfo *TInfo) {
3623 // The TypeSourceInfo that this function returns will not be a null type.
3624 // If there is an error, this function will fill in a dummy type as fallback.
3625 QualType T = declSpecType;
3626 Declarator &D = state.getDeclarator();
3627 Sema &S = state.getSema();
3628 ASTContext &Context = S.Context;
3629 const LangOptions &LangOpts = S.getLangOpts();
3631 // The name we're declaring, if any.
3632 DeclarationName Name;
3633 if (D.getIdentifier())
3634 Name = D.getIdentifier();
3636 // Does this declaration declare a typedef-name?
3637 bool IsTypedefName =
3638 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
3639 D.getContext() == Declarator::AliasDeclContext ||
3640 D.getContext() == Declarator::AliasTemplateContext;
3642 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3643 bool IsQualifiedFunction = T->isFunctionProtoType() &&
3644 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3645 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3647 // If T is 'decltype(auto)', the only declarators we can have are parens
3648 // and at most one function declarator if this is a function declaration.
3649 // If T is a deduced class template specialization type, we can have no
3650 // declarator chunks at all.
3651 if (auto *DT = T->getAs<DeducedType>()) {
3652 const AutoType *AT = T->getAs<AutoType>();
3653 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
3654 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
3655 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3656 unsigned Index = E - I - 1;
3657 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3658 unsigned DiagId = IsClassTemplateDeduction
3659 ? diag::err_deduced_class_template_compound_type
3660 : diag::err_decltype_auto_compound_type;
3661 unsigned DiagKind = 0;
3662 switch (DeclChunk.Kind) {
3663 case DeclaratorChunk::Paren:
3664 // FIXME: Rejecting this is a little silly.
3665 if (IsClassTemplateDeduction) {
3670 case DeclaratorChunk::Function: {
3671 if (IsClassTemplateDeduction) {
3676 if (D.isFunctionDeclarationContext() &&
3677 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3679 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3682 case DeclaratorChunk::Pointer:
3683 case DeclaratorChunk::BlockPointer:
3684 case DeclaratorChunk::MemberPointer:
3687 case DeclaratorChunk::Reference:
3690 case DeclaratorChunk::Array:
3693 case DeclaratorChunk::Pipe:
3697 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3698 D.setInvalidType(true);
3704 // Determine whether we should infer _Nonnull on pointer types.
3705 Optional<NullabilityKind> inferNullability;
3706 bool inferNullabilityCS = false;
3707 bool inferNullabilityInnerOnly = false;
3708 bool inferNullabilityInnerOnlyComplete = false;
3710 // Are we in an assume-nonnull region?
3711 bool inAssumeNonNullRegion = false;
3712 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
3713 if (assumeNonNullLoc.isValid()) {
3714 inAssumeNonNullRegion = true;
3715 recordNullabilitySeen(S, assumeNonNullLoc);
3718 // Whether to complain about missing nullability specifiers or not.
3722 /// Complain on the inner pointers (but not the outermost
3725 /// Complain about any pointers that don't have nullability
3726 /// specified or inferred.
3728 } complainAboutMissingNullability = CAMN_No;
3729 unsigned NumPointersRemaining = 0;
3730 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
3732 if (IsTypedefName) {
3733 // For typedefs, we do not infer any nullability (the default),
3734 // and we only complain about missing nullability specifiers on
3736 complainAboutMissingNullability = CAMN_InnerPointers;
3738 auto isDependentNonPointerType = [](QualType T) -> bool {
3739 // Note: This is intended to be the same check as Type::canHaveNullability
3740 // except with all of the ambiguous cases being treated as 'false' rather
3742 return T->isDependentType() && !T->isAnyPointerType() &&
3743 !T->isBlockPointerType() && !T->isMemberPointerType();
3746 if (T->canHaveNullability() && !T->getNullability(S.Context) &&
3747 !isDependentNonPointerType(T)) {
3748 // Note that we allow but don't require nullability on dependent types.
3749 ++NumPointersRemaining;
3752 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3753 DeclaratorChunk &chunk = D.getTypeObject(i);
3754 switch (chunk.Kind) {
3755 case DeclaratorChunk::Array:
3756 case DeclaratorChunk::Function:
3757 case DeclaratorChunk::Pipe:
3760 case DeclaratorChunk::BlockPointer:
3761 case DeclaratorChunk::MemberPointer:
3762 ++NumPointersRemaining;
3765 case DeclaratorChunk::Paren:
3766 case DeclaratorChunk::Reference:
3769 case DeclaratorChunk::Pointer:
3770 ++NumPointersRemaining;
3775 bool isFunctionOrMethod = false;
3776 switch (auto context = state.getDeclarator().getContext()) {
3777 case Declarator::ObjCParameterContext:
3778 case Declarator::ObjCResultContext:
3779 case Declarator::PrototypeContext:
3780 case Declarator::TrailingReturnContext:
3781 isFunctionOrMethod = true;
3784 case Declarator::MemberContext:
3785 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3786 complainAboutMissingNullability = CAMN_No;
3790 // Weak properties are inferred to be nullable.
3791 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
3792 inferNullability = NullabilityKind::Nullable;
3798 case Declarator::FileContext:
3799 case Declarator::KNRTypeListContext: {
3800 complainAboutMissingNullability = CAMN_Yes;
3802 // Nullability inference depends on the type and declarator.
3803 auto wrappingKind = PointerWrappingDeclaratorKind::None;
3804 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
3805 case PointerDeclaratorKind::NonPointer:
3806 case PointerDeclaratorKind::MultiLevelPointer:
3807 // Cannot infer nullability.
3810 case PointerDeclaratorKind::SingleLevelPointer:
3811 // Infer _Nonnull if we are in an assumes-nonnull region.
3812 if (inAssumeNonNullRegion) {
3813 complainAboutInferringWithinChunk = wrappingKind;
3814 inferNullability = NullabilityKind::NonNull;
3815 inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3816 context == Declarator::ObjCResultContext);
3820 case PointerDeclaratorKind::CFErrorRefPointer:
3821 case PointerDeclaratorKind::NSErrorPointerPointer:
3822 // Within a function or method signature, infer _Nullable at both
3824 if (isFunctionOrMethod && inAssumeNonNullRegion)
3825 inferNullability = NullabilityKind::Nullable;
3828 case PointerDeclaratorKind::MaybePointerToCFRef:
3829 if (isFunctionOrMethod) {
3830 // On pointer-to-pointer parameters marked cf_returns_retained or
3831 // cf_returns_not_retained, if the outer pointer is explicit then
3832 // infer the inner pointer as _Nullable.
3833 auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3835 if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3836 NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3838 NextAttr = NextAttr->getNext();
3842 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3843 if (hasCFReturnsAttr(D.getAttributes()) ||
3844 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3845 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3846 inferNullability = NullabilityKind::Nullable;
3847 inferNullabilityInnerOnly = true;
3856 case Declarator::ConversionIdContext:
3857 complainAboutMissingNullability = CAMN_Yes;
3860 case Declarator::AliasDeclContext:
3861 case Declarator::AliasTemplateContext:
3862 case Declarator::BlockContext:
3863 case Declarator::BlockLiteralContext:
3864 case Declarator::ConditionContext:
3865 case Declarator::CXXCatchContext:
3866 case Declarator::CXXNewContext:
3867 case Declarator::ForContext:
3868 case Declarator::InitStmtContext:
3869 case Declarator::LambdaExprContext:
3870 case Declarator::LambdaExprParameterContext:
3871 case Declarator::ObjCCatchContext:
3872 case Declarator::TemplateParamContext:
3873 case Declarator::TemplateTypeArgContext:
3874 case Declarator::TypeNameContext:
3875 case Declarator::FunctionalCastContext:
3876 // Don't infer in these contexts.
3881 // Local function that returns true if its argument looks like a va_list.
3882 auto isVaList = [&S](QualType T) -> bool {
3883 auto *typedefTy = T->getAs<TypedefType>();
3886 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
3888 if (typedefTy->getDecl() == vaListTypedef)
3890 if (auto *name = typedefTy->getDecl()->getIdentifier())
3891 if (name->isStr("va_list"))
3893 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
3894 } while (typedefTy);
3898 // Local function that checks the nullability for a given pointer declarator.
3899 // Returns true if _Nonnull was inferred.
3900 auto inferPointerNullability = [&](SimplePointerKind pointerKind,
3901 SourceLocation pointerLoc,
3902 AttributeList *&attrs) -> AttributeList * {
3903 // We've seen a pointer.
3904 if (NumPointersRemaining > 0)
3905 --NumPointersRemaining;
3907 // If a nullability attribute is present, there's nothing to do.
3908 if (hasNullabilityAttr(attrs))
3911 // If we're supposed to infer nullability, do so now.
3912 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3913 AttributeList::Syntax syntax
3914 = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3915 : AttributeList::AS_Keyword;
3916 AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3918 S.getNullabilityKeyword(
3920 SourceRange(pointerLoc),
3921 nullptr, SourceLocation(),
3922 nullptr, 0, syntax);
3924 spliceAttrIntoList(*nullabilityAttr, attrs);
3926 if (inferNullabilityCS) {
3927 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
3928 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
3931 if (pointerLoc.isValid() &&
3932 complainAboutInferringWithinChunk !=
3933 PointerWrappingDeclaratorKind::None) {
3935 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
3936 Diag << static_cast<int>(complainAboutInferringWithinChunk);
3937 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
3940 if (inferNullabilityInnerOnly)
3941 inferNullabilityInnerOnlyComplete = true;
3942 return nullabilityAttr;
3945 // If we're supposed to complain about missing nullability, do so
3946 // now if it's truly missing.
3947 switch (complainAboutMissingNullability) {
3951 case CAMN_InnerPointers:
3952 if (NumPointersRemaining == 0)
3957 checkNullabilityConsistency(S, pointerKind, pointerLoc);
3962 // If the type itself could have nullability but does not, infer pointer
3963 // nullability and perform consistency checking.
3964 if (S.CodeSynthesisContexts.empty()) {
3965 if (T->canHaveNullability() && !T->getNullability(S.Context)) {
3967 // Record that we've seen a pointer, but do nothing else.
3968 if (NumPointersRemaining > 0)
3969 --NumPointersRemaining;
3971 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
3972 if (T->isBlockPointerType())
3973 pointerKind = SimplePointerKind::BlockPointer;
3974 else if (T->isMemberPointerType())
3975 pointerKind = SimplePointerKind::MemberPointer;
3977 if (auto *attr = inferPointerNullability(
3978 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3979 D.getMutableDeclSpec().getAttributes().getListRef())) {
3980 T = Context.getAttributedType(
3981 AttributedType::getNullabilityAttrKind(*inferNullability),T,T);
3982 attr->setUsedAsTypeAttr();
3987 if (complainAboutMissingNullability == CAMN_Yes &&
3988 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
3989 D.isPrototypeContext() &&
3990 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
3991 checkNullabilityConsistency(S, SimplePointerKind::Array,
3992 D.getDeclSpec().getTypeSpecTypeLoc());
3996 // Walk the DeclTypeInfo, building the recursive type as we go.
3997 // DeclTypeInfos are ordered from the identifier out, which is
3998 // opposite of what we want :).
3999 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4000 unsigned chunkIndex = e - i - 1;
4001 state.setCurrentChunkIndex(chunkIndex);
4002 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4003 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4004 switch (DeclType.Kind) {
4005 case DeclaratorChunk::Paren:
4006 T = S.BuildParenType(T);
4008 case DeclaratorChunk::BlockPointer:
4009 // If blocks are disabled, emit an error.
4010 if (!LangOpts.Blocks)
4011 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4013 // Handle pointer nullability.
4014 inferPointerNullability(SimplePointerKind::BlockPointer,
4015 DeclType.Loc, DeclType.getAttrListRef());
4017 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4018 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4019 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4020 // qualified with const.
4021 if (LangOpts.OpenCL)
4022 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4023 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4026 case DeclaratorChunk::Pointer:
4027 // Verify that we're not building a pointer to pointer to function with
4028 // exception specification.
4029 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4030 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4031 D.setInvalidType(true);
4032 // Build the type anyway.
4035 // Handle pointer nullability
4036 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4037 DeclType.getAttrListRef());
4039 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
4040 T = Context.getObjCObjectPointerType(T);
4041 if (DeclType.Ptr.TypeQuals)
4042 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4046 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4047 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4048 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4049 if (LangOpts.OpenCL) {
4050 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4051 T->isBlockPointerType()) {
4052 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4053 D.setInvalidType(true);
4057 T = S.BuildPointerType(T, DeclType.Loc, Name);
4058 if (DeclType.Ptr.TypeQuals)
4059 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4061 case DeclaratorChunk::Reference: {
4062 // Verify that we're not building a reference to pointer to function with
4063 // exception specification.
4064 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4065 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4066 D.setInvalidType(true);
4067 // Build the type anyway.
4069 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4071 if (DeclType.Ref.HasRestrict)
4072 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4075 case DeclaratorChunk::Array: {
4076 // Verify that we're not building an array of pointers to function with
4077 // exception specification.
4078 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4079 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4080 D.setInvalidType(true);
4081 // Build the type anyway.
4083 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4084 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4085 ArrayType::ArraySizeModifier ASM;
4087 ASM = ArrayType::Star;
4088 else if (ATI.hasStatic)
4089 ASM = ArrayType::Static;
4091 ASM = ArrayType::Normal;
4092 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4093 // FIXME: This check isn't quite right: it allows star in prototypes
4094 // for function definitions, and disallows some edge cases detailed
4095 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4096 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4097 ASM = ArrayType::Normal;
4098 D.setInvalidType(true);
4101 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4102 // shall appear only in a declaration of a function parameter with an
4104 if (ASM == ArrayType::Static || ATI.TypeQuals) {
4105 if (!(D.isPrototypeContext() ||
4106 D.getContext() == Declarator::KNRTypeListContext)) {
4107 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4108 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4109 // Remove the 'static' and the type qualifiers.
4110 if (ASM == ArrayType::Static)
4111 ASM = ArrayType::Normal;
4113 D.setInvalidType(true);
4116 // C99 6.7.5.2p1: ... and then only in the outermost array type
4118 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4119 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4120 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4121 if (ASM == ArrayType::Static)
4122 ASM = ArrayType::Normal;
4124 D.setInvalidType(true);
4127 const AutoType *AT = T->getContainedAutoType();
4128 // Allow arrays of auto if we are a generic lambda parameter.
4129 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4130 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
4131 // We've already diagnosed this for decltype(auto).
4132 if (!AT->isDecltypeAuto())
4133 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4134 << getPrintableNameForEntity(Name) << T;
4139 // Array parameters can be marked nullable as well, although it's not
4140 // necessary if they're marked 'static'.
4141 if (complainAboutMissingNullability == CAMN_Yes &&
4142 !hasNullabilityAttr(DeclType.getAttrs()) &&
4143 ASM != ArrayType::Static &&
4144 D.isPrototypeContext() &&
4145 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4146 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4149 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4150 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4153 case DeclaratorChunk::Function: {
4154 // If the function declarator has a prototype (i.e. it is not () and
4155 // does not have a K&R-style identifier list), then the arguments are part
4156 // of the type, otherwise the argument list is ().
4157 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4158 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
4160 // Check for auto functions and trailing return type and adjust the
4161 // return type accordingly.
4162 if (!D.isInvalidType()) {
4163 // trailing-return-type is only required if we're declaring a function,
4164 // and not, for instance, a pointer to a function.
4165 if (D.getDeclSpec().hasAutoTypeSpec() &&
4166 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
4167 !S.getLangOpts().CPlusPlus14) {
4168 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4169 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4170 ? diag::err_auto_missing_trailing_return
4171 : diag::err_deduced_return_type);
4173 D.setInvalidType(true);
4174 } else if (FTI.hasTrailingReturnType()) {
4175 // T must be exactly 'auto' at this point. See CWG issue 681.
4176 if (isa<ParenType>(T)) {
4177 S.Diag(D.getLocStart(),
4178 diag::err_trailing_return_in_parens)
4179 << T << D.getSourceRange();
4180 D.setInvalidType(true);
4181 } else if (D.getName().getKind() ==
4182 UnqualifiedId::IK_DeductionGuideName) {
4183 if (T != Context.DependentTy) {
4184 S.Diag(D.getDeclSpec().getLocStart(),
4185 diag::err_deduction_guide_with_complex_decl)
4186 << D.getSourceRange();
4187 D.setInvalidType(true);
4189 } else if (D.getContext() != Declarator::LambdaExprContext &&
4190 (T.hasQualifiers() || !isa<AutoType>(T) ||
4191 cast<AutoType>(T)->getKeyword() !=
4192 AutoTypeKeyword::Auto)) {
4193 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4194 diag::err_trailing_return_without_auto)
4195 << T << D.getDeclSpec().getSourceRange();
4196 D.setInvalidType(true);
4198 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4200 // An error occurred parsing the trailing return type.
4202 D.setInvalidType(true);
4207 // C99 6.7.5.3p1: The return type may not be a function or array type.
4208 // For conversion functions, we'll diagnose this particular error later.
4209 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4210 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
4211 unsigned diagID = diag::err_func_returning_array_function;
4212 // Last processing chunk in block context means this function chunk
4213 // represents the block.
4214 if (chunkIndex == 0 &&
4215 D.getContext() == Declarator::BlockLiteralContext)
4216 diagID = diag::err_block_returning_array_function;
4217 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4219 D.setInvalidType(true);
4222 // Do not allow returning half FP value.
4223 // FIXME: This really should be in BuildFunctionType.
4224 if (T->isHalfType()) {
4225 if (S.getLangOpts().OpenCL) {
4226 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4227 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4228 << T << 0 /*pointer hint*/;
4229 D.setInvalidType(true);
4231 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4232 S.Diag(D.getIdentifierLoc(),
4233 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4234 D.setInvalidType(true);
4238 if (LangOpts.OpenCL) {
4239 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4241 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4243 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4244 << T << 1 /*hint off*/;
4245 D.setInvalidType(true);
4247 // OpenCL doesn't support variadic functions and blocks
4248 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4249 // We also allow here any toolchain reserved identifiers.
4250 if (FTI.isVariadic &&
4251 !(D.getIdentifier() &&
4252 ((D.getIdentifier()->getName() == "printf" &&
4253 LangOpts.OpenCLVersion >= 120) ||
4254 D.getIdentifier()->getName().startswith("__")))) {
4255 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4256 D.setInvalidType(true);
4260 // Methods cannot return interface types. All ObjC objects are
4261 // passed by reference.
4262 if (T->isObjCObjectType()) {
4263 SourceLocation DiagLoc, FixitLoc;
4265 DiagLoc = TInfo->getTypeLoc().getLocStart();
4266 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
4268 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4269 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
4271 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4273 << FixItHint::CreateInsertion(FixitLoc, "*");
4275 T = Context.getObjCObjectPointerType(T);
4278 TLB.pushFullCopy(TInfo->getTypeLoc());
4279 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4280 TLoc.setStarLoc(FixitLoc);
4281 TInfo = TLB.getTypeSourceInfo(Context, T);
4284 D.setInvalidType(true);
4287 // cv-qualifiers on return types are pointless except when the type is a
4288 // class type in C++.
4289 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4290 !(S.getLangOpts().CPlusPlus &&
4291 (T->isDependentType() || T->isRecordType()))) {
4292 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4293 D.getFunctionDefinitionKind() == FDK_Definition) {
4294 // [6.9.1/3] qualified void return is invalid on a C
4295 // function definition. Apparently ok on declarations and
4296 // in C++ though (!)
4297 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4299 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4302 // Objective-C ARC ownership qualifiers are ignored on the function
4303 // return type (by type canonicalization). Complain if this attribute
4304 // was written here.
4305 if (T.getQualifiers().hasObjCLifetime()) {
4306 SourceLocation AttrLoc;
4307 if (chunkIndex + 1 < D.getNumTypeObjects()) {
4308 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4309 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
4310 Attr; Attr = Attr->getNext()) {
4311 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4312 AttrLoc = Attr->getLoc();
4317 if (AttrLoc.isInvalid()) {
4318 for (const AttributeList *Attr
4319 = D.getDeclSpec().getAttributes().getList();
4320 Attr; Attr = Attr->getNext()) {
4321 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4322 AttrLoc = Attr->getLoc();
4328 if (AttrLoc.isValid()) {
4329 // The ownership attributes are almost always written via
4331 // __strong/__weak/__autoreleasing/__unsafe_unretained.
4332 if (AttrLoc.isMacroID())
4333 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
4335 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4336 << T.getQualifiers().getObjCLifetime();
4340 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4342 // Types shall not be defined in return or parameter types.
4343 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4344 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4345 << Context.getTypeDeclType(Tag);
4348 // Exception specs are not allowed in typedefs. Complain, but add it
4350 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus1z)
4351 S.Diag(FTI.getExceptionSpecLocBeg(),
4352 diag::err_exception_spec_in_typedef)
4353 << (D.getContext() == Declarator::AliasDeclContext ||
4354 D.getContext() == Declarator::AliasTemplateContext);
4356 // If we see "T var();" or "T var(T());" at block scope, it is probably
4357 // an attempt to initialize a variable, not a function declaration.
4358 if (FTI.isAmbiguous)
4359 warnAboutAmbiguousFunction(S, D, DeclType, T);
4361 // GNU warning -Wstrict-prototypes
4362 // Warn if a function declaration is without a prototype.
4363 // This warning is issued for all kinds of unprototyped function
4364 // declarations (i.e. function type typedef, function pointer etc.)
4366 // The empty list in a function declarator that is not part of a
4367 // definition of that function specifies that no information
4368 // about the number or types of the parameters is supplied.
4369 if (D.getFunctionDefinitionKind() == FDK_Declaration &&
4370 FTI.NumParams == 0 && !LangOpts.CPlusPlus)
4371 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
4372 << 0 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
4374 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
4376 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
4377 // Simple void foo(), where the incoming T is the result type.
4378 T = Context.getFunctionNoProtoType(T, EI);
4380 // We allow a zero-parameter variadic function in C if the
4381 // function is marked with the "overloadable" attribute. Scan
4382 // for this attribute now.
4383 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
4384 bool Overloadable = false;
4385 for (const AttributeList *Attrs = D.getAttributes();
4386 Attrs; Attrs = Attrs->getNext()) {
4387 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
4388 Overloadable = true;
4394 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4397 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4398 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4400 S.Diag(FTI.Params[0].IdentLoc,
4401 diag::err_ident_list_in_fn_declaration);
4402 D.setInvalidType(true);
4403 // Recover by creating a K&R-style function type.
4404 T = Context.getFunctionNoProtoType(T, EI);
4408 FunctionProtoType::ExtProtoInfo EPI;
4410 EPI.Variadic = FTI.isVariadic;
4411 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
4412 EPI.TypeQuals = FTI.TypeQuals;
4413 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4414 : FTI.RefQualifierIsLValueRef? RQ_LValue
4417 // Otherwise, we have a function with a parameter list that is
4418 // potentially variadic.
4419 SmallVector<QualType, 16> ParamTys;
4420 ParamTys.reserve(FTI.NumParams);
4422 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
4423 ExtParameterInfos(FTI.NumParams);
4424 bool HasAnyInterestingExtParameterInfos = false;
4426 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4427 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4428 QualType ParamTy = Param->getType();
4429 assert(!ParamTy.isNull() && "Couldn't parse type?");
4431 // Look for 'void'. void is allowed only as a single parameter to a
4432 // function with no other parameters (C99 6.7.5.3p10). We record
4433 // int(void) as a FunctionProtoType with an empty parameter list.
4434 if (ParamTy->isVoidType()) {
4435 // If this is something like 'float(int, void)', reject it. 'void'
4436 // is an incomplete type (C99 6.2.5p19) and function decls cannot
4437 // have parameters of incomplete type.
4438 if (FTI.NumParams != 1 || FTI.isVariadic) {
4439 S.Diag(DeclType.Loc, diag::err_void_only_param);
4440 ParamTy = Context.IntTy;
4441 Param->setType(ParamTy);
4442 } else if (FTI.Params[i].Ident) {
4443 // Reject, but continue to parse 'int(void abc)'.
4444 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4445 ParamTy = Context.IntTy;
4446 Param->setType(ParamTy);
4448 // Reject, but continue to parse 'float(const void)'.
4449 if (ParamTy.hasQualifiers())
4450 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4452 // Do not add 'void' to the list.
4455 } else if (ParamTy->isHalfType()) {
4456 // Disallow half FP parameters.
4457 // FIXME: This really should be in BuildFunctionType.
4458 if (S.getLangOpts().OpenCL) {
4459 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4460 S.Diag(Param->getLocation(),
4461 diag::err_opencl_half_param) << ParamTy;
4463 Param->setInvalidDecl();
4465 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4466 S.Diag(Param->getLocation(),
4467 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4470 } else if (!FTI.hasPrototype) {
4471 if (ParamTy->isPromotableIntegerType()) {
4472 ParamTy = Context.getPromotedIntegerType(ParamTy);
4473 Param->setKNRPromoted(true);
4474 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4475 if (BTy->getKind() == BuiltinType::Float) {
4476 ParamTy = Context.DoubleTy;
4477 Param->setKNRPromoted(true);
4482 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4483 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4484 HasAnyInterestingExtParameterInfos = true;
4487 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4488 ExtParameterInfos[i] =
4489 ExtParameterInfos[i].withABI(attr->getABI());
4490 HasAnyInterestingExtParameterInfos = true;
4493 if (Param->hasAttr<PassObjectSizeAttr>()) {
4494 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
4495 HasAnyInterestingExtParameterInfos = true;
4498 ParamTys.push_back(ParamTy);
4501 if (HasAnyInterestingExtParameterInfos) {
4502 EPI.ExtParameterInfos = ExtParameterInfos.data();
4503 checkExtParameterInfos(S, ParamTys, EPI,
4504 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4507 SmallVector<QualType, 4> Exceptions;
4508 SmallVector<ParsedType, 2> DynamicExceptions;
4509 SmallVector<SourceRange, 2> DynamicExceptionRanges;
4510 Expr *NoexceptExpr = nullptr;
4512 if (FTI.getExceptionSpecType() == EST_Dynamic) {
4513 // FIXME: It's rather inefficient to have to split into two vectors
4515 unsigned N = FTI.getNumExceptions();
4516 DynamicExceptions.reserve(N);
4517 DynamicExceptionRanges.reserve(N);
4518 for (unsigned I = 0; I != N; ++I) {
4519 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4520 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4522 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
4523 NoexceptExpr = FTI.NoexceptExpr;
4526 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4527 FTI.getExceptionSpecType(),
4529 DynamicExceptionRanges,
4534 T = Context.getFunctionType(T, ParamTys, EPI);
4538 case DeclaratorChunk::MemberPointer: {
4539 // The scope spec must refer to a class, or be dependent.
4540 CXXScopeSpec &SS = DeclType.Mem.Scope();
4543 // Handle pointer nullability.
4544 inferPointerNullability(SimplePointerKind::MemberPointer,
4545 DeclType.Loc, DeclType.getAttrListRef());
4547 if (SS.isInvalid()) {
4548 // Avoid emitting extra errors if we already errored on the scope.
4549 D.setInvalidType(true);
4550 } else if (S.isDependentScopeSpecifier(SS) ||
4551 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4552 NestedNameSpecifier *NNS = SS.getScopeRep();
4553 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4554 switch (NNS->getKind()) {
4555 case NestedNameSpecifier::Identifier:
4556 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4557 NNS->getAsIdentifier());
4560 case NestedNameSpecifier::Namespace:
4561 case NestedNameSpecifier::NamespaceAlias:
4562 case NestedNameSpecifier::Global:
4563 case NestedNameSpecifier::Super:
4564 llvm_unreachable("Nested-name-specifier must name a type");
4566 case NestedNameSpecifier::TypeSpec:
4567 case NestedNameSpecifier::TypeSpecWithTemplate:
4568 ClsType = QualType(NNS->getAsType(), 0);
4569 // Note: if the NNS has a prefix and ClsType is a nondependent
4570 // TemplateSpecializationType, then the NNS prefix is NOT included
4571 // in ClsType; hence we wrap ClsType into an ElaboratedType.
4572 // NOTE: in particular, no wrap occurs if ClsType already is an
4573 // Elaborated, DependentName, or DependentTemplateSpecialization.
4574 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4575 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4579 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4580 diag::err_illegal_decl_mempointer_in_nonclass)
4581 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4582 << DeclType.Mem.Scope().getRange();
4583 D.setInvalidType(true);
4586 if (!ClsType.isNull())
4587 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4591 D.setInvalidType(true);
4592 } else if (DeclType.Mem.TypeQuals) {
4593 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4598 case DeclaratorChunk::Pipe: {
4599 T = S.BuildReadPipeType(T, DeclType.Loc);
4600 processTypeAttrs(state, T, TAL_DeclSpec,
4601 D.getDeclSpec().getAttributes().getList());
4607 D.setInvalidType(true);
4611 // See if there are any attributes on this declarator chunk.
4612 processTypeAttrs(state, T, TAL_DeclChunk,
4613 const_cast<AttributeList *>(DeclType.getAttrs()));
4616 assert(!T.isNull() && "T must not be null after this point");
4618 if (LangOpts.CPlusPlus && T->isFunctionType()) {
4619 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4620 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4623 // A cv-qualifier-seq shall only be part of the function type
4624 // for a nonstatic member function, the function type to which a pointer
4625 // to member refers, or the top-level function type of a function typedef
4628 // Core issue 547 also allows cv-qualifiers on function types that are
4629 // top-level template type arguments.
4630 enum { NonMember, Member, DeductionGuide } Kind = NonMember;
4631 if (D.getName().getKind() == UnqualifiedId::IK_DeductionGuideName)
4632 Kind = DeductionGuide;
4633 else if (!D.getCXXScopeSpec().isSet()) {
4634 if ((D.getContext() == Declarator::MemberContext ||
4635 D.getContext() == Declarator::LambdaExprContext) &&
4636 !D.getDeclSpec().isFriendSpecified())
4639 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4640 if (!DC || DC->isRecord())
4644 // C++11 [dcl.fct]p6 (w/DR1417):
4645 // An attempt to specify a function type with a cv-qualifier-seq or a
4646 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4647 // - the function type for a non-static member function,
4648 // - the function type to which a pointer to member refers,
4649 // - the top-level function type of a function typedef declaration or
4650 // alias-declaration,
4651 // - the type-id in the default argument of a type-parameter, or
4652 // - the type-id of a template-argument for a type-parameter
4654 // FIXME: Checking this here is insufficient. We accept-invalid on:
4656 // template<typename T> struct S { void f(T); };
4657 // S<int() const> s;
4659 // ... for instance.
4660 if (IsQualifiedFunction &&
4662 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4664 D.getContext() != Declarator::TemplateTypeArgContext) {
4665 SourceLocation Loc = D.getLocStart();
4666 SourceRange RemovalRange;
4668 if (D.isFunctionDeclarator(I)) {
4669 SmallVector<SourceLocation, 4> RemovalLocs;
4670 const DeclaratorChunk &Chunk = D.getTypeObject(I);
4671 assert(Chunk.Kind == DeclaratorChunk::Function);
4672 if (Chunk.Fun.hasRefQualifier())
4673 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4674 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4675 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4676 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4677 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4678 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4679 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4680 if (!RemovalLocs.empty()) {
4681 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
4682 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4683 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4684 Loc = RemovalLocs.front();
4688 S.Diag(Loc, diag::err_invalid_qualified_function_type)
4689 << Kind << D.isFunctionDeclarator() << T
4690 << getFunctionQualifiersAsString(FnTy)
4691 << FixItHint::CreateRemoval(RemovalRange);
4693 // Strip the cv-qualifiers and ref-qualifiers from the type.
4694 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4696 EPI.RefQualifier = RQ_None;
4698 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4700 // Rebuild any parens around the identifier in the function type.
4701 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4702 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4704 T = S.BuildParenType(T);
4709 // Apply any undistributed attributes from the declarator.
4710 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
4712 // Diagnose any ignored type attributes.
4713 state.diagnoseIgnoredTypeAttrs(T);
4715 // C++0x [dcl.constexpr]p9:
4716 // A constexpr specifier used in an object declaration declares the object
4718 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4722 // If there was an ellipsis in the declarator, the declaration declares a
4723 // parameter pack whose type may be a pack expansion type.
4724 if (D.hasEllipsis()) {
4725 // C++0x [dcl.fct]p13:
4726 // A declarator-id or abstract-declarator containing an ellipsis shall
4727 // only be used in a parameter-declaration. Such a parameter-declaration
4728 // is a parameter pack (14.5.3). [...]
4729 switch (D.getContext()) {
4730 case Declarator::PrototypeContext:
4731 case Declarator::LambdaExprParameterContext:
4732 // C++0x [dcl.fct]p13:
4733 // [...] When it is part of a parameter-declaration-clause, the
4734 // parameter pack is a function parameter pack (14.5.3). The type T
4735 // of the declarator-id of the function parameter pack shall contain
4736 // a template parameter pack; each template parameter pack in T is
4737 // expanded by the function parameter pack.
4739 // We represent function parameter packs as function parameters whose
4740 // type is a pack expansion.
4741 if (!T->containsUnexpandedParameterPack()) {
4742 S.Diag(D.getEllipsisLoc(),
4743 diag::err_function_parameter_pack_without_parameter_packs)
4744 << T << D.getSourceRange();
4745 D.setEllipsisLoc(SourceLocation());
4747 T = Context.getPackExpansionType(T, None);
4750 case Declarator::TemplateParamContext:
4751 // C++0x [temp.param]p15:
4752 // If a template-parameter is a [...] is a parameter-declaration that
4753 // declares a parameter pack (8.3.5), then the template-parameter is a
4754 // template parameter pack (14.5.3).
4756 // Note: core issue 778 clarifies that, if there are any unexpanded
4757 // parameter packs in the type of the non-type template parameter, then
4758 // it expands those parameter packs.
4759 if (T->containsUnexpandedParameterPack())
4760 T = Context.getPackExpansionType(T, None);
4762 S.Diag(D.getEllipsisLoc(),
4763 LangOpts.CPlusPlus11
4764 ? diag::warn_cxx98_compat_variadic_templates
4765 : diag::ext_variadic_templates);
4768 case Declarator::FileContext:
4769 case Declarator::KNRTypeListContext:
4770 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
4771 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
4772 case Declarator::TypeNameContext:
4773 case Declarator::FunctionalCastContext:
4774 case Declarator::CXXNewContext:
4775 case Declarator::AliasDeclContext:
4776 case Declarator::AliasTemplateContext:
4777 case Declarator::MemberContext:
4778 case Declarator::BlockContext:
4779 case Declarator::ForContext:
4780 case Declarator::InitStmtContext:
4781 case Declarator::ConditionContext:
4782 case Declarator::CXXCatchContext:
4783 case Declarator::ObjCCatchContext:
4784 case Declarator::BlockLiteralContext:
4785 case Declarator::LambdaExprContext:
4786 case Declarator::ConversionIdContext:
4787 case Declarator::TrailingReturnContext:
4788 case Declarator::TemplateTypeArgContext:
4789 // FIXME: We may want to allow parameter packs in block-literal contexts
4791 S.Diag(D.getEllipsisLoc(),
4792 diag::err_ellipsis_in_declarator_not_parameter);
4793 D.setEllipsisLoc(SourceLocation());
4798 assert(!T.isNull() && "T must not be null at the end of this function");
4799 if (D.isInvalidType())
4800 return Context.getTrivialTypeSourceInfo(T);
4802 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
4805 /// GetTypeForDeclarator - Convert the type for the specified
4806 /// declarator to Type instances.
4808 /// The result of this call will never be null, but the associated
4809 /// type may be a null type if there's an unrecoverable error.
4810 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
4811 // Determine the type of the declarator. Not all forms of declarator
4814 TypeProcessingState state(*this, D);
4816 TypeSourceInfo *ReturnTypeInfo = nullptr;
4817 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4819 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
4820 inferARCWriteback(state, T);
4822 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
4825 static void transferARCOwnershipToDeclSpec(Sema &S,
4826 QualType &declSpecTy,
4827 Qualifiers::ObjCLifetime ownership) {
4828 if (declSpecTy->isObjCRetainableType() &&
4829 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
4831 qs.addObjCLifetime(ownership);
4832 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
4836 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
4837 Qualifiers::ObjCLifetime ownership,
4838 unsigned chunkIndex) {
4839 Sema &S = state.getSema();
4840 Declarator &D = state.getDeclarator();
4842 // Look for an explicit lifetime attribute.
4843 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
4844 for (const AttributeList *attr = chunk.getAttrs(); attr;
4845 attr = attr->getNext())
4846 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
4849 const char *attrStr = nullptr;
4850 switch (ownership) {
4851 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
4852 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
4853 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
4854 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
4855 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
4858 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
4859 Arg->Ident = &S.Context.Idents.get(attrStr);
4860 Arg->Loc = SourceLocation();
4862 ArgsUnion Args(Arg);
4864 // If there wasn't one, add one (with an invalid source location
4865 // so that we don't make an AttributedType for it).
4866 AttributeList *attr = D.getAttributePool()
4867 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
4868 /*scope*/ nullptr, SourceLocation(),
4869 /*args*/ &Args, 1, AttributeList::AS_GNU);
4870 spliceAttrIntoList(*attr, chunk.getAttrListRef());
4872 // TODO: mark whether we did this inference?
4875 /// \brief Used for transferring ownership in casts resulting in l-values.
4876 static void transferARCOwnership(TypeProcessingState &state,
4877 QualType &declSpecTy,
4878 Qualifiers::ObjCLifetime ownership) {
4879 Sema &S = state.getSema();
4880 Declarator &D = state.getDeclarator();
4883 bool hasIndirection = false;
4884 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4885 DeclaratorChunk &chunk = D.getTypeObject(i);
4886 switch (chunk.Kind) {
4887 case DeclaratorChunk::Paren:
4891 case DeclaratorChunk::Array:
4892 case DeclaratorChunk::Reference:
4893 case DeclaratorChunk::Pointer:
4895 hasIndirection = true;
4899 case DeclaratorChunk::BlockPointer:
4901 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
4904 case DeclaratorChunk::Function:
4905 case DeclaratorChunk::MemberPointer:
4906 case DeclaratorChunk::Pipe:
4914 DeclaratorChunk &chunk = D.getTypeObject(inner);
4915 if (chunk.Kind == DeclaratorChunk::Pointer) {
4916 if (declSpecTy->isObjCRetainableType())
4917 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4918 if (declSpecTy->isObjCObjectType() && hasIndirection)
4919 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
4921 assert(chunk.Kind == DeclaratorChunk::Array ||
4922 chunk.Kind == DeclaratorChunk::Reference);
4923 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4927 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
4928 TypeProcessingState state(*this, D);
4930 TypeSourceInfo *ReturnTypeInfo = nullptr;
4931 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4933 if (getLangOpts().ObjC1) {
4934 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
4935 if (ownership != Qualifiers::OCL_None)
4936 transferARCOwnership(state, declSpecTy, ownership);
4939 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4942 /// Map an AttributedType::Kind to an AttributeList::Kind.
4943 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
4945 case AttributedType::attr_address_space:
4946 return AttributeList::AT_AddressSpace;
4947 case AttributedType::attr_regparm:
4948 return AttributeList::AT_Regparm;
4949 case AttributedType::attr_vector_size:
4950 return AttributeList::AT_VectorSize;
4951 case AttributedType::attr_neon_vector_type:
4952 return AttributeList::AT_NeonVectorType;
4953 case AttributedType::attr_neon_polyvector_type:
4954 return AttributeList::AT_NeonPolyVectorType;
4955 case AttributedType::attr_objc_gc:
4956 return AttributeList::AT_ObjCGC;
4957 case AttributedType::attr_objc_ownership:
4958 case AttributedType::attr_objc_inert_unsafe_unretained:
4959 return AttributeList::AT_ObjCOwnership;
4960 case AttributedType::attr_noreturn:
4961 return AttributeList::AT_NoReturn;
4962 case AttributedType::attr_cdecl:
4963 return AttributeList::AT_CDecl;
4964 case AttributedType::attr_fastcall:
4965 return AttributeList::AT_FastCall;
4966 case AttributedType::attr_stdcall:
4967 return AttributeList::AT_StdCall;
4968 case AttributedType::attr_thiscall:
4969 return AttributeList::AT_ThisCall;
4970 case AttributedType::attr_regcall:
4971 return AttributeList::AT_RegCall;
4972 case AttributedType::attr_pascal:
4973 return AttributeList::AT_Pascal;
4974 case AttributedType::attr_swiftcall:
4975 return AttributeList::AT_SwiftCall;
4976 case AttributedType::attr_vectorcall:
4977 return AttributeList::AT_VectorCall;
4978 case AttributedType::attr_pcs:
4979 case AttributedType::attr_pcs_vfp:
4980 return AttributeList::AT_Pcs;
4981 case AttributedType::attr_inteloclbicc:
4982 return AttributeList::AT_IntelOclBicc;
4983 case AttributedType::attr_ms_abi:
4984 return AttributeList::AT_MSABI;
4985 case AttributedType::attr_sysv_abi:
4986 return AttributeList::AT_SysVABI;
4987 case AttributedType::attr_preserve_most:
4988 return AttributeList::AT_PreserveMost;
4989 case AttributedType::attr_preserve_all:
4990 return AttributeList::AT_PreserveAll;
4991 case AttributedType::attr_ptr32:
4992 return AttributeList::AT_Ptr32;
4993 case AttributedType::attr_ptr64:
4994 return AttributeList::AT_Ptr64;
4995 case AttributedType::attr_sptr:
4996 return AttributeList::AT_SPtr;
4997 case AttributedType::attr_uptr:
4998 return AttributeList::AT_UPtr;
4999 case AttributedType::attr_nonnull:
5000 return AttributeList::AT_TypeNonNull;
5001 case AttributedType::attr_nullable:
5002 return AttributeList::AT_TypeNullable;
5003 case AttributedType::attr_null_unspecified:
5004 return AttributeList::AT_TypeNullUnspecified;
5005 case AttributedType::attr_objc_kindof:
5006 return AttributeList::AT_ObjCKindOf;
5008 llvm_unreachable("unexpected attribute kind!");
5011 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5012 const AttributeList *attrs,
5013 const AttributeList *DeclAttrs = nullptr) {
5014 // DeclAttrs and attrs cannot be both empty.
5015 assert((attrs || DeclAttrs) &&
5016 "no type attributes in the expected location!");
5018 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
5019 // Try to search for an attribute of matching kind in attrs list.
5020 while (attrs && attrs->getKind() != parsedKind)
5021 attrs = attrs->getNext();
5023 // No matching type attribute in attrs list found.
5024 // Try searching through C++11 attributes in the declarator attribute list.
5025 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
5026 DeclAttrs->getKind() != parsedKind))
5027 DeclAttrs = DeclAttrs->getNext();
5031 assert(attrs && "no matching type attribute in expected location!");
5033 TL.setAttrNameLoc(attrs->getLoc());
5034 if (TL.hasAttrExprOperand()) {
5035 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
5036 TL.setAttrExprOperand(attrs->getArgAsExpr(0));
5037 } else if (TL.hasAttrEnumOperand()) {
5038 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
5039 "unexpected attribute operand kind");
5040 if (attrs->isArgIdent(0))
5041 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
5043 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
5046 // FIXME: preserve this information to here.
5047 if (TL.hasAttrOperand())
5048 TL.setAttrOperandParensRange(SourceRange());
5052 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5053 ASTContext &Context;
5057 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
5058 : Context(Context), DS(DS) {}
5060 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5061 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
5062 Visit(TL.getModifiedLoc());
5064 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5065 Visit(TL.getUnqualifiedLoc());
5067 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5068 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5070 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5071 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5072 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5073 // addition field. What we have is good enough for dispay of location
5074 // of 'fixit' on interface name.
5075 TL.setNameEndLoc(DS.getLocEnd());
5077 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5078 TypeSourceInfo *RepTInfo = nullptr;
5079 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5080 TL.copy(RepTInfo->getTypeLoc());
5082 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5083 TypeSourceInfo *RepTInfo = nullptr;
5084 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5085 TL.copy(RepTInfo->getTypeLoc());
5087 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5088 TypeSourceInfo *TInfo = nullptr;
5089 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5091 // If we got no declarator info from previous Sema routines,
5092 // just fill with the typespec loc.
5094 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5098 TypeLoc OldTL = TInfo->getTypeLoc();
5099 if (TInfo->getType()->getAs<ElaboratedType>()) {
5100 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5101 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5102 .castAs<TemplateSpecializationTypeLoc>();
5105 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5106 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
5110 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5111 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
5112 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5113 TL.setParensRange(DS.getTypeofParensRange());
5115 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5116 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
5117 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5118 TL.setParensRange(DS.getTypeofParensRange());
5119 assert(DS.getRepAsType());
5120 TypeSourceInfo *TInfo = nullptr;
5121 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5122 TL.setUnderlyingTInfo(TInfo);
5124 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5125 // FIXME: This holds only because we only have one unary transform.
5126 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
5127 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5128 TL.setParensRange(DS.getTypeofParensRange());
5129 assert(DS.getRepAsType());
5130 TypeSourceInfo *TInfo = nullptr;
5131 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5132 TL.setUnderlyingTInfo(TInfo);
5134 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5135 // By default, use the source location of the type specifier.
5136 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5137 if (TL.needsExtraLocalData()) {
5138 // Set info for the written builtin specifiers.
5139 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5140 // Try to have a meaningful source location.
5141 if (TL.getWrittenSignSpec() != TSS_unspecified)
5142 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5143 if (TL.getWrittenWidthSpec() != TSW_unspecified)
5144 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5147 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5148 ElaboratedTypeKeyword Keyword
5149 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5150 if (DS.getTypeSpecType() == TST_typename) {
5151 TypeSourceInfo *TInfo = nullptr;
5152 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5154 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5158 TL.setElaboratedKeywordLoc(Keyword != ETK_None
5159 ? DS.getTypeSpecTypeLoc()
5160 : SourceLocation());
5161 const CXXScopeSpec& SS = DS.getTypeSpecScope();
5162 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5163 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5165 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5166 assert(DS.getTypeSpecType() == TST_typename);
5167 TypeSourceInfo *TInfo = nullptr;
5168 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5170 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
5172 void VisitDependentTemplateSpecializationTypeLoc(
5173 DependentTemplateSpecializationTypeLoc TL) {
5174 assert(DS.getTypeSpecType() == TST_typename);
5175 TypeSourceInfo *TInfo = nullptr;
5176 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5179 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
5181 void VisitTagTypeLoc(TagTypeLoc TL) {
5182 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
5184 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5185 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
5186 // or an _Atomic qualifier.
5187 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
5188 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5189 TL.setParensRange(DS.getTypeofParensRange());
5191 TypeSourceInfo *TInfo = nullptr;
5192 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5194 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5196 TL.setKWLoc(DS.getAtomicSpecLoc());
5197 // No parens, to indicate this was spelled as an _Atomic qualifier.
5198 TL.setParensRange(SourceRange());
5199 Visit(TL.getValueLoc());
5203 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5204 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5206 TypeSourceInfo *TInfo = nullptr;
5207 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5208 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5211 void VisitTypeLoc(TypeLoc TL) {
5212 // FIXME: add other typespec types and change this to an assert.
5213 TL.initialize(Context, DS.getTypeSpecTypeLoc());
5217 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
5218 ASTContext &Context;
5219 const DeclaratorChunk &Chunk;
5222 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
5223 : Context(Context), Chunk(Chunk) {}
5225 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5226 llvm_unreachable("qualified type locs not expected here!");
5228 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5229 llvm_unreachable("decayed type locs not expected here!");
5232 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5233 fillAttributedTypeLoc(TL, Chunk.getAttrs());
5235 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5238 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5239 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
5240 TL.setCaretLoc(Chunk.Loc);
5242 void VisitPointerTypeLoc(PointerTypeLoc TL) {
5243 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5244 TL.setStarLoc(Chunk.Loc);
5246 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5247 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5248 TL.setStarLoc(Chunk.Loc);
5250 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5251 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
5252 const CXXScopeSpec& SS = Chunk.Mem.Scope();
5253 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
5255 const Type* ClsTy = TL.getClass();
5256 QualType ClsQT = QualType(ClsTy, 0);
5257 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5258 // Now copy source location info into the type loc component.
5259 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5260 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5261 case NestedNameSpecifier::Identifier:
5262 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
5264 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
5265 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
5266 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5267 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5271 case NestedNameSpecifier::TypeSpec:
5272 case NestedNameSpecifier::TypeSpecWithTemplate:
5273 if (isa<ElaboratedType>(ClsTy)) {
5274 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5275 ETLoc.setElaboratedKeywordLoc(SourceLocation());
5276 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5277 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5278 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5280 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
5284 case NestedNameSpecifier::Namespace:
5285 case NestedNameSpecifier::NamespaceAlias:
5286 case NestedNameSpecifier::Global:
5287 case NestedNameSpecifier::Super:
5288 llvm_unreachable("Nested-name-specifier must name a type");
5291 // Finally fill in MemberPointerLocInfo fields.
5292 TL.setStarLoc(Chunk.Loc);
5293 TL.setClassTInfo(ClsTInfo);
5295 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5296 assert(Chunk.Kind == DeclaratorChunk::Reference);
5297 // 'Amp' is misleading: this might have been originally
5298 /// spelled with AmpAmp.
5299 TL.setAmpLoc(Chunk.Loc);
5301 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5302 assert(Chunk.Kind == DeclaratorChunk::Reference);
5303 assert(!Chunk.Ref.LValueRef);
5304 TL.setAmpAmpLoc(Chunk.Loc);
5306 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
5307 assert(Chunk.Kind == DeclaratorChunk::Array);
5308 TL.setLBracketLoc(Chunk.Loc);
5309 TL.setRBracketLoc(Chunk.EndLoc);
5310 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
5312 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5313 assert(Chunk.Kind == DeclaratorChunk::Function);
5314 TL.setLocalRangeBegin(Chunk.Loc);
5315 TL.setLocalRangeEnd(Chunk.EndLoc);
5317 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
5318 TL.setLParenLoc(FTI.getLParenLoc());
5319 TL.setRParenLoc(FTI.getRParenLoc());
5320 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
5321 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5322 TL.setParam(tpi++, Param);
5324 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
5326 void VisitParenTypeLoc(ParenTypeLoc TL) {
5327 assert(Chunk.Kind == DeclaratorChunk::Paren);
5328 TL.setLParenLoc(Chunk.Loc);
5329 TL.setRParenLoc(Chunk.EndLoc);
5331 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5332 assert(Chunk.Kind == DeclaratorChunk::Pipe);
5333 TL.setKWLoc(Chunk.Loc);
5336 void VisitTypeLoc(TypeLoc TL) {
5337 llvm_unreachable("unsupported TypeLoc kind in declarator!");
5340 } // end anonymous namespace
5342 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5344 switch (Chunk.Kind) {
5345 case DeclaratorChunk::Function:
5346 case DeclaratorChunk::Array:
5347 case DeclaratorChunk::Paren:
5348 case DeclaratorChunk::Pipe:
5349 llvm_unreachable("cannot be _Atomic qualified");
5351 case DeclaratorChunk::Pointer:
5352 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
5355 case DeclaratorChunk::BlockPointer:
5356 case DeclaratorChunk::Reference:
5357 case DeclaratorChunk::MemberPointer:
5358 // FIXME: Provide a source location for the _Atomic keyword.
5363 ATL.setParensRange(SourceRange());
5366 /// \brief Create and instantiate a TypeSourceInfo with type source information.
5368 /// \param T QualType referring to the type as written in source code.
5370 /// \param ReturnTypeInfo For declarators whose return type does not show
5371 /// up in the normal place in the declaration specifiers (such as a C++
5372 /// conversion function), this pointer will refer to a type source information
5373 /// for that return type.
5375 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
5376 TypeSourceInfo *ReturnTypeInfo) {
5377 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
5378 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
5379 const AttributeList *DeclAttrs = D.getAttributes();
5381 // Handle parameter packs whose type is a pack expansion.
5382 if (isa<PackExpansionType>(T)) {
5383 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
5384 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5387 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5388 // An AtomicTypeLoc might be produced by an atomic qualifier in this
5389 // declarator chunk.
5390 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
5391 fillAtomicQualLoc(ATL, D.getTypeObject(i));
5392 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
5395 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
5396 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
5397 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5400 // FIXME: Ordering here?
5401 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
5402 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5404 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
5405 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5408 // If we have different source information for the return type, use
5409 // that. This really only applies to C++ conversion functions.
5410 if (ReturnTypeInfo) {
5411 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
5412 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
5413 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
5415 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
5421 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
5422 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
5423 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
5424 // and Sema during declaration parsing. Try deallocating/caching them when
5425 // it's appropriate, instead of allocating them and keeping them around.
5426 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
5428 new (LocT) LocInfoType(T, TInfo);
5429 assert(LocT->getTypeClass() != T->getTypeClass() &&
5430 "LocInfoType's TypeClass conflicts with an existing Type class");
5431 return ParsedType::make(QualType(LocT, 0));
5434 void LocInfoType::getAsStringInternal(std::string &Str,
5435 const PrintingPolicy &Policy) const {
5436 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
5437 " was used directly instead of getting the QualType through"
5438 " GetTypeFromParser");
5441 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
5442 // C99 6.7.6: Type names have no identifier. This is already validated by
5444 assert(D.getIdentifier() == nullptr &&
5445 "Type name should have no identifier!");
5447 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5448 QualType T = TInfo->getType();
5449 if (D.isInvalidType())
5452 // Make sure there are no unused decl attributes on the declarator.
5453 // We don't want to do this for ObjC parameters because we're going
5454 // to apply them to the actual parameter declaration.
5455 // Likewise, we don't want to do this for alias declarations, because
5456 // we are actually going to build a declaration from this eventually.
5457 if (D.getContext() != Declarator::ObjCParameterContext &&
5458 D.getContext() != Declarator::AliasDeclContext &&
5459 D.getContext() != Declarator::AliasTemplateContext)
5460 checkUnusedDeclAttributes(D);
5462 if (getLangOpts().CPlusPlus) {
5463 // Check that there are no default arguments (C++ only).
5464 CheckExtraCXXDefaultArguments(D);
5467 return CreateParsedType(T, TInfo);
5470 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
5471 QualType T = Context.getObjCInstanceType();
5472 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
5473 return CreateParsedType(T, TInfo);
5476 //===----------------------------------------------------------------------===//
5477 // Type Attribute Processing
5478 //===----------------------------------------------------------------------===//
5480 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5481 /// specified type. The attribute contains 1 argument, the id of the address
5482 /// space for the type.
5483 static void HandleAddressSpaceTypeAttribute(QualType &Type,
5484 const AttributeList &Attr, Sema &S){
5486 // If this type is already address space qualified, reject it.
5487 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5488 // qualifiers for two or more different address spaces."
5489 if (Type.getAddressSpace()) {
5490 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5495 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5496 // qualified by an address-space qualifier."
5497 if (Type->isFunctionType()) {
5498 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5504 if (Attr.getKind() == AttributeList::AT_AddressSpace) {
5505 // Check the attribute arguments.
5506 if (Attr.getNumArgs() != 1) {
5507 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5508 << Attr.getName() << 1;
5512 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5513 llvm::APSInt addrSpace(32);
5514 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
5515 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
5516 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5517 << Attr.getName() << AANT_ArgumentIntegerConstant
5518 << ASArgExpr->getSourceRange();
5524 if (addrSpace.isSigned()) {
5525 if (addrSpace.isNegative()) {
5526 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
5527 << ASArgExpr->getSourceRange();
5531 addrSpace.setIsSigned(false);
5533 llvm::APSInt max(addrSpace.getBitWidth());
5534 max = Qualifiers::MaxAddressSpace - LangAS::Count;
5535 if (addrSpace > max) {
5536 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
5537 << (unsigned)max.getZExtValue() << ASArgExpr->getSourceRange();
5541 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()) + LangAS::Count;
5543 // The keyword-based type attributes imply which address space to use.
5544 switch (Attr.getKind()) {
5545 case AttributeList::AT_OpenCLGlobalAddressSpace:
5546 ASIdx = LangAS::opencl_global; break;
5547 case AttributeList::AT_OpenCLLocalAddressSpace:
5548 ASIdx = LangAS::opencl_local; break;
5549 case AttributeList::AT_OpenCLConstantAddressSpace:
5550 ASIdx = LangAS::opencl_constant; break;
5551 case AttributeList::AT_OpenCLGenericAddressSpace:
5552 ASIdx = LangAS::opencl_generic; break;
5554 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
5559 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5562 /// Does this type have a "direct" ownership qualifier? That is,
5563 /// is it written like "__strong id", as opposed to something like
5564 /// "typeof(foo)", where that happens to be strong?
5565 static bool hasDirectOwnershipQualifier(QualType type) {
5566 // Fast path: no qualifier at all.
5567 assert(type.getQualifiers().hasObjCLifetime());
5571 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5572 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5575 type = attr->getModifiedType();
5577 // X *__strong (...)
5578 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5579 type = paren->getInnerType();
5581 // That's it for things we want to complain about. In particular,
5582 // we do not want to look through typedefs, typeof(expr),
5583 // typeof(type), or any other way that the type is somehow
5592 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5593 /// attribute on the specified type.
5595 /// Returns 'true' if the attribute was handled.
5596 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5597 AttributeList &attr,
5599 bool NonObjCPointer = false;
5601 if (!type->isDependentType() && !type->isUndeducedType()) {
5602 if (const PointerType *ptr = type->getAs<PointerType>()) {
5603 QualType pointee = ptr->getPointeeType();
5604 if (pointee->isObjCRetainableType() || pointee->isPointerType())
5606 // It is important not to lose the source info that there was an attribute
5607 // applied to non-objc pointer. We will create an attributed type but
5608 // its type will be the same as the original type.
5609 NonObjCPointer = true;
5610 } else if (!type->isObjCRetainableType()) {
5614 // Don't accept an ownership attribute in the declspec if it would
5615 // just be the return type of a block pointer.
5616 if (state.isProcessingDeclSpec()) {
5617 Declarator &D = state.getDeclarator();
5618 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5619 /*onlyBlockPointers=*/true))
5624 Sema &S = state.getSema();
5625 SourceLocation AttrLoc = attr.getLoc();
5626 if (AttrLoc.isMacroID())
5627 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
5629 if (!attr.isArgIdent(0)) {
5630 S.Diag(AttrLoc, diag::err_attribute_argument_type)
5631 << attr.getName() << AANT_ArgumentString;
5636 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5637 Qualifiers::ObjCLifetime lifetime;
5638 if (II->isStr("none"))
5639 lifetime = Qualifiers::OCL_ExplicitNone;
5640 else if (II->isStr("strong"))
5641 lifetime = Qualifiers::OCL_Strong;
5642 else if (II->isStr("weak"))
5643 lifetime = Qualifiers::OCL_Weak;
5644 else if (II->isStr("autoreleasing"))
5645 lifetime = Qualifiers::OCL_Autoreleasing;
5647 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5648 << attr.getName() << II;
5653 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
5654 // outside of ARC mode.
5655 if (!S.getLangOpts().ObjCAutoRefCount &&
5656 lifetime != Qualifiers::OCL_Weak &&
5657 lifetime != Qualifiers::OCL_ExplicitNone) {
5661 SplitQualType underlyingType = type.split();
5663 // Check for redundant/conflicting ownership qualifiers.
5664 if (Qualifiers::ObjCLifetime previousLifetime
5665 = type.getQualifiers().getObjCLifetime()) {
5666 // If it's written directly, that's an error.
5667 if (hasDirectOwnershipQualifier(type)) {
5668 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5673 // Otherwise, if the qualifiers actually conflict, pull sugar off
5674 // and remove the ObjCLifetime qualifiers.
5675 if (previousLifetime != lifetime) {
5676 // It's possible to have multiple local ObjCLifetime qualifiers. We
5677 // can't stop after we reach a type that is directly qualified.
5678 const Type *prevTy = nullptr;
5679 while (!prevTy || prevTy != underlyingType.Ty) {
5680 prevTy = underlyingType.Ty;
5681 underlyingType = underlyingType.getSingleStepDesugaredType();
5683 underlyingType.Quals.removeObjCLifetime();
5687 underlyingType.Quals.addObjCLifetime(lifetime);
5689 if (NonObjCPointer) {
5690 StringRef name = attr.getName()->getName();
5692 case Qualifiers::OCL_None:
5693 case Qualifiers::OCL_ExplicitNone:
5695 case Qualifiers::OCL_Strong: name = "__strong"; break;
5696 case Qualifiers::OCL_Weak: name = "__weak"; break;
5697 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5699 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5700 << TDS_ObjCObjOrBlock << type;
5703 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
5704 // because having both 'T' and '__unsafe_unretained T' exist in the type
5705 // system causes unfortunate widespread consistency problems. (For example,
5706 // they're not considered compatible types, and we mangle them identicially
5707 // as template arguments.) These problems are all individually fixable,
5708 // but it's easier to just not add the qualifier and instead sniff it out
5709 // in specific places using isObjCInertUnsafeUnretainedType().
5711 // Doing this does means we miss some trivial consistency checks that
5712 // would've triggered in ARC, but that's better than trying to solve all
5713 // the coexistence problems with __unsafe_unretained.
5714 if (!S.getLangOpts().ObjCAutoRefCount &&
5715 lifetime == Qualifiers::OCL_ExplicitNone) {
5716 type = S.Context.getAttributedType(
5717 AttributedType::attr_objc_inert_unsafe_unretained,
5722 QualType origType = type;
5723 if (!NonObjCPointer)
5724 type = S.Context.getQualifiedType(underlyingType);
5726 // If we have a valid source location for the attribute, use an
5727 // AttributedType instead.
5728 if (AttrLoc.isValid())
5729 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
5732 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
5733 unsigned diagnostic, QualType type) {
5734 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
5735 S.DelayedDiagnostics.add(
5736 sema::DelayedDiagnostic::makeForbiddenType(
5737 S.getSourceManager().getExpansionLoc(loc),
5738 diagnostic, type, /*ignored*/ 0));
5740 S.Diag(loc, diagnostic);
5744 // Sometimes, __weak isn't allowed.
5745 if (lifetime == Qualifiers::OCL_Weak &&
5746 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
5748 // Use a specialized diagnostic if the runtime just doesn't support them.
5749 unsigned diagnostic =
5750 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
5751 : diag::err_arc_weak_no_runtime);
5753 // In any case, delay the diagnostic until we know what we're parsing.
5754 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
5760 // Forbid __weak for class objects marked as
5761 // objc_arc_weak_reference_unavailable
5762 if (lifetime == Qualifiers::OCL_Weak) {
5763 if (const ObjCObjectPointerType *ObjT =
5764 type->getAs<ObjCObjectPointerType>()) {
5765 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
5766 if (Class->isArcWeakrefUnavailable()) {
5767 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
5768 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
5769 diag::note_class_declared);
5778 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
5779 /// attribute on the specified type. Returns true to indicate that
5780 /// the attribute was handled, false to indicate that the type does
5781 /// not permit the attribute.
5782 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
5783 AttributeList &attr,
5785 Sema &S = state.getSema();
5787 // Delay if this isn't some kind of pointer.
5788 if (!type->isPointerType() &&
5789 !type->isObjCObjectPointerType() &&
5790 !type->isBlockPointerType())
5793 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
5794 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
5799 // Check the attribute arguments.
5800 if (!attr.isArgIdent(0)) {
5801 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
5802 << attr.getName() << AANT_ArgumentString;
5806 Qualifiers::GC GCAttr;
5807 if (attr.getNumArgs() > 1) {
5808 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5809 << attr.getName() << 1;
5814 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5815 if (II->isStr("weak"))
5816 GCAttr = Qualifiers::Weak;
5817 else if (II->isStr("strong"))
5818 GCAttr = Qualifiers::Strong;
5820 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
5821 << attr.getName() << II;
5826 QualType origType = type;
5827 type = S.Context.getObjCGCQualType(origType, GCAttr);
5829 // Make an attributed type to preserve the source information.
5830 if (attr.getLoc().isValid())
5831 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
5838 /// A helper class to unwrap a type down to a function for the
5839 /// purposes of applying attributes there.
5842 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
5843 /// if (unwrapped.isFunctionType()) {
5844 /// const FunctionType *fn = unwrapped.get();
5845 /// // change fn somehow
5846 /// T = unwrapped.wrap(fn);
5848 struct FunctionTypeUnwrapper {
5860 const FunctionType *Fn;
5861 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
5863 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
5865 const Type *Ty = T.getTypePtr();
5866 if (isa<FunctionType>(Ty)) {
5867 Fn = cast<FunctionType>(Ty);
5869 } else if (isa<ParenType>(Ty)) {
5870 T = cast<ParenType>(Ty)->getInnerType();
5871 Stack.push_back(Parens);
5872 } else if (isa<PointerType>(Ty)) {
5873 T = cast<PointerType>(Ty)->getPointeeType();
5874 Stack.push_back(Pointer);
5875 } else if (isa<BlockPointerType>(Ty)) {
5876 T = cast<BlockPointerType>(Ty)->getPointeeType();
5877 Stack.push_back(BlockPointer);
5878 } else if (isa<MemberPointerType>(Ty)) {
5879 T = cast<MemberPointerType>(Ty)->getPointeeType();
5880 Stack.push_back(MemberPointer);
5881 } else if (isa<ReferenceType>(Ty)) {
5882 T = cast<ReferenceType>(Ty)->getPointeeType();
5883 Stack.push_back(Reference);
5884 } else if (isa<AttributedType>(Ty)) {
5885 T = cast<AttributedType>(Ty)->getEquivalentType();
5886 Stack.push_back(Attributed);
5888 const Type *DTy = Ty->getUnqualifiedDesugaredType();
5894 T = QualType(DTy, 0);
5895 Stack.push_back(Desugar);
5900 bool isFunctionType() const { return (Fn != nullptr); }
5901 const FunctionType *get() const { return Fn; }
5903 QualType wrap(Sema &S, const FunctionType *New) {
5904 // If T wasn't modified from the unwrapped type, do nothing.
5905 if (New == get()) return Original;
5908 return wrap(S.Context, Original, 0);
5912 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
5913 if (I == Stack.size())
5914 return C.getQualifiedType(Fn, Old.getQualifiers());
5916 // Build up the inner type, applying the qualifiers from the old
5917 // type to the new type.
5918 SplitQualType SplitOld = Old.split();
5920 // As a special case, tail-recurse if there are no qualifiers.
5921 if (SplitOld.Quals.empty())
5922 return wrap(C, SplitOld.Ty, I);
5923 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
5926 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
5927 if (I == Stack.size()) return QualType(Fn, 0);
5929 switch (static_cast<WrapKind>(Stack[I++])) {
5931 // This is the point at which we potentially lose source
5933 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
5936 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
5939 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
5940 return C.getParenType(New);
5944 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
5945 return C.getPointerType(New);
5948 case BlockPointer: {
5949 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
5950 return C.getBlockPointerType(New);
5953 case MemberPointer: {
5954 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
5955 QualType New = wrap(C, OldMPT->getPointeeType(), I);
5956 return C.getMemberPointerType(New, OldMPT->getClass());
5960 const ReferenceType *OldRef = cast<ReferenceType>(Old);
5961 QualType New = wrap(C, OldRef->getPointeeType(), I);
5962 if (isa<LValueReferenceType>(OldRef))
5963 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
5965 return C.getRValueReferenceType(New);
5969 llvm_unreachable("unknown wrapping kind");
5972 } // end anonymous namespace
5974 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
5975 AttributeList &Attr,
5977 Sema &S = State.getSema();
5979 AttributeList::Kind Kind = Attr.getKind();
5980 QualType Desugared = Type;
5981 const AttributedType *AT = dyn_cast<AttributedType>(Type);
5983 AttributedType::Kind CurAttrKind = AT->getAttrKind();
5985 // You cannot specify duplicate type attributes, so if the attribute has
5986 // already been applied, flag it.
5987 if (getAttrListKind(CurAttrKind) == Kind) {
5988 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
5993 // You cannot have both __sptr and __uptr on the same type, nor can you
5994 // have __ptr32 and __ptr64.
5995 if ((CurAttrKind == AttributedType::attr_ptr32 &&
5996 Kind == AttributeList::AT_Ptr64) ||
5997 (CurAttrKind == AttributedType::attr_ptr64 &&
5998 Kind == AttributeList::AT_Ptr32)) {
5999 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
6000 << "'__ptr32'" << "'__ptr64'";
6002 } else if ((CurAttrKind == AttributedType::attr_sptr &&
6003 Kind == AttributeList::AT_UPtr) ||
6004 (CurAttrKind == AttributedType::attr_uptr &&
6005 Kind == AttributeList::AT_SPtr)) {
6006 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
6007 << "'__sptr'" << "'__uptr'";
6011 Desugared = AT->getEquivalentType();
6012 AT = dyn_cast<AttributedType>(Desugared);
6015 // Pointer type qualifiers can only operate on pointer types, but not
6016 // pointer-to-member types.
6017 if (!isa<PointerType>(Desugared)) {
6018 if (Type->isMemberPointerType())
6019 S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers)
6022 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
6023 << Attr.getName() << 0;
6027 AttributedType::Kind TAK;
6029 default: llvm_unreachable("Unknown attribute kind");
6030 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
6031 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
6032 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
6033 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
6036 Type = S.Context.getAttributedType(TAK, Type, Type);
6040 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
6041 NullabilityKind nullability,
6042 SourceLocation nullabilityLoc,
6043 bool isContextSensitive,
6044 bool allowOnArrayType) {
6045 recordNullabilitySeen(*this, nullabilityLoc);
6047 // Check for existing nullability attributes on the type.
6048 QualType desugared = type;
6049 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
6050 // Check whether there is already a null
6051 if (auto existingNullability = attributed->getImmediateNullability()) {
6052 // Duplicated nullability.
6053 if (nullability == *existingNullability) {
6054 Diag(nullabilityLoc, diag::warn_nullability_duplicate)
6055 << DiagNullabilityKind(nullability, isContextSensitive)
6056 << FixItHint::CreateRemoval(nullabilityLoc);
6061 // Conflicting nullability.
6062 Diag(nullabilityLoc, diag::err_nullability_conflicting)
6063 << DiagNullabilityKind(nullability, isContextSensitive)
6064 << DiagNullabilityKind(*existingNullability, false);
6068 desugared = attributed->getModifiedType();
6071 // If there is already a different nullability specifier, complain.
6072 // This (unlike the code above) looks through typedefs that might
6073 // have nullability specifiers on them, which means we cannot
6074 // provide a useful Fix-It.
6075 if (auto existingNullability = desugared->getNullability(Context)) {
6076 if (nullability != *existingNullability) {
6077 Diag(nullabilityLoc, diag::err_nullability_conflicting)
6078 << DiagNullabilityKind(nullability, isContextSensitive)
6079 << DiagNullabilityKind(*existingNullability, false);
6081 // Try to find the typedef with the existing nullability specifier.
6082 if (auto typedefType = desugared->getAs<TypedefType>()) {
6083 TypedefNameDecl *typedefDecl = typedefType->getDecl();
6084 QualType underlyingType = typedefDecl->getUnderlyingType();
6085 if (auto typedefNullability
6086 = AttributedType::stripOuterNullability(underlyingType)) {
6087 if (*typedefNullability == *existingNullability) {
6088 Diag(typedefDecl->getLocation(), diag::note_nullability_here)
6089 << DiagNullabilityKind(*existingNullability, false);
6098 // If this definitely isn't a pointer type, reject the specifier.
6099 if (!desugared->canHaveNullability() &&
6100 !(allowOnArrayType && desugared->isArrayType())) {
6101 Diag(nullabilityLoc, diag::err_nullability_nonpointer)
6102 << DiagNullabilityKind(nullability, isContextSensitive) << type;
6106 // For the context-sensitive keywords/Objective-C property
6107 // attributes, require that the type be a single-level pointer.
6108 if (isContextSensitive) {
6109 // Make sure that the pointee isn't itself a pointer type.
6110 const Type *pointeeType;
6111 if (desugared->isArrayType())
6112 pointeeType = desugared->getArrayElementTypeNoTypeQual();
6114 pointeeType = desugared->getPointeeType().getTypePtr();
6116 if (pointeeType->isAnyPointerType() ||
6117 pointeeType->isObjCObjectPointerType() ||
6118 pointeeType->isMemberPointerType()) {
6119 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
6120 << DiagNullabilityKind(nullability, true)
6122 Diag(nullabilityLoc, diag::note_nullability_type_specifier)
6123 << DiagNullabilityKind(nullability, false)
6125 << FixItHint::CreateReplacement(nullabilityLoc,
6126 getNullabilitySpelling(nullability));
6131 // Form the attributed type.
6132 type = Context.getAttributedType(
6133 AttributedType::getNullabilityAttrKind(nullability), type, type);
6137 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
6138 if (isa<ObjCTypeParamType>(type)) {
6139 // Build the attributed type to record where __kindof occurred.
6140 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6145 // Find out if it's an Objective-C object or object pointer type;
6146 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
6147 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
6148 : type->getAs<ObjCObjectType>();
6150 // If not, we can't apply __kindof.
6152 // FIXME: Handle dependent types that aren't yet object types.
6153 Diag(loc, diag::err_objc_kindof_nonobject)
6158 // Rebuild the "equivalent" type, which pushes __kindof down into
6160 // There is no need to apply kindof on an unqualified id type.
6161 QualType equivType = Context.getObjCObjectType(
6162 objType->getBaseType(), objType->getTypeArgsAsWritten(),
6163 objType->getProtocols(),
6164 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
6166 // If we started with an object pointer type, rebuild it.
6168 equivType = Context.getObjCObjectPointerType(equivType);
6169 if (auto nullability = type->getNullability(Context)) {
6170 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
6171 equivType = Context.getAttributedType(attrKind, equivType, equivType);
6175 // Build the attributed type to record where __kindof occurred.
6176 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6183 /// Map a nullability attribute kind to a nullability kind.
6184 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
6186 case AttributeList::AT_TypeNonNull:
6187 return NullabilityKind::NonNull;
6189 case AttributeList::AT_TypeNullable:
6190 return NullabilityKind::Nullable;
6192 case AttributeList::AT_TypeNullUnspecified:
6193 return NullabilityKind::Unspecified;
6196 llvm_unreachable("not a nullability attribute kind");
6200 /// Distribute a nullability type attribute that cannot be applied to
6201 /// the type specifier to a pointer, block pointer, or member pointer
6202 /// declarator, complaining if necessary.
6204 /// \returns true if the nullability annotation was distributed, false
6206 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
6208 AttributeList &attr) {
6209 Declarator &declarator = state.getDeclarator();
6211 /// Attempt to move the attribute to the specified chunk.
6212 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
6213 // If there is already a nullability attribute there, don't add
6215 if (hasNullabilityAttr(chunk.getAttrListRef()))
6218 // Complain about the nullability qualifier being in the wrong
6225 PK_MemberFunctionPointer,
6227 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
6229 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
6230 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
6232 auto diag = state.getSema().Diag(attr.getLoc(),
6233 diag::warn_nullability_declspec)
6234 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
6235 attr.isContextSensitiveKeywordAttribute())
6237 << static_cast<unsigned>(pointerKind);
6239 // FIXME: MemberPointer chunks don't carry the location of the *.
6240 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
6241 diag << FixItHint::CreateRemoval(attr.getLoc())
6242 << FixItHint::CreateInsertion(
6243 state.getSema().getPreprocessor()
6244 .getLocForEndOfToken(chunk.Loc),
6245 " " + attr.getName()->getName().str() + " ");
6248 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
6249 chunk.getAttrListRef());
6253 // Move it to the outermost pointer, member pointer, or block
6254 // pointer declarator.
6255 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
6256 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6257 switch (chunk.Kind) {
6258 case DeclaratorChunk::Pointer:
6259 case DeclaratorChunk::BlockPointer:
6260 case DeclaratorChunk::MemberPointer:
6261 return moveToChunk(chunk, false);
6263 case DeclaratorChunk::Paren:
6264 case DeclaratorChunk::Array:
6267 case DeclaratorChunk::Function:
6268 // Try to move past the return type to a function/block/member
6269 // function pointer.
6270 if (DeclaratorChunk *dest = maybeMovePastReturnType(
6272 /*onlyBlockPointers=*/false)) {
6273 return moveToChunk(*dest, true);
6278 // Don't walk through these.
6279 case DeclaratorChunk::Reference:
6280 case DeclaratorChunk::Pipe:
6288 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
6289 assert(!Attr.isInvalid());
6290 switch (Attr.getKind()) {
6292 llvm_unreachable("not a calling convention attribute");
6293 case AttributeList::AT_CDecl:
6294 return AttributedType::attr_cdecl;
6295 case AttributeList::AT_FastCall:
6296 return AttributedType::attr_fastcall;
6297 case AttributeList::AT_StdCall:
6298 return AttributedType::attr_stdcall;
6299 case AttributeList::AT_ThisCall:
6300 return AttributedType::attr_thiscall;
6301 case AttributeList::AT_RegCall:
6302 return AttributedType::attr_regcall;
6303 case AttributeList::AT_Pascal:
6304 return AttributedType::attr_pascal;
6305 case AttributeList::AT_SwiftCall:
6306 return AttributedType::attr_swiftcall;
6307 case AttributeList::AT_VectorCall:
6308 return AttributedType::attr_vectorcall;
6309 case AttributeList::AT_Pcs: {
6310 // The attribute may have had a fixit applied where we treated an
6311 // identifier as a string literal. The contents of the string are valid,
6312 // but the form may not be.
6314 if (Attr.isArgExpr(0))
6315 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6317 Str = Attr.getArgAsIdent(0)->Ident->getName();
6318 return llvm::StringSwitch<AttributedType::Kind>(Str)
6319 .Case("aapcs", AttributedType::attr_pcs)
6320 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
6322 case AttributeList::AT_IntelOclBicc:
6323 return AttributedType::attr_inteloclbicc;
6324 case AttributeList::AT_MSABI:
6325 return AttributedType::attr_ms_abi;
6326 case AttributeList::AT_SysVABI:
6327 return AttributedType::attr_sysv_abi;
6328 case AttributeList::AT_PreserveMost:
6329 return AttributedType::attr_preserve_most;
6330 case AttributeList::AT_PreserveAll:
6331 return AttributedType::attr_preserve_all;
6333 llvm_unreachable("unexpected attribute kind!");
6336 /// Process an individual function attribute. Returns true to
6337 /// indicate that the attribute was handled, false if it wasn't.
6338 static bool handleFunctionTypeAttr(TypeProcessingState &state,
6339 AttributeList &attr,
6341 Sema &S = state.getSema();
6343 FunctionTypeUnwrapper unwrapped(S, type);
6345 if (attr.getKind() == AttributeList::AT_NoReturn) {
6346 if (S.CheckNoReturnAttr(attr))
6349 // Delay if this is not a function type.
6350 if (!unwrapped.isFunctionType())
6353 // Otherwise we can process right away.
6354 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6355 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6359 // ns_returns_retained is not always a type attribute, but if we got
6360 // here, we're treating it as one right now.
6361 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
6362 assert(S.getLangOpts().ObjCAutoRefCount &&
6363 "ns_returns_retained treated as type attribute in non-ARC");
6364 if (attr.getNumArgs()) return true;
6366 // Delay if this is not a function type.
6367 if (!unwrapped.isFunctionType())
6370 FunctionType::ExtInfo EI
6371 = unwrapped.get()->getExtInfo().withProducesResult(true);
6372 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6376 if (attr.getKind() == AttributeList::AT_AnyX86NoCallerSavedRegisters) {
6377 if (S.CheckNoCallerSavedRegsAttr(attr))
6380 // Delay if this is not a function type.
6381 if (!unwrapped.isFunctionType())
6384 FunctionType::ExtInfo EI =
6385 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
6386 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6390 if (attr.getKind() == AttributeList::AT_Regparm) {
6392 if (S.CheckRegparmAttr(attr, value))
6395 // Delay if this is not a function type.
6396 if (!unwrapped.isFunctionType())
6399 // Diagnose regparm with fastcall.
6400 const FunctionType *fn = unwrapped.get();
6401 CallingConv CC = fn->getCallConv();
6402 if (CC == CC_X86FastCall) {
6403 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6404 << FunctionType::getNameForCallConv(CC)
6410 FunctionType::ExtInfo EI =
6411 unwrapped.get()->getExtInfo().withRegParm(value);
6412 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6416 // Delay if the type didn't work out to a function.
6417 if (!unwrapped.isFunctionType()) return false;
6419 // Otherwise, a calling convention.
6421 if (S.CheckCallingConvAttr(attr, CC))
6424 const FunctionType *fn = unwrapped.get();
6425 CallingConv CCOld = fn->getCallConv();
6426 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
6429 // Error out on when there's already an attribute on the type
6430 // and the CCs don't match.
6431 const AttributedType *AT = S.getCallingConvAttributedType(type);
6432 if (AT && AT->getAttrKind() != CCAttrKind) {
6433 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6434 << FunctionType::getNameForCallConv(CC)
6435 << FunctionType::getNameForCallConv(CCOld);
6441 // Diagnose use of variadic functions with calling conventions that
6442 // don't support them (e.g. because they're callee-cleanup).
6443 // We delay warning about this on unprototyped function declarations
6444 // until after redeclaration checking, just in case we pick up a
6445 // prototype that way. And apparently we also "delay" warning about
6446 // unprototyped function types in general, despite not necessarily having
6447 // much ability to diagnose it later.
6448 if (!supportsVariadicCall(CC)) {
6449 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6450 if (FnP && FnP->isVariadic()) {
6451 unsigned DiagID = diag::err_cconv_varargs;
6453 // stdcall and fastcall are ignored with a warning for GCC and MS
6455 bool IsInvalid = true;
6456 if (CC == CC_X86StdCall || CC == CC_X86FastCall) {
6457 DiagID = diag::warn_cconv_varargs;
6461 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
6462 if (IsInvalid) attr.setInvalid();
6467 // Also diagnose fastcall with regparm.
6468 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
6469 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6470 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
6475 // Modify the CC from the wrapped function type, wrap it all back, and then
6476 // wrap the whole thing in an AttributedType as written. The modified type
6477 // might have a different CC if we ignored the attribute.
6478 QualType Equivalent;
6482 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
6484 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6486 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
6490 bool Sema::hasExplicitCallingConv(QualType &T) {
6491 QualType R = T.IgnoreParens();
6492 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
6493 if (AT->isCallingConv())
6495 R = AT->getModifiedType().IgnoreParens();
6500 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
6501 SourceLocation Loc) {
6502 FunctionTypeUnwrapper Unwrapped(*this, T);
6503 const FunctionType *FT = Unwrapped.get();
6504 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
6505 cast<FunctionProtoType>(FT)->isVariadic());
6506 CallingConv CurCC = FT->getCallConv();
6507 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
6512 // MS compiler ignores explicit calling convention attributes on structors. We
6513 // should do the same.
6514 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
6515 // Issue a warning on ignored calling convention -- except of __stdcall.
6516 // Again, this is what MS compiler does.
6517 if (CurCC != CC_X86StdCall)
6518 Diag(Loc, diag::warn_cconv_structors)
6519 << FunctionType::getNameForCallConv(CurCC);
6520 // Default adjustment.
6522 // Only adjust types with the default convention. For example, on Windows
6523 // we should adjust a __cdecl type to __thiscall for instance methods, and a
6524 // __thiscall type to __cdecl for static methods.
6525 CallingConv DefaultCC =
6526 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6528 if (CurCC != DefaultCC || DefaultCC == ToCC)
6531 if (hasExplicitCallingConv(T))
6535 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6536 QualType Wrapped = Unwrapped.wrap(*this, FT);
6537 T = Context.getAdjustedType(T, Wrapped);
6540 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6541 /// and float scalars, although arrays, pointers, and function return values are
6542 /// allowed in conjunction with this construct. Aggregates with this attribute
6543 /// are invalid, even if they are of the same size as a corresponding scalar.
6544 /// The raw attribute should contain precisely 1 argument, the vector size for
6545 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6546 /// this routine will return a new vector type.
6547 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
6549 // Check the attribute arguments.
6550 if (Attr.getNumArgs() != 1) {
6551 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6552 << Attr.getName() << 1;
6556 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6557 llvm::APSInt vecSize(32);
6558 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
6559 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
6560 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6561 << Attr.getName() << AANT_ArgumentIntegerConstant
6562 << sizeExpr->getSourceRange();
6566 // The base type must be integer (not Boolean or enumeration) or float, and
6567 // can't already be a vector.
6568 if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
6569 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
6570 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6574 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6575 // vecSize is specified in bytes - convert to bits.
6576 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
6578 // the vector size needs to be an integral multiple of the type size.
6579 if (vectorSize % typeSize) {
6580 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
6581 << sizeExpr->getSourceRange();
6585 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
6586 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
6587 << sizeExpr->getSourceRange();
6591 if (vectorSize == 0) {
6592 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
6593 << sizeExpr->getSourceRange();
6598 // Success! Instantiate the vector type, the number of elements is > 0, and
6599 // not required to be a power of 2, unlike GCC.
6600 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
6601 VectorType::GenericVector);
6604 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
6606 static void HandleExtVectorTypeAttr(QualType &CurType,
6607 const AttributeList &Attr,
6609 // check the attribute arguments.
6610 if (Attr.getNumArgs() != 1) {
6611 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6612 << Attr.getName() << 1;
6618 // Special case where the argument is a template id.
6619 if (Attr.isArgIdent(0)) {
6621 SourceLocation TemplateKWLoc;
6623 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6625 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6627 if (Size.isInvalid())
6630 sizeExpr = Size.get();
6632 sizeExpr = Attr.getArgAsExpr(0);
6635 // Create the vector type.
6636 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6641 static bool isPermittedNeonBaseType(QualType &Ty,
6642 VectorType::VectorKind VecKind, Sema &S) {
6643 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6647 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6649 // Signed poly is mathematically wrong, but has been baked into some ABIs by
6651 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6652 Triple.getArch() == llvm::Triple::aarch64_be;
6653 if (VecKind == VectorType::NeonPolyVector) {
6654 if (IsPolyUnsigned) {
6655 // AArch64 polynomial vectors are unsigned and support poly64.
6656 return BTy->getKind() == BuiltinType::UChar ||
6657 BTy->getKind() == BuiltinType::UShort ||
6658 BTy->getKind() == BuiltinType::ULong ||
6659 BTy->getKind() == BuiltinType::ULongLong;
6661 // AArch32 polynomial vector are signed.
6662 return BTy->getKind() == BuiltinType::SChar ||
6663 BTy->getKind() == BuiltinType::Short;
6667 // Non-polynomial vector types: the usual suspects are allowed, as well as
6668 // float64_t on AArch64.
6669 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6670 Triple.getArch() == llvm::Triple::aarch64_be;
6672 if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6675 return BTy->getKind() == BuiltinType::SChar ||
6676 BTy->getKind() == BuiltinType::UChar ||
6677 BTy->getKind() == BuiltinType::Short ||
6678 BTy->getKind() == BuiltinType::UShort ||
6679 BTy->getKind() == BuiltinType::Int ||
6680 BTy->getKind() == BuiltinType::UInt ||
6681 BTy->getKind() == BuiltinType::Long ||
6682 BTy->getKind() == BuiltinType::ULong ||
6683 BTy->getKind() == BuiltinType::LongLong ||
6684 BTy->getKind() == BuiltinType::ULongLong ||
6685 BTy->getKind() == BuiltinType::Float ||
6686 BTy->getKind() == BuiltinType::Half;
6689 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6690 /// "neon_polyvector_type" attributes are used to create vector types that
6691 /// are mangled according to ARM's ABI. Otherwise, these types are identical
6692 /// to those created with the "vector_size" attribute. Unlike "vector_size"
6693 /// the argument to these Neon attributes is the number of vector elements,
6694 /// not the vector size in bytes. The vector width and element type must
6695 /// match one of the standard Neon vector types.
6696 static void HandleNeonVectorTypeAttr(QualType& CurType,
6697 const AttributeList &Attr, Sema &S,
6698 VectorType::VectorKind VecKind) {
6699 // Target must have NEON
6700 if (!S.Context.getTargetInfo().hasFeature("neon")) {
6701 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6705 // Check the attribute arguments.
6706 if (Attr.getNumArgs() != 1) {
6707 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6708 << Attr.getName() << 1;
6712 // The number of elements must be an ICE.
6713 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6714 llvm::APSInt numEltsInt(32);
6715 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6716 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6717 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6718 << Attr.getName() << AANT_ArgumentIntegerConstant
6719 << numEltsExpr->getSourceRange();
6723 // Only certain element types are supported for Neon vectors.
6724 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6725 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6730 // The total size of the vector must be 64 or 128 bits.
6731 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6732 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6733 unsigned vecSize = typeSize * numElts;
6734 if (vecSize != 64 && vecSize != 128) {
6735 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6740 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6743 /// Handle OpenCL Access Qualifier Attribute.
6744 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr,
6746 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
6747 if (!(CurType->isImageType() || CurType->isPipeType())) {
6748 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
6753 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
6754 QualType PointeeTy = TypedefTy->desugar();
6755 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
6757 std::string PrevAccessQual;
6758 switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) {
6759 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6760 case BuiltinType::Id: \
6761 PrevAccessQual = #Access; \
6763 #include "clang/Basic/OpenCLImageTypes.def"
6765 assert(0 && "Unable to find corresponding image type.");
6768 S.Diag(TypedefTy->getDecl()->getLocStart(),
6769 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
6770 } else if (CurType->isPipeType()) {
6771 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
6772 QualType ElemType = CurType->getAs<PipeType>()->getElementType();
6773 CurType = S.Context.getWritePipeType(ElemType);
6778 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
6779 TypeAttrLocation TAL, AttributeList *attrs) {
6780 // Scan through and apply attributes to this type where it makes sense. Some
6781 // attributes (such as __address_space__, __vector_size__, etc) apply to the
6782 // type, but others can be present in the type specifiers even though they
6783 // apply to the decl. Here we apply type attributes and ignore the rest.
6785 bool hasOpenCLAddressSpace = false;
6787 AttributeList &attr = *attrs;
6788 attrs = attr.getNext(); // reset to the next here due to early loop continue
6791 // Skip attributes that were marked to be invalid.
6792 if (attr.isInvalid())
6795 if (attr.isCXX11Attribute()) {
6796 // [[gnu::...]] attributes are treated as declaration attributes, so may
6797 // not appertain to a DeclaratorChunk, even if we handle them as type
6799 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
6800 if (TAL == TAL_DeclChunk) {
6801 state.getSema().Diag(attr.getLoc(),
6802 diag::warn_cxx11_gnu_attribute_on_type)
6806 } else if (TAL != TAL_DeclChunk) {
6807 // Otherwise, only consider type processing for a C++11 attribute if
6808 // it's actually been applied to a type.
6813 // If this is an attribute we can handle, do so now,
6814 // otherwise, add it to the FnAttrs list for rechaining.
6815 switch (attr.getKind()) {
6817 // A C++11 attribute on a declarator chunk must appertain to a type.
6818 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
6819 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
6821 attr.setUsedAsTypeAttr();
6825 case AttributeList::UnknownAttribute:
6826 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6827 state.getSema().Diag(attr.getLoc(),
6828 diag::warn_unknown_attribute_ignored)
6832 case AttributeList::IgnoredAttribute:
6835 case AttributeList::AT_MayAlias:
6836 // FIXME: This attribute needs to actually be handled, but if we ignore
6837 // it it breaks large amounts of Linux software.
6838 attr.setUsedAsTypeAttr();
6840 case AttributeList::AT_OpenCLPrivateAddressSpace:
6841 case AttributeList::AT_OpenCLGlobalAddressSpace:
6842 case AttributeList::AT_OpenCLLocalAddressSpace:
6843 case AttributeList::AT_OpenCLConstantAddressSpace:
6844 case AttributeList::AT_OpenCLGenericAddressSpace:
6845 case AttributeList::AT_AddressSpace:
6846 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
6847 attr.setUsedAsTypeAttr();
6848 hasOpenCLAddressSpace = true;
6850 OBJC_POINTER_TYPE_ATTRS_CASELIST:
6851 if (!handleObjCPointerTypeAttr(state, attr, type))
6852 distributeObjCPointerTypeAttr(state, attr, type);
6853 attr.setUsedAsTypeAttr();
6855 case AttributeList::AT_VectorSize:
6856 HandleVectorSizeAttr(type, attr, state.getSema());
6857 attr.setUsedAsTypeAttr();
6859 case AttributeList::AT_ExtVectorType:
6860 HandleExtVectorTypeAttr(type, attr, state.getSema());
6861 attr.setUsedAsTypeAttr();
6863 case AttributeList::AT_NeonVectorType:
6864 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6865 VectorType::NeonVector);
6866 attr.setUsedAsTypeAttr();
6868 case AttributeList::AT_NeonPolyVectorType:
6869 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6870 VectorType::NeonPolyVector);
6871 attr.setUsedAsTypeAttr();
6873 case AttributeList::AT_OpenCLAccess:
6874 HandleOpenCLAccessAttr(type, attr, state.getSema());
6875 attr.setUsedAsTypeAttr();
6878 MS_TYPE_ATTRS_CASELIST:
6879 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6880 attr.setUsedAsTypeAttr();
6884 NULLABILITY_TYPE_ATTRS_CASELIST:
6885 // Either add nullability here or try to distribute it. We
6886 // don't want to distribute the nullability specifier past any
6887 // dependent type, because that complicates the user model.
6888 if (type->canHaveNullability() || type->isDependentType() ||
6889 type->isArrayType() ||
6890 !distributeNullabilityTypeAttr(state, type, attr)) {
6892 if (TAL == TAL_DeclChunk)
6893 endIndex = state.getCurrentChunkIndex();
6895 endIndex = state.getDeclarator().getNumTypeObjects();
6896 bool allowOnArrayType =
6897 state.getDeclarator().isPrototypeContext() &&
6898 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
6899 if (state.getSema().checkNullabilityTypeSpecifier(
6901 mapNullabilityAttrKind(attr.getKind()),
6903 attr.isContextSensitiveKeywordAttribute(),
6904 allowOnArrayType)) {
6908 attr.setUsedAsTypeAttr();
6912 case AttributeList::AT_ObjCKindOf:
6913 // '__kindof' must be part of the decl-specifiers.
6920 state.getSema().Diag(attr.getLoc(),
6921 diag::err_objc_kindof_wrong_position)
6922 << FixItHint::CreateRemoval(attr.getLoc())
6923 << FixItHint::CreateInsertion(
6924 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6928 // Apply it regardless.
6929 if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6931 attr.setUsedAsTypeAttr();
6934 case AttributeList::AT_NSReturnsRetained:
6935 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6937 // fallthrough into the function attrs
6939 FUNCTION_TYPE_ATTRS_CASELIST:
6940 attr.setUsedAsTypeAttr();
6942 // Never process function type attributes as part of the
6943 // declaration-specifiers.
6944 if (TAL == TAL_DeclSpec)
6945 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6947 // Otherwise, handle the possible delays.
6948 else if (!handleFunctionTypeAttr(state, attr, type))
6949 distributeFunctionTypeAttr(state, attr, type);
6954 // If address space is not set, OpenCL 2.0 defines non private default
6955 // address spaces for some cases:
6956 // OpenCL 2.0, section 6.5:
6957 // The address space for a variable at program scope or a static variable
6958 // inside a function can either be __global or __constant, but defaults to
6959 // __global if not specified.
6961 // Pointers that are declared without pointing to a named address space point
6962 // to the generic address space.
6963 if (state.getSema().getLangOpts().OpenCLVersion >= 200 &&
6964 !hasOpenCLAddressSpace && type.getAddressSpace() == 0 &&
6965 (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) {
6966 Declarator &D = state.getDeclarator();
6967 if (state.getCurrentChunkIndex() > 0 &&
6968 (D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6969 DeclaratorChunk::Pointer ||
6970 D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6971 DeclaratorChunk::BlockPointer)) {
6972 type = state.getSema().Context.getAddrSpaceQualType(
6973 type, LangAS::opencl_generic);
6974 } else if (state.getCurrentChunkIndex() == 0 &&
6975 D.getContext() == Declarator::FileContext &&
6976 !D.isFunctionDeclarator() && !D.isFunctionDefinition() &&
6977 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6978 !type->isSamplerT())
6979 type = state.getSema().Context.getAddrSpaceQualType(
6980 type, LangAS::opencl_global);
6981 else if (state.getCurrentChunkIndex() == 0 &&
6982 D.getContext() == Declarator::BlockContext &&
6983 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
6984 type = state.getSema().Context.getAddrSpaceQualType(
6985 type, LangAS::opencl_global);
6989 void Sema::completeExprArrayBound(Expr *E) {
6990 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6991 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6992 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
6993 SourceLocation PointOfInstantiation = E->getExprLoc();
6995 if (MemberSpecializationInfo *MSInfo =
6996 Var->getMemberSpecializationInfo()) {
6997 // If we don't already have a point of instantiation, this is it.
6998 if (MSInfo->getPointOfInstantiation().isInvalid()) {
6999 MSInfo->setPointOfInstantiation(PointOfInstantiation);
7001 // This is a modification of an existing AST node. Notify
7003 if (ASTMutationListener *L = getASTMutationListener())
7004 L->StaticDataMemberInstantiated(Var);
7007 VarTemplateSpecializationDecl *VarSpec =
7008 cast<VarTemplateSpecializationDecl>(Var);
7009 if (VarSpec->getPointOfInstantiation().isInvalid())
7010 VarSpec->setPointOfInstantiation(PointOfInstantiation);
7013 InstantiateVariableDefinition(PointOfInstantiation, Var);
7015 // Update the type to the newly instantiated definition's type both
7016 // here and within the expression.
7017 if (VarDecl *Def = Var->getDefinition()) {
7019 QualType T = Def->getType();
7021 // FIXME: Update the type on all intervening expressions.
7025 // We still go on to try to complete the type independently, as it
7026 // may also require instantiations or diagnostics if it remains
7033 /// \brief Ensure that the type of the given expression is complete.
7035 /// This routine checks whether the expression \p E has a complete type. If the
7036 /// expression refers to an instantiable construct, that instantiation is
7037 /// performed as needed to complete its type. Furthermore
7038 /// Sema::RequireCompleteType is called for the expression's type (or in the
7039 /// case of a reference type, the referred-to type).
7041 /// \param E The expression whose type is required to be complete.
7042 /// \param Diagnoser The object that will emit a diagnostic if the type is
7045 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
7047 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
7048 QualType T = E->getType();
7050 // Incomplete array types may be completed by the initializer attached to
7051 // their definitions. For static data members of class templates and for
7052 // variable templates, we need to instantiate the definition to get this
7053 // initializer and complete the type.
7054 if (T->isIncompleteArrayType()) {
7055 completeExprArrayBound(E);
7059 // FIXME: Are there other cases which require instantiating something other
7060 // than the type to complete the type of an expression?
7062 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
7065 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
7066 BoundTypeDiagnoser<> Diagnoser(DiagID);
7067 return RequireCompleteExprType(E, Diagnoser);
7070 /// @brief Ensure that the type T is a complete type.
7072 /// This routine checks whether the type @p T is complete in any
7073 /// context where a complete type is required. If @p T is a complete
7074 /// type, returns false. If @p T is a class template specialization,
7075 /// this routine then attempts to perform class template
7076 /// instantiation. If instantiation fails, or if @p T is incomplete
7077 /// and cannot be completed, issues the diagnostic @p diag (giving it
7078 /// the type @p T) and returns true.
7080 /// @param Loc The location in the source that the incomplete type
7081 /// diagnostic should refer to.
7083 /// @param T The type that this routine is examining for completeness.
7085 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
7086 /// @c false otherwise.
7087 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7088 TypeDiagnoser &Diagnoser) {
7089 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
7091 if (const TagType *Tag = T->getAs<TagType>()) {
7092 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
7093 Tag->getDecl()->setCompleteDefinitionRequired();
7094 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
7100 /// \brief Determine whether there is any declaration of \p D that was ever a
7101 /// definition (perhaps before module merging) and is currently visible.
7102 /// \param D The definition of the entity.
7103 /// \param Suggested Filled in with the declaration that should be made visible
7104 /// in order to provide a definition of this entity.
7105 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
7106 /// not defined. This only matters for enums with a fixed underlying
7107 /// type, since in all other cases, a type is complete if and only if it
7109 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
7110 bool OnlyNeedComplete) {
7111 // Easy case: if we don't have modules, all declarations are visible.
7112 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
7115 // If this definition was instantiated from a template, map back to the
7116 // pattern from which it was instantiated.
7117 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
7118 // We're in the middle of defining it; this definition should be treated
7121 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
7122 if (auto *Pattern = RD->getTemplateInstantiationPattern())
7124 D = RD->getDefinition();
7125 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
7126 if (auto *Pattern = ED->getTemplateInstantiationPattern())
7128 if (OnlyNeedComplete && ED->isFixed()) {
7129 // If the enum has a fixed underlying type, and we're only looking for a
7130 // complete type (not a definition), any visible declaration of it will
7132 *Suggested = nullptr;
7133 for (auto *Redecl : ED->redecls()) {
7134 if (isVisible(Redecl))
7136 if (Redecl->isThisDeclarationADefinition() ||
7137 (Redecl->isCanonicalDecl() && !*Suggested))
7138 *Suggested = Redecl;
7142 D = ED->getDefinition();
7143 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7144 if (auto *Pattern = FD->getTemplateInstantiationPattern())
7146 D = FD->getDefinition();
7147 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
7148 if (auto *Pattern = VD->getTemplateInstantiationPattern())
7150 D = VD->getDefinition();
7152 assert(D && "missing definition for pattern of instantiated definition");
7158 // The external source may have additional definitions of this entity that are
7159 // visible, so complete the redeclaration chain now and ask again.
7160 if (auto *Source = Context.getExternalSource()) {
7161 Source->CompleteRedeclChain(D);
7162 return isVisible(D);
7168 /// Locks in the inheritance model for the given class and all of its bases.
7169 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
7170 RD = RD->getMostRecentDecl();
7171 if (!RD->hasAttr<MSInheritanceAttr>()) {
7172 MSInheritanceAttr::Spelling IM;
7174 switch (S.MSPointerToMemberRepresentationMethod) {
7175 case LangOptions::PPTMK_BestCase:
7176 IM = RD->calculateInheritanceModel();
7178 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
7179 IM = MSInheritanceAttr::Keyword_single_inheritance;
7181 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
7182 IM = MSInheritanceAttr::Keyword_multiple_inheritance;
7184 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
7185 IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
7189 RD->addAttr(MSInheritanceAttr::CreateImplicit(
7190 S.getASTContext(), IM,
7191 /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
7192 LangOptions::PPTMK_BestCase,
7193 S.ImplicitMSInheritanceAttrLoc.isValid()
7194 ? S.ImplicitMSInheritanceAttrLoc
7195 : RD->getSourceRange()));
7196 S.Consumer.AssignInheritanceModel(RD);
7200 /// \brief The implementation of RequireCompleteType
7201 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
7202 TypeDiagnoser *Diagnoser) {
7203 // FIXME: Add this assertion to make sure we always get instantiation points.
7204 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
7205 // FIXME: Add this assertion to help us flush out problems with
7206 // checking for dependent types and type-dependent expressions.
7208 // assert(!T->isDependentType() &&
7209 // "Can't ask whether a dependent type is complete");
7211 // We lock in the inheritance model once somebody has asked us to ensure
7212 // that a pointer-to-member type is complete.
7213 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7214 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
7215 if (!MPTy->getClass()->isDependentType()) {
7216 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
7217 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
7222 NamedDecl *Def = nullptr;
7223 bool Incomplete = T->isIncompleteType(&Def);
7225 // Check that any necessary explicit specializations are visible. For an
7226 // enum, we just need the declaration, so don't check this.
7227 if (Def && !isa<EnumDecl>(Def))
7228 checkSpecializationVisibility(Loc, Def);
7230 // If we have a complete type, we're done.
7232 // If we know about the definition but it is not visible, complain.
7233 NamedDecl *SuggestedDef = nullptr;
7235 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
7236 // If the user is going to see an error here, recover by making the
7237 // definition visible.
7238 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
7240 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
7241 /*Recover*/TreatAsComplete);
7242 return !TreatAsComplete;
7248 const TagType *Tag = T->getAs<TagType>();
7249 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
7251 // If there's an unimported definition of this type in a module (for
7252 // instance, because we forward declared it, then imported the definition),
7253 // import that definition now.
7255 // FIXME: What about other cases where an import extends a redeclaration
7256 // chain for a declaration that can be accessed through a mechanism other
7257 // than name lookup (eg, referenced in a template, or a variable whose type
7258 // could be completed by the module)?
7260 // FIXME: Should we map through to the base array element type before
7261 // checking for a tag type?
7264 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
7266 // Avoid diagnosing invalid decls as incomplete.
7267 if (D->isInvalidDecl())
7270 // Give the external AST source a chance to complete the type.
7271 if (auto *Source = Context.getExternalSource()) {
7273 Source->CompleteType(Tag->getDecl());
7275 Source->CompleteType(IFace->getDecl());
7277 // If the external source completed the type, go through the motions
7278 // again to ensure we're allowed to use the completed type.
7279 if (!T->isIncompleteType())
7280 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7284 // If we have a class template specialization or a class member of a
7285 // class template specialization, or an array with known size of such,
7286 // try to instantiate it.
7287 QualType MaybeTemplate = T;
7288 while (const ConstantArrayType *Array
7289 = Context.getAsConstantArrayType(MaybeTemplate))
7290 MaybeTemplate = Array->getElementType();
7291 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
7292 bool Instantiated = false;
7293 bool Diagnosed = false;
7294 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
7295 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
7296 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
7297 Diagnosed = InstantiateClassTemplateSpecialization(
7298 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
7299 /*Complain=*/Diagnoser);
7300 Instantiated = true;
7302 } else if (CXXRecordDecl *Rec
7303 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
7304 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
7305 if (!Rec->isBeingDefined() && Pattern) {
7306 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
7307 assert(MSI && "Missing member specialization information?");
7308 // This record was instantiated from a class within a template.
7309 if (MSI->getTemplateSpecializationKind() !=
7310 TSK_ExplicitSpecialization) {
7311 Diagnosed = InstantiateClass(Loc, Rec, Pattern,
7312 getTemplateInstantiationArgs(Rec),
7313 TSK_ImplicitInstantiation,
7314 /*Complain=*/Diagnoser);
7315 Instantiated = true;
7321 // Instantiate* might have already complained that the template is not
7322 // defined, if we asked it to.
7323 if (Diagnoser && Diagnosed)
7325 // If we instantiated a definition, check that it's usable, even if
7326 // instantiation produced an error, so that repeated calls to this
7327 // function give consistent answers.
7328 if (!T->isIncompleteType())
7329 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7333 // FIXME: If we didn't instantiate a definition because of an explicit
7334 // specialization declaration, check that it's visible.
7339 Diagnoser->diagnose(*this, Loc, T);
7341 // If the type was a forward declaration of a class/struct/union
7342 // type, produce a note.
7343 if (Tag && !Tag->getDecl()->isInvalidDecl())
7344 Diag(Tag->getDecl()->getLocation(),
7345 Tag->isBeingDefined() ? diag::note_type_being_defined
7346 : diag::note_forward_declaration)
7347 << QualType(Tag, 0);
7349 // If the Objective-C class was a forward declaration, produce a note.
7350 if (IFace && !IFace->getDecl()->isInvalidDecl())
7351 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
7353 // If we have external information that we can use to suggest a fix,
7356 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
7361 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7363 BoundTypeDiagnoser<> Diagnoser(DiagID);
7364 return RequireCompleteType(Loc, T, Diagnoser);
7367 /// \brief Get diagnostic %select index for tag kind for
7368 /// literal type diagnostic message.
7369 /// WARNING: Indexes apply to particular diagnostics only!
7371 /// \returns diagnostic %select index.
7372 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
7374 case TTK_Struct: return 0;
7375 case TTK_Interface: return 1;
7376 case TTK_Class: return 2;
7377 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
7381 /// @brief Ensure that the type T is a literal type.
7383 /// This routine checks whether the type @p T is a literal type. If @p T is an
7384 /// incomplete type, an attempt is made to complete it. If @p T is a literal
7385 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
7386 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
7387 /// it the type @p T), along with notes explaining why the type is not a
7388 /// literal type, and returns true.
7390 /// @param Loc The location in the source that the non-literal type
7391 /// diagnostic should refer to.
7393 /// @param T The type that this routine is examining for literalness.
7395 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
7397 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
7398 /// @c false otherwise.
7399 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
7400 TypeDiagnoser &Diagnoser) {
7401 assert(!T->isDependentType() && "type should not be dependent");
7403 QualType ElemType = Context.getBaseElementType(T);
7404 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
7405 T->isLiteralType(Context))
7408 Diagnoser.diagnose(*this, Loc, T);
7410 if (T->isVariableArrayType())
7413 const RecordType *RT = ElemType->getAs<RecordType>();
7417 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7419 // A partially-defined class type can't be a literal type, because a literal
7420 // class type must have a trivial destructor (which can't be checked until
7421 // the class definition is complete).
7422 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
7425 // If the class has virtual base classes, then it's not an aggregate, and
7426 // cannot have any constexpr constructors or a trivial default constructor,
7427 // so is non-literal. This is better to diagnose than the resulting absence
7428 // of constexpr constructors.
7429 if (RD->getNumVBases()) {
7430 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
7431 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
7432 for (const auto &I : RD->vbases())
7433 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
7434 << I.getSourceRange();
7435 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
7436 !RD->hasTrivialDefaultConstructor()) {
7437 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
7438 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
7439 for (const auto &I : RD->bases()) {
7440 if (!I.getType()->isLiteralType(Context)) {
7441 Diag(I.getLocStart(),
7442 diag::note_non_literal_base_class)
7443 << RD << I.getType() << I.getSourceRange();
7447 for (const auto *I : RD->fields()) {
7448 if (!I->getType()->isLiteralType(Context) ||
7449 I->getType().isVolatileQualified()) {
7450 Diag(I->getLocation(), diag::note_non_literal_field)
7451 << RD << I << I->getType()
7452 << I->getType().isVolatileQualified();
7456 } else if (!RD->hasTrivialDestructor()) {
7457 // All fields and bases are of literal types, so have trivial destructors.
7458 // If this class's destructor is non-trivial it must be user-declared.
7459 CXXDestructorDecl *Dtor = RD->getDestructor();
7460 assert(Dtor && "class has literal fields and bases but no dtor?");
7464 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
7465 diag::note_non_literal_user_provided_dtor :
7466 diag::note_non_literal_nontrivial_dtor) << RD;
7467 if (!Dtor->isUserProvided())
7468 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
7474 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
7475 BoundTypeDiagnoser<> Diagnoser(DiagID);
7476 return RequireLiteralType(Loc, T, Diagnoser);
7479 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
7480 /// and qualified by the nested-name-specifier contained in SS.
7481 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
7482 const CXXScopeSpec &SS, QualType T) {
7485 NestedNameSpecifier *NNS;
7487 NNS = SS.getScopeRep();
7489 if (Keyword == ETK_None)
7493 return Context.getElaboratedType(Keyword, NNS, T);
7496 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
7497 ExprResult ER = CheckPlaceholderExpr(E);
7498 if (ER.isInvalid()) return QualType();
7501 if (!getLangOpts().CPlusPlus && E->refersToBitField())
7502 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
7504 if (!E->isTypeDependent()) {
7505 QualType T = E->getType();
7506 if (const TagType *TT = T->getAs<TagType>())
7507 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
7509 return Context.getTypeOfExprType(E);
7512 /// getDecltypeForExpr - Given an expr, will return the decltype for
7513 /// that expression, according to the rules in C++11
7514 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
7515 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
7516 if (E->isTypeDependent())
7517 return S.Context.DependentTy;
7519 // C++11 [dcl.type.simple]p4:
7520 // The type denoted by decltype(e) is defined as follows:
7522 // - if e is an unparenthesized id-expression or an unparenthesized class
7523 // member access (5.2.5), decltype(e) is the type of the entity named
7524 // by e. If there is no such entity, or if e names a set of overloaded
7525 // functions, the program is ill-formed;
7527 // We apply the same rules for Objective-C ivar and property references.
7528 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7529 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
7530 return VD->getType();
7531 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7532 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
7533 return FD->getType();
7534 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
7535 return IR->getDecl()->getType();
7536 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
7537 if (PR->isExplicitProperty())
7538 return PR->getExplicitProperty()->getType();
7539 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
7540 return PE->getType();
7543 // C++11 [expr.lambda.prim]p18:
7544 // Every occurrence of decltype((x)) where x is a possibly
7545 // parenthesized id-expression that names an entity of automatic
7546 // storage duration is treated as if x were transformed into an
7547 // access to a corresponding data member of the closure type that
7548 // would have been declared if x were an odr-use of the denoted
7550 using namespace sema;
7551 if (S.getCurLambda()) {
7552 if (isa<ParenExpr>(E)) {
7553 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7554 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7555 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
7557 return S.Context.getLValueReferenceType(T);
7564 // C++11 [dcl.type.simple]p4:
7566 QualType T = E->getType();
7567 switch (E->getValueKind()) {
7568 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
7570 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
7571 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
7573 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
7574 // - otherwise, decltype(e) is the type of e.
7575 case VK_RValue: break;
7581 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
7582 bool AsUnevaluated) {
7583 ExprResult ER = CheckPlaceholderExpr(E);
7584 if (ER.isInvalid()) return QualType();
7587 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
7588 E->HasSideEffects(Context, false)) {
7589 // The expression operand for decltype is in an unevaluated expression
7590 // context, so side effects could result in unintended consequences.
7591 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7594 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
7597 QualType Sema::BuildUnaryTransformType(QualType BaseType,
7598 UnaryTransformType::UTTKind UKind,
7599 SourceLocation Loc) {
7601 case UnaryTransformType::EnumUnderlyingType:
7602 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
7603 Diag(Loc, diag::err_only_enums_have_underlying_types);
7606 QualType Underlying = BaseType;
7607 if (!BaseType->isDependentType()) {
7608 // The enum could be incomplete if we're parsing its definition or
7609 // recovering from an error.
7610 NamedDecl *FwdDecl = nullptr;
7611 if (BaseType->isIncompleteType(&FwdDecl)) {
7612 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
7613 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
7617 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
7618 assert(ED && "EnumType has no EnumDecl");
7620 DiagnoseUseOfDecl(ED, Loc);
7622 Underlying = ED->getIntegerType();
7623 assert(!Underlying.isNull());
7625 return Context.getUnaryTransformType(BaseType, Underlying,
7626 UnaryTransformType::EnumUnderlyingType);
7629 llvm_unreachable("unknown unary transform type");
7632 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
7633 if (!T->isDependentType()) {
7634 // FIXME: It isn't entirely clear whether incomplete atomic types
7635 // are allowed or not; for simplicity, ban them for the moment.
7636 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
7639 int DisallowedKind = -1;
7640 if (T->isArrayType())
7642 else if (T->isFunctionType())
7644 else if (T->isReferenceType())
7646 else if (T->isAtomicType())
7648 else if (T.hasQualifiers())
7650 else if (!T.isTriviallyCopyableType(Context))
7651 // Some other non-trivially-copyable type (probably a C++ class)
7654 if (DisallowedKind != -1) {
7655 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
7659 // FIXME: Do we need any handling for ARC here?
7662 // Build the pointer type.
7663 return Context.getAtomicType(T);