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)
648 FUNCTION_TYPE_ATTRS_CASELIST:
649 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
652 MS_TYPE_ATTRS_CASELIST:
653 // Microsoft type attributes cannot go after the declarator-id.
656 NULLABILITY_TYPE_ATTRS_CASELIST:
657 // Nullability specifiers cannot go after the declarator-id.
659 // Objective-C __kindof does not get distributed.
660 case AttributeList::AT_ObjCKindOf:
666 } while ((attr = next));
669 /// Add a synthetic '()' to a block-literal declarator if it is
670 /// required, given the return type.
671 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
672 QualType declSpecType) {
673 Declarator &declarator = state.getDeclarator();
675 // First, check whether the declarator would produce a function,
676 // i.e. whether the innermost semantic chunk is a function.
677 if (declarator.isFunctionDeclarator()) {
678 // If so, make that declarator a prototyped declarator.
679 declarator.getFunctionTypeInfo().hasPrototype = true;
683 // If there are any type objects, the type as written won't name a
684 // function, regardless of the decl spec type. This is because a
685 // block signature declarator is always an abstract-declarator, and
686 // abstract-declarators can't just be parentheses chunks. Therefore
687 // we need to build a function chunk unless there are no type
688 // objects and the decl spec type is a function.
689 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
692 // Note that there *are* cases with invalid declarators where
693 // declarators consist solely of parentheses. In general, these
694 // occur only in failed efforts to make function declarators, so
695 // faking up the function chunk is still the right thing to do.
697 // Otherwise, we need to fake up a function declarator.
698 SourceLocation loc = declarator.getLocStart();
700 // ...and *prepend* it to the declarator.
701 SourceLocation NoLoc;
702 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
704 /*IsAmbiguous=*/false,
708 /*EllipsisLoc=*/NoLoc,
711 /*RefQualifierIsLvalueRef=*/true,
712 /*RefQualifierLoc=*/NoLoc,
713 /*ConstQualifierLoc=*/NoLoc,
714 /*VolatileQualifierLoc=*/NoLoc,
715 /*RestrictQualifierLoc=*/NoLoc,
716 /*MutableLoc=*/NoLoc, EST_None,
717 /*ESpecRange=*/SourceRange(),
718 /*Exceptions=*/nullptr,
719 /*ExceptionRanges=*/nullptr,
721 /*NoexceptExpr=*/nullptr,
722 /*ExceptionSpecTokens=*/nullptr,
723 /*DeclsInPrototype=*/None,
724 loc, loc, declarator));
726 // For consistency, make sure the state still has us as processing
728 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
729 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
732 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
737 // If this occurs outside a template instantiation, warn the user about
738 // it; they probably didn't mean to specify a redundant qualifier.
739 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
740 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
741 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
742 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
743 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
744 if (!(RemoveTQs & Qual.first))
747 if (!S.inTemplateInstantiation()) {
748 if (TypeQuals & Qual.first)
749 S.Diag(Qual.second, DiagID)
750 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
751 << FixItHint::CreateRemoval(Qual.second);
754 TypeQuals &= ~Qual.first;
758 /// Return true if this is omitted block return type. Also check type
759 /// attributes and type qualifiers when returning true.
760 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
762 if (!isOmittedBlockReturnType(declarator))
765 // Warn if we see type attributes for omitted return type on a block literal.
766 AttributeList *&attrs =
767 declarator.getMutableDeclSpec().getAttributes().getListRef();
768 AttributeList *prev = nullptr;
769 for (AttributeList *cur = attrs; cur; cur = cur->getNext()) {
770 AttributeList &attr = *cur;
771 // Skip attributes that were marked to be invalid or non-type
773 if (attr.isInvalid() || !attr.isTypeAttr()) {
777 S.Diag(attr.getLoc(),
778 diag::warn_block_literal_attributes_on_omitted_return_type)
780 // Remove cur from the list.
782 prev->setNext(cur->getNext());
785 attrs = cur->getNext();
789 // Warn if we see type qualifiers for omitted return type on a block literal.
790 const DeclSpec &DS = declarator.getDeclSpec();
791 unsigned TypeQuals = DS.getTypeQualifiers();
792 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
793 diag::warn_block_literal_qualifiers_on_omitted_return_type);
794 declarator.getMutableDeclSpec().ClearTypeQualifiers();
799 /// Apply Objective-C type arguments to the given type.
800 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
801 ArrayRef<TypeSourceInfo *> typeArgs,
802 SourceRange typeArgsRange,
803 bool failOnError = false) {
804 // We can only apply type arguments to an Objective-C class type.
805 const auto *objcObjectType = type->getAs<ObjCObjectType>();
806 if (!objcObjectType || !objcObjectType->getInterface()) {
807 S.Diag(loc, diag::err_objc_type_args_non_class)
816 // The class type must be parameterized.
817 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
818 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
820 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
821 << objcClass->getDeclName()
822 << FixItHint::CreateRemoval(typeArgsRange);
830 // The type must not already be specialized.
831 if (objcObjectType->isSpecialized()) {
832 S.Diag(loc, diag::err_objc_type_args_specialized_class)
834 << FixItHint::CreateRemoval(typeArgsRange);
842 // Check the type arguments.
843 SmallVector<QualType, 4> finalTypeArgs;
844 unsigned numTypeParams = typeParams->size();
845 bool anyPackExpansions = false;
846 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
847 TypeSourceInfo *typeArgInfo = typeArgs[i];
848 QualType typeArg = typeArgInfo->getType();
850 // Type arguments cannot have explicit qualifiers or nullability.
851 // We ignore indirect sources of these, e.g. behind typedefs or
852 // template arguments.
853 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
854 bool diagnosed = false;
855 SourceRange rangeToRemove;
856 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
857 rangeToRemove = attr.getLocalSourceRange();
858 if (attr.getTypePtr()->getImmediateNullability()) {
859 typeArg = attr.getTypePtr()->getModifiedType();
860 S.Diag(attr.getLocStart(),
861 diag::err_objc_type_arg_explicit_nullability)
862 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
868 S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified)
869 << typeArg << typeArg.getQualifiers().getAsString()
870 << FixItHint::CreateRemoval(rangeToRemove);
874 // Remove qualifiers even if they're non-local.
875 typeArg = typeArg.getUnqualifiedType();
877 finalTypeArgs.push_back(typeArg);
879 if (typeArg->getAs<PackExpansionType>())
880 anyPackExpansions = true;
882 // Find the corresponding type parameter, if there is one.
883 ObjCTypeParamDecl *typeParam = nullptr;
884 if (!anyPackExpansions) {
885 if (i < numTypeParams) {
886 typeParam = typeParams->begin()[i];
888 // Too many arguments.
889 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
891 << objcClass->getDeclName()
892 << (unsigned)typeArgs.size()
894 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
904 // Objective-C object pointer types must be substitutable for the bounds.
905 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
906 // If we don't have a type parameter to match against, assume
907 // everything is fine. There was a prior pack expansion that
908 // means we won't be able to match anything.
910 assert(anyPackExpansions && "Too many arguments?");
914 // Retrieve the bound.
915 QualType bound = typeParam->getUnderlyingType();
916 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
918 // Determine whether the type argument is substitutable for the bound.
919 if (typeArgObjC->isObjCIdType()) {
920 // When the type argument is 'id', the only acceptable type
921 // parameter bound is 'id'.
922 if (boundObjC->isObjCIdType())
924 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
925 // Otherwise, we follow the assignability rules.
929 // Diagnose the mismatch.
930 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
931 diag::err_objc_type_arg_does_not_match_bound)
932 << typeArg << bound << typeParam->getDeclName();
933 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
934 << typeParam->getDeclName();
942 // Block pointer types are permitted for unqualified 'id' bounds.
943 if (typeArg->isBlockPointerType()) {
944 // If we don't have a type parameter to match against, assume
945 // everything is fine. There was a prior pack expansion that
946 // means we won't be able to match anything.
948 assert(anyPackExpansions && "Too many arguments?");
952 // Retrieve the bound.
953 QualType bound = typeParam->getUnderlyingType();
954 if (bound->isBlockCompatibleObjCPointerType(S.Context))
957 // Diagnose the mismatch.
958 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
959 diag::err_objc_type_arg_does_not_match_bound)
960 << typeArg << bound << typeParam->getDeclName();
961 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
962 << typeParam->getDeclName();
970 // Dependent types will be checked at instantiation time.
971 if (typeArg->isDependentType()) {
975 // Diagnose non-id-compatible type arguments.
976 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
977 diag::err_objc_type_arg_not_id_compatible)
979 << typeArgInfo->getTypeLoc().getSourceRange();
987 // Make sure we didn't have the wrong number of arguments.
988 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
989 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
990 << (typeArgs.size() < typeParams->size())
991 << objcClass->getDeclName()
992 << (unsigned)finalTypeArgs.size()
993 << (unsigned)numTypeParams;
994 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1003 // Success. Form the specialized type.
1004 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1007 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1008 SourceLocation ProtocolLAngleLoc,
1009 ArrayRef<ObjCProtocolDecl *> Protocols,
1010 ArrayRef<SourceLocation> ProtocolLocs,
1011 SourceLocation ProtocolRAngleLoc,
1013 QualType Result = QualType(Decl->getTypeForDecl(), 0);
1014 if (!Protocols.empty()) {
1016 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1019 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1020 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1021 if (FailOnError) Result = QualType();
1023 if (FailOnError && Result.isNull())
1030 QualType Sema::BuildObjCObjectType(QualType BaseType,
1032 SourceLocation TypeArgsLAngleLoc,
1033 ArrayRef<TypeSourceInfo *> TypeArgs,
1034 SourceLocation TypeArgsRAngleLoc,
1035 SourceLocation ProtocolLAngleLoc,
1036 ArrayRef<ObjCProtocolDecl *> Protocols,
1037 ArrayRef<SourceLocation> ProtocolLocs,
1038 SourceLocation ProtocolRAngleLoc,
1040 QualType Result = BaseType;
1041 if (!TypeArgs.empty()) {
1042 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1043 SourceRange(TypeArgsLAngleLoc,
1046 if (FailOnError && Result.isNull())
1050 if (!Protocols.empty()) {
1052 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1055 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1056 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1057 if (FailOnError) Result = QualType();
1059 if (FailOnError && Result.isNull())
1066 TypeResult Sema::actOnObjCProtocolQualifierType(
1067 SourceLocation lAngleLoc,
1068 ArrayRef<Decl *> protocols,
1069 ArrayRef<SourceLocation> protocolLocs,
1070 SourceLocation rAngleLoc) {
1071 // Form id<protocol-list>.
1072 QualType Result = Context.getObjCObjectType(
1073 Context.ObjCBuiltinIdTy, { },
1075 (ObjCProtocolDecl * const *)protocols.data(),
1078 Result = Context.getObjCObjectPointerType(Result);
1080 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1081 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1083 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1084 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1086 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1087 .castAs<ObjCObjectTypeLoc>();
1088 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1089 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1091 // No type arguments.
1092 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1093 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1095 // Fill in protocol qualifiers.
1096 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1097 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1098 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1099 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1101 // We're done. Return the completed type to the parser.
1102 return CreateParsedType(Result, ResultTInfo);
1105 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1108 ParsedType BaseType,
1109 SourceLocation TypeArgsLAngleLoc,
1110 ArrayRef<ParsedType> TypeArgs,
1111 SourceLocation TypeArgsRAngleLoc,
1112 SourceLocation ProtocolLAngleLoc,
1113 ArrayRef<Decl *> Protocols,
1114 ArrayRef<SourceLocation> ProtocolLocs,
1115 SourceLocation ProtocolRAngleLoc) {
1116 TypeSourceInfo *BaseTypeInfo = nullptr;
1117 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1121 // Handle missing type-source info.
1123 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1125 // Extract type arguments.
1126 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1127 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1128 TypeSourceInfo *TypeArgInfo = nullptr;
1129 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1130 if (TypeArg.isNull()) {
1131 ActualTypeArgInfos.clear();
1135 assert(TypeArgInfo && "No type source info?");
1136 ActualTypeArgInfos.push_back(TypeArgInfo);
1139 // Build the object type.
1140 QualType Result = BuildObjCObjectType(
1141 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1142 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1144 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1146 ProtocolLocs, ProtocolRAngleLoc,
1147 /*FailOnError=*/false);
1152 // Create source information for this type.
1153 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1154 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1156 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1157 // object pointer type. Fill in source information for it.
1158 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1159 // The '*' is implicit.
1160 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1161 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1164 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1165 // Protocol qualifier information.
1166 if (OTPTL.getNumProtocols() > 0) {
1167 assert(OTPTL.getNumProtocols() == Protocols.size());
1168 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1169 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1170 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1171 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1174 // We're done. Return the completed type to the parser.
1175 return CreateParsedType(Result, ResultTInfo);
1178 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1180 // Type argument information.
1181 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1182 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1183 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1184 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1185 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1186 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1188 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1189 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1192 // Protocol qualifier information.
1193 if (ObjCObjectTL.getNumProtocols() > 0) {
1194 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1195 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1196 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1197 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1198 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1200 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1201 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1205 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1206 if (ObjCObjectTL.getType() == T)
1207 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1209 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1211 // We're done. Return the completed type to the parser.
1212 return CreateParsedType(Result, ResultTInfo);
1215 static OpenCLAccessAttr::Spelling getImageAccess(const AttributeList *Attrs) {
1217 const AttributeList *Next = Attrs;
1219 const AttributeList &Attr = *Next;
1220 Next = Attr.getNext();
1221 if (Attr.getKind() == AttributeList::AT_OpenCLAccess) {
1222 return static_cast<OpenCLAccessAttr::Spelling>(
1223 Attr.getSemanticSpelling());
1227 return OpenCLAccessAttr::Keyword_read_only;
1230 /// \brief Convert the specified declspec to the appropriate type
1232 /// \param state Specifies the declarator containing the declaration specifier
1233 /// to be converted, along with other associated processing state.
1234 /// \returns The type described by the declaration specifiers. This function
1235 /// never returns null.
1236 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1237 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1240 Sema &S = state.getSema();
1241 Declarator &declarator = state.getDeclarator();
1242 const DeclSpec &DS = declarator.getDeclSpec();
1243 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1244 if (DeclLoc.isInvalid())
1245 DeclLoc = DS.getLocStart();
1247 ASTContext &Context = S.Context;
1250 switch (DS.getTypeSpecType()) {
1251 case DeclSpec::TST_void:
1252 Result = Context.VoidTy;
1254 case DeclSpec::TST_char:
1255 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1256 Result = Context.CharTy;
1257 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1258 Result = Context.SignedCharTy;
1260 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1261 "Unknown TSS value");
1262 Result = Context.UnsignedCharTy;
1265 case DeclSpec::TST_wchar:
1266 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1267 Result = Context.WCharTy;
1268 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1269 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1270 << DS.getSpecifierName(DS.getTypeSpecType(),
1271 Context.getPrintingPolicy());
1272 Result = Context.getSignedWCharType();
1274 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1275 "Unknown TSS value");
1276 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1277 << DS.getSpecifierName(DS.getTypeSpecType(),
1278 Context.getPrintingPolicy());
1279 Result = Context.getUnsignedWCharType();
1282 case DeclSpec::TST_char16:
1283 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1284 "Unknown TSS value");
1285 Result = Context.Char16Ty;
1287 case DeclSpec::TST_char32:
1288 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1289 "Unknown TSS value");
1290 Result = Context.Char32Ty;
1292 case DeclSpec::TST_unspecified:
1293 // If this is a missing declspec in a block literal return context, then it
1294 // is inferred from the return statements inside the block.
1295 // The declspec is always missing in a lambda expr context; it is either
1296 // specified with a trailing return type or inferred.
1297 if (S.getLangOpts().CPlusPlus14 &&
1298 declarator.getContext() == Declarator::LambdaExprContext) {
1299 // In C++1y, a lambda's implicit return type is 'auto'.
1300 Result = Context.getAutoDeductType();
1302 } else if (declarator.getContext() == Declarator::LambdaExprContext ||
1303 checkOmittedBlockReturnType(S, declarator,
1304 Context.DependentTy)) {
1305 Result = Context.DependentTy;
1309 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1310 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1311 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1312 // Note that the one exception to this is function definitions, which are
1313 // allowed to be completely missing a declspec. This is handled in the
1314 // parser already though by it pretending to have seen an 'int' in this
1316 if (S.getLangOpts().ImplicitInt) {
1317 // In C89 mode, we only warn if there is a completely missing declspec
1318 // when one is not allowed.
1320 S.Diag(DeclLoc, diag::ext_missing_declspec)
1321 << DS.getSourceRange()
1322 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
1324 } else if (!DS.hasTypeSpecifier()) {
1325 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1326 // "At least one type specifier shall be given in the declaration
1327 // specifiers in each declaration, and in the specifier-qualifier list in
1328 // each struct declaration and type name."
1329 if (S.getLangOpts().CPlusPlus) {
1330 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1331 << DS.getSourceRange();
1333 // When this occurs in C++ code, often something is very broken with the
1334 // value being declared, poison it as invalid so we don't get chains of
1336 declarator.setInvalidType(true);
1337 } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1338 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1339 << DS.getSourceRange();
1340 declarator.setInvalidType(true);
1342 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1343 << DS.getSourceRange();
1348 case DeclSpec::TST_int: {
1349 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
1350 switch (DS.getTypeSpecWidth()) {
1351 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1352 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
1353 case DeclSpec::TSW_long: Result = Context.LongTy; break;
1354 case DeclSpec::TSW_longlong:
1355 Result = Context.LongLongTy;
1357 // 'long long' is a C99 or C++11 feature.
1358 if (!S.getLangOpts().C99) {
1359 if (S.getLangOpts().CPlusPlus)
1360 S.Diag(DS.getTypeSpecWidthLoc(),
1361 S.getLangOpts().CPlusPlus11 ?
1362 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1364 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1369 switch (DS.getTypeSpecWidth()) {
1370 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1371 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
1372 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
1373 case DeclSpec::TSW_longlong:
1374 Result = Context.UnsignedLongLongTy;
1376 // 'long long' is a C99 or C++11 feature.
1377 if (!S.getLangOpts().C99) {
1378 if (S.getLangOpts().CPlusPlus)
1379 S.Diag(DS.getTypeSpecWidthLoc(),
1380 S.getLangOpts().CPlusPlus11 ?
1381 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1383 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1390 case DeclSpec::TST_int128:
1391 if (!S.Context.getTargetInfo().hasInt128Type())
1392 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1394 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1395 Result = Context.UnsignedInt128Ty;
1397 Result = Context.Int128Ty;
1399 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1400 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1401 case DeclSpec::TST_double:
1402 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1403 Result = Context.LongDoubleTy;
1405 Result = Context.DoubleTy;
1407 case DeclSpec::TST_float128:
1408 if (!S.Context.getTargetInfo().hasFloat128Type())
1409 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1411 Result = Context.Float128Ty;
1413 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1415 case DeclSpec::TST_decimal32: // _Decimal32
1416 case DeclSpec::TST_decimal64: // _Decimal64
1417 case DeclSpec::TST_decimal128: // _Decimal128
1418 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1419 Result = Context.IntTy;
1420 declarator.setInvalidType(true);
1422 case DeclSpec::TST_class:
1423 case DeclSpec::TST_enum:
1424 case DeclSpec::TST_union:
1425 case DeclSpec::TST_struct:
1426 case DeclSpec::TST_interface: {
1427 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
1429 // This can happen in C++ with ambiguous lookups.
1430 Result = Context.IntTy;
1431 declarator.setInvalidType(true);
1435 // If the type is deprecated or unavailable, diagnose it.
1436 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1438 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1439 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1441 // TypeQuals handled by caller.
1442 Result = Context.getTypeDeclType(D);
1444 // In both C and C++, make an ElaboratedType.
1445 ElaboratedTypeKeyword Keyword
1446 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1447 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
1450 case DeclSpec::TST_typename: {
1451 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1452 DS.getTypeSpecSign() == 0 &&
1453 "Can't handle qualifiers on typedef names yet!");
1454 Result = S.GetTypeFromParser(DS.getRepAsType());
1455 if (Result.isNull()) {
1456 declarator.setInvalidType(true);
1459 // TypeQuals handled by caller.
1462 case DeclSpec::TST_typeofType:
1463 // FIXME: Preserve type source info.
1464 Result = S.GetTypeFromParser(DS.getRepAsType());
1465 assert(!Result.isNull() && "Didn't get a type for typeof?");
1466 if (!Result->isDependentType())
1467 if (const TagType *TT = Result->getAs<TagType>())
1468 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1469 // TypeQuals handled by caller.
1470 Result = Context.getTypeOfType(Result);
1472 case DeclSpec::TST_typeofExpr: {
1473 Expr *E = DS.getRepAsExpr();
1474 assert(E && "Didn't get an expression for typeof?");
1475 // TypeQuals handled by caller.
1476 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1477 if (Result.isNull()) {
1478 Result = Context.IntTy;
1479 declarator.setInvalidType(true);
1483 case DeclSpec::TST_decltype: {
1484 Expr *E = DS.getRepAsExpr();
1485 assert(E && "Didn't get an expression for decltype?");
1486 // TypeQuals handled by caller.
1487 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1488 if (Result.isNull()) {
1489 Result = Context.IntTy;
1490 declarator.setInvalidType(true);
1494 case DeclSpec::TST_underlyingType:
1495 Result = S.GetTypeFromParser(DS.getRepAsType());
1496 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1497 Result = S.BuildUnaryTransformType(Result,
1498 UnaryTransformType::EnumUnderlyingType,
1499 DS.getTypeSpecTypeLoc());
1500 if (Result.isNull()) {
1501 Result = Context.IntTy;
1502 declarator.setInvalidType(true);
1506 case DeclSpec::TST_auto:
1507 Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1510 case DeclSpec::TST_auto_type:
1511 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1514 case DeclSpec::TST_decltype_auto:
1515 Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1516 /*IsDependent*/ false);
1519 case DeclSpec::TST_unknown_anytype:
1520 Result = Context.UnknownAnyTy;
1523 case DeclSpec::TST_atomic:
1524 Result = S.GetTypeFromParser(DS.getRepAsType());
1525 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1526 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1527 if (Result.isNull()) {
1528 Result = Context.IntTy;
1529 declarator.setInvalidType(true);
1533 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1534 case DeclSpec::TST_##ImgType##_t: \
1535 switch (getImageAccess(DS.getAttributes().getList())) { \
1536 case OpenCLAccessAttr::Keyword_write_only: \
1537 Result = Context.Id##WOTy; break; \
1538 case OpenCLAccessAttr::Keyword_read_write: \
1539 Result = Context.Id##RWTy; break; \
1540 case OpenCLAccessAttr::Keyword_read_only: \
1541 Result = Context.Id##ROTy; break; \
1544 #include "clang/Basic/OpenCLImageTypes.def"
1546 case DeclSpec::TST_error:
1547 Result = Context.IntTy;
1548 declarator.setInvalidType(true);
1552 if (S.getLangOpts().OpenCL &&
1553 S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
1554 declarator.setInvalidType(true);
1556 // Handle complex types.
1557 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1558 if (S.getLangOpts().Freestanding)
1559 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1560 Result = Context.getComplexType(Result);
1561 } else if (DS.isTypeAltiVecVector()) {
1562 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1563 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1564 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1565 if (DS.isTypeAltiVecPixel())
1566 VecKind = VectorType::AltiVecPixel;
1567 else if (DS.isTypeAltiVecBool())
1568 VecKind = VectorType::AltiVecBool;
1569 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1572 // FIXME: Imaginary.
1573 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1574 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1576 // Before we process any type attributes, synthesize a block literal
1577 // function declarator if necessary.
1578 if (declarator.getContext() == Declarator::BlockLiteralContext)
1579 maybeSynthesizeBlockSignature(state, Result);
1581 // Apply any type attributes from the decl spec. This may cause the
1582 // list of type attributes to be temporarily saved while the type
1583 // attributes are pushed around.
1584 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1585 if (!DS.isTypeSpecPipe())
1586 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList());
1588 // Apply const/volatile/restrict qualifiers to T.
1589 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1590 // Warn about CV qualifiers on function types.
1592 // If the specification of a function type includes any type qualifiers,
1593 // the behavior is undefined.
1594 // C++11 [dcl.fct]p7:
1595 // The effect of a cv-qualifier-seq in a function declarator is not the
1596 // same as adding cv-qualification on top of the function type. In the
1597 // latter case, the cv-qualifiers are ignored.
1598 if (TypeQuals && Result->isFunctionType()) {
1599 diagnoseAndRemoveTypeQualifiers(
1600 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1601 S.getLangOpts().CPlusPlus
1602 ? diag::warn_typecheck_function_qualifiers_ignored
1603 : diag::warn_typecheck_function_qualifiers_unspecified);
1604 // No diagnostic for 'restrict' or '_Atomic' applied to a
1605 // function type; we'll diagnose those later, in BuildQualifiedType.
1608 // C++11 [dcl.ref]p1:
1609 // Cv-qualified references are ill-formed except when the
1610 // cv-qualifiers are introduced through the use of a typedef-name
1611 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1613 // There don't appear to be any other contexts in which a cv-qualified
1614 // reference type could be formed, so the 'ill-formed' clause here appears
1616 if (TypeQuals && Result->isReferenceType()) {
1617 diagnoseAndRemoveTypeQualifiers(
1618 S, DS, TypeQuals, Result,
1619 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1620 diag::warn_typecheck_reference_qualifiers);
1623 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1624 // than once in the same specifier-list or qualifier-list, either directly
1625 // or via one or more typedefs."
1626 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1627 && TypeQuals & Result.getCVRQualifiers()) {
1628 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1629 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1633 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1634 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1638 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1639 // produce a warning in this case.
1642 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1644 // If adding qualifiers fails, just use the unqualified type.
1645 if (Qualified.isNull())
1646 declarator.setInvalidType(true);
1651 assert(!Result.isNull() && "This function should not return a null type");
1655 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1657 return Entity.getAsString();
1662 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1663 Qualifiers Qs, const DeclSpec *DS) {
1667 // Ignore any attempt to form a cv-qualified reference.
1668 if (T->isReferenceType()) {
1670 Qs.removeVolatile();
1673 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1674 // object or incomplete types shall not be restrict-qualified."
1675 if (Qs.hasRestrict()) {
1676 unsigned DiagID = 0;
1679 if (T->isAnyPointerType() || T->isReferenceType() ||
1680 T->isMemberPointerType()) {
1682 if (T->isObjCObjectPointerType())
1684 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1685 EltTy = PTy->getPointeeType();
1687 EltTy = T->getPointeeType();
1689 // If we have a pointer or reference, the pointee must have an object
1691 if (!EltTy->isIncompleteOrObjectType()) {
1692 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1695 } else if (!T->isDependentType()) {
1696 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1701 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1702 Qs.removeRestrict();
1706 return Context.getQualifiedType(T, Qs);
1709 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1710 unsigned CVRAU, const DeclSpec *DS) {
1714 // Ignore any attempt to form a cv-qualified reference.
1715 if (T->isReferenceType())
1717 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1719 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1721 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1724 // If the same qualifier appears more than once in the same
1725 // specifier-qualifier-list, either directly or via one or more typedefs,
1726 // the behavior is the same as if it appeared only once.
1728 // It's not specified what happens when the _Atomic qualifier is applied to
1729 // a type specified with the _Atomic specifier, but we assume that this
1730 // should be treated as if the _Atomic qualifier appeared multiple times.
1731 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1733 // If other qualifiers appear along with the _Atomic qualifier in a
1734 // specifier-qualifier-list, the resulting type is the so-qualified
1737 // Don't need to worry about array types here, since _Atomic can't be
1738 // applied to such types.
1739 SplitQualType Split = T.getSplitUnqualifiedType();
1740 T = BuildAtomicType(QualType(Split.Ty, 0),
1741 DS ? DS->getAtomicSpecLoc() : Loc);
1744 Split.Quals.addCVRQualifiers(CVR);
1745 return BuildQualifiedType(T, Loc, Split.Quals);
1748 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1749 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1750 return BuildQualifiedType(T, Loc, Q, DS);
1753 /// \brief Build a paren type including \p T.
1754 QualType Sema::BuildParenType(QualType T) {
1755 return Context.getParenType(T);
1758 /// Given that we're building a pointer or reference to the given
1759 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1762 // Bail out if retention is unrequired or already specified.
1763 if (!type->isObjCLifetimeType() ||
1764 type.getObjCLifetime() != Qualifiers::OCL_None)
1767 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1769 // If the object type is const-qualified, we can safely use
1770 // __unsafe_unretained. This is safe (because there are no read
1771 // barriers), and it'll be safe to coerce anything but __weak* to
1772 // the resulting type.
1773 if (type.isConstQualified()) {
1774 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1776 // Otherwise, check whether the static type does not require
1777 // retaining. This currently only triggers for Class (possibly
1778 // protocol-qualifed, and arrays thereof).
1779 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1780 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1782 // If we are in an unevaluated context, like sizeof, skip adding a
1784 } else if (S.isUnevaluatedContext()) {
1787 // If that failed, give an error and recover using __strong. __strong
1788 // is the option most likely to prevent spurious second-order diagnostics,
1789 // like when binding a reference to a field.
1791 // These types can show up in private ivars in system headers, so
1792 // we need this to not be an error in those cases. Instead we
1794 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1795 S.DelayedDiagnostics.add(
1796 sema::DelayedDiagnostic::makeForbiddenType(loc,
1797 diag::err_arc_indirect_no_ownership, type, isReference));
1799 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1801 implicitLifetime = Qualifiers::OCL_Strong;
1803 assert(implicitLifetime && "didn't infer any lifetime!");
1806 qs.addObjCLifetime(implicitLifetime);
1807 return S.Context.getQualifiedType(type, qs);
1810 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1812 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1814 switch (FnTy->getRefQualifier()) {
1835 /// Kinds of declarator that cannot contain a qualified function type.
1837 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1838 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1839 /// at the topmost level of a type.
1841 /// Parens and member pointers are permitted. We don't diagnose array and
1842 /// function declarators, because they don't allow function types at all.
1844 /// The values of this enum are used in diagnostics.
1845 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1846 } // end anonymous namespace
1848 /// Check whether the type T is a qualified function type, and if it is,
1849 /// diagnose that it cannot be contained within the given kind of declarator.
1850 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1851 QualifiedFunctionKind QFK) {
1852 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1853 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1854 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1857 S.Diag(Loc, diag::err_compound_qualified_function_type)
1858 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1859 << getFunctionQualifiersAsString(FPT);
1863 /// \brief Build a pointer type.
1865 /// \param T The type to which we'll be building a pointer.
1867 /// \param Loc The location of the entity whose type involves this
1868 /// pointer type or, if there is no such entity, the location of the
1869 /// type that will have pointer type.
1871 /// \param Entity The name of the entity that involves the pointer
1874 /// \returns A suitable pointer type, if there are no
1875 /// errors. Otherwise, returns a NULL type.
1876 QualType Sema::BuildPointerType(QualType T,
1877 SourceLocation Loc, DeclarationName Entity) {
1878 if (T->isReferenceType()) {
1879 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1880 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1881 << getPrintableNameForEntity(Entity) << T;
1885 if (T->isFunctionType() && getLangOpts().OpenCL) {
1886 Diag(Loc, diag::err_opencl_function_pointer);
1890 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1893 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1895 // In ARC, it is forbidden to build pointers to unqualified pointers.
1896 if (getLangOpts().ObjCAutoRefCount)
1897 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1899 // Build the pointer type.
1900 return Context.getPointerType(T);
1903 /// \brief Build a reference type.
1905 /// \param T The type to which we'll be building a reference.
1907 /// \param Loc The location of the entity whose type involves this
1908 /// reference type or, if there is no such entity, the location of the
1909 /// type that will have reference type.
1911 /// \param Entity The name of the entity that involves the reference
1914 /// \returns A suitable reference type, if there are no
1915 /// errors. Otherwise, returns a NULL type.
1916 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1918 DeclarationName Entity) {
1919 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1920 "Unresolved overloaded function type");
1922 // C++0x [dcl.ref]p6:
1923 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1924 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1925 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1926 // the type "lvalue reference to T", while an attempt to create the type
1927 // "rvalue reference to cv TR" creates the type TR.
1928 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1930 // C++ [dcl.ref]p4: There shall be no references to references.
1932 // According to C++ DR 106, references to references are only
1933 // diagnosed when they are written directly (e.g., "int & &"),
1934 // but not when they happen via a typedef:
1936 // typedef int& intref;
1937 // typedef intref& intref2;
1939 // Parser::ParseDeclaratorInternal diagnoses the case where
1940 // references are written directly; here, we handle the
1941 // collapsing of references-to-references as described in C++0x.
1942 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1945 // A declarator that specifies the type "reference to cv void"
1947 if (T->isVoidType()) {
1948 Diag(Loc, diag::err_reference_to_void);
1952 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1955 // In ARC, it is forbidden to build references to unqualified pointers.
1956 if (getLangOpts().ObjCAutoRefCount)
1957 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1959 // Handle restrict on references.
1961 return Context.getLValueReferenceType(T, SpelledAsLValue);
1962 return Context.getRValueReferenceType(T);
1965 /// \brief Build a Read-only Pipe type.
1967 /// \param T The type to which we'll be building a Pipe.
1969 /// \param Loc We do not use it for now.
1971 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1973 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
1974 return Context.getReadPipeType(T);
1977 /// \brief Build a Write-only Pipe type.
1979 /// \param T The type to which we'll be building a Pipe.
1981 /// \param Loc We do not use it for now.
1983 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1985 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
1986 return Context.getWritePipeType(T);
1989 /// Check whether the specified array size makes the array type a VLA. If so,
1990 /// return true, if not, return the size of the array in SizeVal.
1991 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1992 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1993 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1994 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1996 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1998 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
2001 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
2002 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2006 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2007 S.LangOpts.GNUMode ||
2008 S.LangOpts.OpenCL).isInvalid();
2011 /// \brief Build an array type.
2013 /// \param T The type of each element in the array.
2015 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2017 /// \param ArraySize Expression describing the size of the array.
2019 /// \param Brackets The range from the opening '[' to the closing ']'.
2021 /// \param Entity The name of the entity that involves the array
2024 /// \returns A suitable array type, if there are no errors. Otherwise,
2025 /// returns a NULL type.
2026 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2027 Expr *ArraySize, unsigned Quals,
2028 SourceRange Brackets, DeclarationName Entity) {
2030 SourceLocation Loc = Brackets.getBegin();
2031 if (getLangOpts().CPlusPlus) {
2032 // C++ [dcl.array]p1:
2033 // T is called the array element type; this type shall not be a reference
2034 // type, the (possibly cv-qualified) type void, a function type or an
2035 // abstract class type.
2037 // C++ [dcl.array]p3:
2038 // When several "array of" specifications are adjacent, [...] only the
2039 // first of the constant expressions that specify the bounds of the arrays
2042 // Note: function types are handled in the common path with C.
2043 if (T->isReferenceType()) {
2044 Diag(Loc, diag::err_illegal_decl_array_of_references)
2045 << getPrintableNameForEntity(Entity) << T;
2049 if (T->isVoidType() || T->isIncompleteArrayType()) {
2050 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2054 if (RequireNonAbstractType(Brackets.getBegin(), T,
2055 diag::err_array_of_abstract_type))
2058 // Mentioning a member pointer type for an array type causes us to lock in
2059 // an inheritance model, even if it's inside an unused typedef.
2060 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2061 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2062 if (!MPTy->getClass()->isDependentType())
2063 (void)isCompleteType(Loc, T);
2066 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2067 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2068 if (RequireCompleteType(Loc, T,
2069 diag::err_illegal_decl_array_incomplete_type))
2073 if (T->isFunctionType()) {
2074 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2075 << getPrintableNameForEntity(Entity) << T;
2079 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2080 // If the element type is a struct or union that contains a variadic
2081 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2082 if (EltTy->getDecl()->hasFlexibleArrayMember())
2083 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2084 } else if (T->isObjCObjectType()) {
2085 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2089 // Do placeholder conversions on the array size expression.
2090 if (ArraySize && ArraySize->hasPlaceholderType()) {
2091 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2092 if (Result.isInvalid()) return QualType();
2093 ArraySize = Result.get();
2096 // Do lvalue-to-rvalue conversions on the array size expression.
2097 if (ArraySize && !ArraySize->isRValue()) {
2098 ExprResult Result = DefaultLvalueConversion(ArraySize);
2099 if (Result.isInvalid())
2102 ArraySize = Result.get();
2105 // C99 6.7.5.2p1: The size expression shall have integer type.
2106 // C++11 allows contextual conversions to such types.
2107 if (!getLangOpts().CPlusPlus11 &&
2108 ArraySize && !ArraySize->isTypeDependent() &&
2109 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2110 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2111 << ArraySize->getType() << ArraySize->getSourceRange();
2115 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2117 if (ASM == ArrayType::Star)
2118 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2120 T = Context.getIncompleteArrayType(T, ASM, Quals);
2121 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2122 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2123 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2124 !T->isConstantSizeType()) ||
2125 isArraySizeVLA(*this, ArraySize, ConstVal)) {
2126 // Even in C++11, don't allow contextual conversions in the array bound
2128 if (getLangOpts().CPlusPlus11 &&
2129 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2130 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2131 << ArraySize->getType() << ArraySize->getSourceRange();
2135 // C99: an array with an element type that has a non-constant-size is a VLA.
2136 // C99: an array with a non-ICE size is a VLA. We accept any expression
2137 // that we can fold to a non-zero positive value as an extension.
2138 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2140 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2141 // have a value greater than zero.
2142 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2144 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2145 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2147 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2148 << ArraySize->getSourceRange();
2151 if (ConstVal == 0) {
2152 // GCC accepts zero sized static arrays. We allow them when
2153 // we're not in a SFINAE context.
2154 Diag(ArraySize->getLocStart(),
2155 isSFINAEContext()? diag::err_typecheck_zero_array_size
2156 : diag::ext_typecheck_zero_array_size)
2157 << ArraySize->getSourceRange();
2159 if (ASM == ArrayType::Static) {
2160 Diag(ArraySize->getLocStart(),
2161 diag::warn_typecheck_zero_static_array_size)
2162 << ArraySize->getSourceRange();
2163 ASM = ArrayType::Normal;
2165 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2166 !T->isIncompleteType() && !T->isUndeducedType()) {
2167 // Is the array too large?
2168 unsigned ActiveSizeBits
2169 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2170 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2171 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2172 << ConstVal.toString(10)
2173 << ArraySize->getSourceRange();
2178 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2181 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2182 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2183 Diag(Loc, diag::err_opencl_vla);
2186 // CUDA device code doesn't support VLAs.
2187 if (getLangOpts().CUDA && T->isVariableArrayType())
2188 CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget();
2190 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2191 if (!getLangOpts().C99) {
2192 if (T->isVariableArrayType()) {
2193 // Prohibit the use of VLAs during template argument deduction.
2194 if (isSFINAEContext()) {
2195 Diag(Loc, diag::err_vla_in_sfinae);
2198 // Just extwarn about VLAs.
2200 Diag(Loc, diag::ext_vla);
2201 } else if (ASM != ArrayType::Normal || Quals != 0)
2203 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2204 : diag::ext_c99_array_usage) << ASM;
2207 if (T->isVariableArrayType()) {
2208 // Warn about VLAs for -Wvla.
2209 Diag(Loc, diag::warn_vla_used);
2212 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2213 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2214 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2215 if (getLangOpts().OpenCL) {
2216 const QualType ArrType = Context.getBaseElementType(T);
2217 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2218 ArrType->isSamplerT() || ArrType->isImageType()) {
2219 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2227 /// \brief Build an ext-vector type.
2229 /// Run the required checks for the extended vector type.
2230 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2231 SourceLocation AttrLoc) {
2232 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2233 // in conjunction with complex types (pointers, arrays, functions, etc.).
2235 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2236 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2237 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2238 // of bool aren't allowed.
2239 if ((!T->isDependentType() && !T->isIntegerType() &&
2240 !T->isRealFloatingType()) ||
2241 T->isBooleanType()) {
2242 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2246 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2247 llvm::APSInt vecSize(32);
2248 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2249 Diag(AttrLoc, diag::err_attribute_argument_type)
2250 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2251 << ArraySize->getSourceRange();
2255 // Unlike gcc's vector_size attribute, the size is specified as the
2256 // number of elements, not the number of bytes.
2257 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2259 if (vectorSize == 0) {
2260 Diag(AttrLoc, diag::err_attribute_zero_size)
2261 << ArraySize->getSourceRange();
2265 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2266 Diag(AttrLoc, diag::err_attribute_size_too_large)
2267 << ArraySize->getSourceRange();
2271 return Context.getExtVectorType(T, vectorSize);
2274 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2277 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2278 if (T->isArrayType() || T->isFunctionType()) {
2279 Diag(Loc, diag::err_func_returning_array_function)
2280 << T->isFunctionType() << T;
2284 // Functions cannot return half FP.
2285 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2286 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2287 FixItHint::CreateInsertion(Loc, "*");
2291 // Methods cannot return interface types. All ObjC objects are
2292 // passed by reference.
2293 if (T->isObjCObjectType()) {
2294 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2295 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2302 /// Check the extended parameter information. Most of the necessary
2303 /// checking should occur when applying the parameter attribute; the
2304 /// only other checks required are positional restrictions.
2305 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2306 const FunctionProtoType::ExtProtoInfo &EPI,
2307 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2308 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2310 bool hasCheckedSwiftCall = false;
2311 auto checkForSwiftCC = [&](unsigned paramIndex) {
2312 // Only do this once.
2313 if (hasCheckedSwiftCall) return;
2314 hasCheckedSwiftCall = true;
2315 if (EPI.ExtInfo.getCC() == CC_Swift) return;
2316 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2317 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2320 for (size_t paramIndex = 0, numParams = paramTypes.size();
2321 paramIndex != numParams; ++paramIndex) {
2322 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2323 // Nothing interesting to check for orindary-ABI parameters.
2324 case ParameterABI::Ordinary:
2327 // swift_indirect_result parameters must be a prefix of the function
2329 case ParameterABI::SwiftIndirectResult:
2330 checkForSwiftCC(paramIndex);
2331 if (paramIndex != 0 &&
2332 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2333 != ParameterABI::SwiftIndirectResult) {
2334 S.Diag(getParamLoc(paramIndex),
2335 diag::err_swift_indirect_result_not_first);
2339 case ParameterABI::SwiftContext:
2340 checkForSwiftCC(paramIndex);
2343 // swift_error parameters must be preceded by a swift_context parameter.
2344 case ParameterABI::SwiftErrorResult:
2345 checkForSwiftCC(paramIndex);
2346 if (paramIndex == 0 ||
2347 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2348 ParameterABI::SwiftContext) {
2349 S.Diag(getParamLoc(paramIndex),
2350 diag::err_swift_error_result_not_after_swift_context);
2354 llvm_unreachable("bad ABI kind");
2358 QualType Sema::BuildFunctionType(QualType T,
2359 MutableArrayRef<QualType> ParamTypes,
2360 SourceLocation Loc, DeclarationName Entity,
2361 const FunctionProtoType::ExtProtoInfo &EPI) {
2362 bool Invalid = false;
2364 Invalid |= CheckFunctionReturnType(T, Loc);
2366 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2367 // FIXME: Loc is too inprecise here, should use proper locations for args.
2368 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2369 if (ParamType->isVoidType()) {
2370 Diag(Loc, diag::err_param_with_void_type);
2372 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2373 // Disallow half FP arguments.
2374 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2375 FixItHint::CreateInsertion(Loc, "*");
2379 ParamTypes[Idx] = ParamType;
2382 if (EPI.ExtParameterInfos) {
2383 checkExtParameterInfos(*this, ParamTypes, EPI,
2384 [=](unsigned i) { return Loc; });
2390 return Context.getFunctionType(T, ParamTypes, EPI);
2393 /// \brief Build a member pointer type \c T Class::*.
2395 /// \param T the type to which the member pointer refers.
2396 /// \param Class the class type into which the member pointer points.
2397 /// \param Loc the location where this type begins
2398 /// \param Entity the name of the entity that will have this member pointer type
2400 /// \returns a member pointer type, if successful, or a NULL type if there was
2402 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2404 DeclarationName Entity) {
2405 // Verify that we're not building a pointer to pointer to function with
2406 // exception specification.
2407 if (CheckDistantExceptionSpec(T)) {
2408 Diag(Loc, diag::err_distant_exception_spec);
2412 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2413 // with reference type, or "cv void."
2414 if (T->isReferenceType()) {
2415 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2416 << getPrintableNameForEntity(Entity) << T;
2420 if (T->isVoidType()) {
2421 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2422 << getPrintableNameForEntity(Entity);
2426 if (!Class->isDependentType() && !Class->isRecordType()) {
2427 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2431 // Adjust the default free function calling convention to the default method
2432 // calling convention.
2434 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2435 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2436 if (T->isFunctionType())
2437 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2439 return Context.getMemberPointerType(T, Class.getTypePtr());
2442 /// \brief Build a block pointer type.
2444 /// \param T The type to which we'll be building a block pointer.
2446 /// \param Loc The source location, used for diagnostics.
2448 /// \param Entity The name of the entity that involves the block pointer
2451 /// \returns A suitable block pointer type, if there are no
2452 /// errors. Otherwise, returns a NULL type.
2453 QualType Sema::BuildBlockPointerType(QualType T,
2455 DeclarationName Entity) {
2456 if (!T->isFunctionType()) {
2457 Diag(Loc, diag::err_nonfunction_block_type);
2461 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2464 return Context.getBlockPointerType(T);
2467 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2468 QualType QT = Ty.get();
2470 if (TInfo) *TInfo = nullptr;
2474 TypeSourceInfo *DI = nullptr;
2475 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2476 QT = LIT->getType();
2477 DI = LIT->getTypeSourceInfo();
2480 if (TInfo) *TInfo = DI;
2484 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2485 Qualifiers::ObjCLifetime ownership,
2486 unsigned chunkIndex);
2488 /// Given that this is the declaration of a parameter under ARC,
2489 /// attempt to infer attributes and such for pointer-to-whatever
2491 static void inferARCWriteback(TypeProcessingState &state,
2492 QualType &declSpecType) {
2493 Sema &S = state.getSema();
2494 Declarator &declarator = state.getDeclarator();
2496 // TODO: should we care about decl qualifiers?
2498 // Check whether the declarator has the expected form. We walk
2499 // from the inside out in order to make the block logic work.
2500 unsigned outermostPointerIndex = 0;
2501 bool isBlockPointer = false;
2502 unsigned numPointers = 0;
2503 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2504 unsigned chunkIndex = i;
2505 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2506 switch (chunk.Kind) {
2507 case DeclaratorChunk::Paren:
2511 case DeclaratorChunk::Reference:
2512 case DeclaratorChunk::Pointer:
2513 // Count the number of pointers. Treat references
2514 // interchangeably as pointers; if they're mis-ordered, normal
2515 // type building will discover that.
2516 outermostPointerIndex = chunkIndex;
2520 case DeclaratorChunk::BlockPointer:
2521 // If we have a pointer to block pointer, that's an acceptable
2522 // indirect reference; anything else is not an application of
2524 if (numPointers != 1) return;
2526 outermostPointerIndex = chunkIndex;
2527 isBlockPointer = true;
2529 // We don't care about pointer structure in return values here.
2532 case DeclaratorChunk::Array: // suppress if written (id[])?
2533 case DeclaratorChunk::Function:
2534 case DeclaratorChunk::MemberPointer:
2535 case DeclaratorChunk::Pipe:
2541 // If we have *one* pointer, then we want to throw the qualifier on
2542 // the declaration-specifiers, which means that it needs to be a
2543 // retainable object type.
2544 if (numPointers == 1) {
2545 // If it's not a retainable object type, the rule doesn't apply.
2546 if (!declSpecType->isObjCRetainableType()) return;
2548 // If it already has lifetime, don't do anything.
2549 if (declSpecType.getObjCLifetime()) return;
2551 // Otherwise, modify the type in-place.
2554 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2555 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2557 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2558 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2560 // If we have *two* pointers, then we want to throw the qualifier on
2561 // the outermost pointer.
2562 } else if (numPointers == 2) {
2563 // If we don't have a block pointer, we need to check whether the
2564 // declaration-specifiers gave us something that will turn into a
2565 // retainable object pointer after we slap the first pointer on it.
2566 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2569 // Look for an explicit lifetime attribute there.
2570 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2571 if (chunk.Kind != DeclaratorChunk::Pointer &&
2572 chunk.Kind != DeclaratorChunk::BlockPointer)
2574 for (const AttributeList *attr = chunk.getAttrs(); attr;
2575 attr = attr->getNext())
2576 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2579 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2580 outermostPointerIndex);
2582 // Any other number of pointers/references does not trigger the rule.
2585 // TODO: mark whether we did this inference?
2588 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2589 SourceLocation FallbackLoc,
2590 SourceLocation ConstQualLoc,
2591 SourceLocation VolatileQualLoc,
2592 SourceLocation RestrictQualLoc,
2593 SourceLocation AtomicQualLoc,
2594 SourceLocation UnalignedQualLoc) {
2602 } const QualKinds[5] = {
2603 { "const", DeclSpec::TQ_const, ConstQualLoc },
2604 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2605 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2606 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2607 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2610 SmallString<32> QualStr;
2611 unsigned NumQuals = 0;
2613 FixItHint FixIts[5];
2615 // Build a string naming the redundant qualifiers.
2616 for (auto &E : QualKinds) {
2617 if (Quals & E.Mask) {
2618 if (!QualStr.empty()) QualStr += ' ';
2621 // If we have a location for the qualifier, offer a fixit.
2622 SourceLocation QualLoc = E.Loc;
2623 if (QualLoc.isValid()) {
2624 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2625 if (Loc.isInvalid() ||
2626 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2634 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2635 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2638 // Diagnose pointless type qualifiers on the return type of a function.
2639 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2641 unsigned FunctionChunkIndex) {
2642 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2643 // FIXME: TypeSourceInfo doesn't preserve location information for
2645 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2646 RetTy.getLocalCVRQualifiers(),
2647 D.getIdentifierLoc());
2651 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2652 End = D.getNumTypeObjects();
2653 OuterChunkIndex != End; ++OuterChunkIndex) {
2654 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2655 switch (OuterChunk.Kind) {
2656 case DeclaratorChunk::Paren:
2659 case DeclaratorChunk::Pointer: {
2660 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2661 S.diagnoseIgnoredQualifiers(
2662 diag::warn_qual_return_type,
2665 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2666 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2667 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2668 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
2669 SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
2673 case DeclaratorChunk::Function:
2674 case DeclaratorChunk::BlockPointer:
2675 case DeclaratorChunk::Reference:
2676 case DeclaratorChunk::Array:
2677 case DeclaratorChunk::MemberPointer:
2678 case DeclaratorChunk::Pipe:
2679 // FIXME: We can't currently provide an accurate source location and a
2680 // fix-it hint for these.
2681 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2682 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2683 RetTy.getCVRQualifiers() | AtomicQual,
2684 D.getIdentifierLoc());
2688 llvm_unreachable("unknown declarator chunk kind");
2691 // If the qualifiers come from a conversion function type, don't diagnose
2692 // them -- they're not necessarily redundant, since such a conversion
2693 // operator can be explicitly called as "x.operator const int()".
2694 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2697 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2698 // which are present there.
2699 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2700 D.getDeclSpec().getTypeQualifiers(),
2701 D.getIdentifierLoc(),
2702 D.getDeclSpec().getConstSpecLoc(),
2703 D.getDeclSpec().getVolatileSpecLoc(),
2704 D.getDeclSpec().getRestrictSpecLoc(),
2705 D.getDeclSpec().getAtomicSpecLoc(),
2706 D.getDeclSpec().getUnalignedSpecLoc());
2709 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2710 TypeSourceInfo *&ReturnTypeInfo) {
2711 Sema &SemaRef = state.getSema();
2712 Declarator &D = state.getDeclarator();
2714 ReturnTypeInfo = nullptr;
2716 // The TagDecl owned by the DeclSpec.
2717 TagDecl *OwnedTagDecl = nullptr;
2719 switch (D.getName().getKind()) {
2720 case UnqualifiedId::IK_ImplicitSelfParam:
2721 case UnqualifiedId::IK_OperatorFunctionId:
2722 case UnqualifiedId::IK_Identifier:
2723 case UnqualifiedId::IK_LiteralOperatorId:
2724 case UnqualifiedId::IK_TemplateId:
2725 T = ConvertDeclSpecToType(state);
2727 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2728 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2729 // Owned declaration is embedded in declarator.
2730 OwnedTagDecl->setEmbeddedInDeclarator(true);
2734 case UnqualifiedId::IK_ConstructorName:
2735 case UnqualifiedId::IK_ConstructorTemplateId:
2736 case UnqualifiedId::IK_DestructorName:
2737 // Constructors and destructors don't have return types. Use
2739 T = SemaRef.Context.VoidTy;
2740 processTypeAttrs(state, T, TAL_DeclSpec,
2741 D.getDeclSpec().getAttributes().getList());
2744 case UnqualifiedId::IK_DeductionGuideName:
2745 // Deduction guides have a trailing return type and no type in their
2746 // decl-specifier sequence. Use a placeholder return type for now.
2747 T = SemaRef.Context.DependentTy;
2750 case UnqualifiedId::IK_ConversionFunctionId:
2751 // The result type of a conversion function is the type that it
2753 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2758 if (D.getAttributes())
2759 distributeTypeAttrsFromDeclarator(state, T);
2761 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2762 if (DeducedType *Deduced = T->getContainedDeducedType()) {
2763 AutoType *Auto = dyn_cast<AutoType>(Deduced);
2766 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
2767 // class template argument deduction)?
2768 bool IsCXXAutoType =
2769 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
2771 switch (D.getContext()) {
2772 case Declarator::LambdaExprContext:
2773 // Declared return type of a lambda-declarator is implicit and is always
2776 case Declarator::ObjCParameterContext:
2777 case Declarator::ObjCResultContext:
2778 case Declarator::PrototypeContext:
2781 case Declarator::LambdaExprParameterContext:
2782 // In C++14, generic lambdas allow 'auto' in their parameters.
2783 if (!SemaRef.getLangOpts().CPlusPlus14 ||
2784 !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto)
2787 // If auto is mentioned in a lambda parameter context, convert it to a
2788 // template parameter type.
2789 sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda();
2790 assert(LSI && "No LambdaScopeInfo on the stack!");
2791 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
2792 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
2793 const bool IsParameterPack = D.hasEllipsis();
2795 // Create the TemplateTypeParmDecl here to retrieve the corresponding
2796 // template parameter type. Template parameters are temporarily added
2797 // to the TU until the associated TemplateDecl is created.
2798 TemplateTypeParmDecl *CorrespondingTemplateParam =
2799 TemplateTypeParmDecl::Create(
2800 SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(),
2801 /*KeyLoc*/SourceLocation(), /*NameLoc*/D.getLocStart(),
2802 TemplateParameterDepth, AutoParameterPosition,
2803 /*Identifier*/nullptr, false, IsParameterPack);
2804 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
2805 // Replace the 'auto' in the function parameter with this invented
2806 // template type parameter.
2807 // FIXME: Retain some type sugar to indicate that this was written
2809 T = SemaRef.ReplaceAutoType(
2810 T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
2813 case Declarator::MemberContext: {
2814 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2815 D.isFunctionDeclarator())
2817 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2818 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2819 case TTK_Enum: llvm_unreachable("unhandled tag kind");
2820 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2821 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
2822 case TTK_Class: Error = 5; /* Class member */ break;
2823 case TTK_Interface: Error = 6; /* Interface member */ break;
2825 if (D.getDeclSpec().isFriendSpecified())
2826 Error = 20; // Friend type
2829 case Declarator::CXXCatchContext:
2830 case Declarator::ObjCCatchContext:
2831 Error = 7; // Exception declaration
2833 case Declarator::TemplateParamContext:
2834 if (isa<DeducedTemplateSpecializationType>(Deduced))
2835 Error = 19; // Template parameter
2836 else if (!SemaRef.getLangOpts().CPlusPlus1z)
2837 Error = 8; // Template parameter (until C++1z)
2839 case Declarator::BlockLiteralContext:
2840 Error = 9; // Block literal
2842 case Declarator::TemplateTypeArgContext:
2843 Error = 10; // Template type argument
2845 case Declarator::AliasDeclContext:
2846 case Declarator::AliasTemplateContext:
2847 Error = 12; // Type alias
2849 case Declarator::TrailingReturnContext:
2850 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2851 Error = 13; // Function return type
2853 case Declarator::ConversionIdContext:
2854 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2855 Error = 14; // conversion-type-id
2857 case Declarator::FunctionalCastContext:
2858 if (isa<DeducedTemplateSpecializationType>(Deduced))
2861 case Declarator::TypeNameContext:
2862 Error = 15; // Generic
2864 case Declarator::FileContext:
2865 case Declarator::BlockContext:
2866 case Declarator::ForContext:
2867 case Declarator::InitStmtContext:
2868 case Declarator::ConditionContext:
2869 // FIXME: P0091R3 (erroneously) does not permit class template argument
2870 // deduction in conditions, for-init-statements, and other declarations
2871 // that are not simple-declarations.
2873 case Declarator::CXXNewContext:
2874 // FIXME: P0091R3 does not permit class template argument deduction here,
2875 // but we follow GCC and allow it anyway.
2876 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
2877 Error = 17; // 'new' type
2879 case Declarator::KNRTypeListContext:
2880 Error = 18; // K&R function parameter
2884 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2887 // In Objective-C it is an error to use 'auto' on a function declarator
2888 // (and everywhere for '__auto_type').
2889 if (D.isFunctionDeclarator() &&
2890 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
2893 bool HaveTrailing = false;
2895 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2896 // contains a trailing return type. That is only legal at the outermost
2897 // level. Check all declarator chunks (outermost first) anyway, to give
2898 // better diagnostics.
2899 // We don't support '__auto_type' with trailing return types.
2900 // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
2901 if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
2902 D.hasTrailingReturnType()) {
2903 HaveTrailing = true;
2907 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2908 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2909 AutoRange = D.getName().getSourceRange();
2914 switch (Auto->getKeyword()) {
2915 case AutoTypeKeyword::Auto: Kind = 0; break;
2916 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
2917 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
2920 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
2921 "unknown auto type");
2925 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
2926 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
2928 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2929 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
2930 << QualType(Deduced, 0) << AutoRange;
2931 if (auto *TD = TN.getAsTemplateDecl())
2932 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
2934 T = SemaRef.Context.IntTy;
2935 D.setInvalidType(true);
2936 } else if (!HaveTrailing) {
2937 // If there was a trailing return type, we already got
2938 // warn_cxx98_compat_trailing_return_type in the parser.
2939 SemaRef.Diag(AutoRange.getBegin(),
2940 diag::warn_cxx98_compat_auto_type_specifier)
2945 if (SemaRef.getLangOpts().CPlusPlus &&
2946 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2947 // Check the contexts where C++ forbids the declaration of a new class
2948 // or enumeration in a type-specifier-seq.
2949 unsigned DiagID = 0;
2950 switch (D.getContext()) {
2951 case Declarator::TrailingReturnContext:
2952 // Class and enumeration definitions are syntactically not allowed in
2953 // trailing return types.
2954 llvm_unreachable("parser should not have allowed this");
2956 case Declarator::FileContext:
2957 case Declarator::MemberContext:
2958 case Declarator::BlockContext:
2959 case Declarator::ForContext:
2960 case Declarator::InitStmtContext:
2961 case Declarator::BlockLiteralContext:
2962 case Declarator::LambdaExprContext:
2963 // C++11 [dcl.type]p3:
2964 // A type-specifier-seq shall not define a class or enumeration unless
2965 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2966 // the declaration of a template-declaration.
2967 case Declarator::AliasDeclContext:
2969 case Declarator::AliasTemplateContext:
2970 DiagID = diag::err_type_defined_in_alias_template;
2972 case Declarator::TypeNameContext:
2973 case Declarator::FunctionalCastContext:
2974 case Declarator::ConversionIdContext:
2975 case Declarator::TemplateParamContext:
2976 case Declarator::CXXNewContext:
2977 case Declarator::CXXCatchContext:
2978 case Declarator::ObjCCatchContext:
2979 case Declarator::TemplateTypeArgContext:
2980 DiagID = diag::err_type_defined_in_type_specifier;
2982 case Declarator::PrototypeContext:
2983 case Declarator::LambdaExprParameterContext:
2984 case Declarator::ObjCParameterContext:
2985 case Declarator::ObjCResultContext:
2986 case Declarator::KNRTypeListContext:
2988 // Types shall not be defined in return or parameter types.
2989 DiagID = diag::err_type_defined_in_param_type;
2991 case Declarator::ConditionContext:
2993 // The type-specifier-seq shall not contain typedef and shall not declare
2994 // a new class or enumeration.
2995 DiagID = diag::err_type_defined_in_condition;
3000 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3001 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3002 D.setInvalidType(true);
3006 assert(!T.isNull() && "This function should not return a null type");
3010 /// Produce an appropriate diagnostic for an ambiguity between a function
3011 /// declarator and a C++ direct-initializer.
3012 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3013 DeclaratorChunk &DeclType, QualType RT) {
3014 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3015 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3017 // If the return type is void there is no ambiguity.
3018 if (RT->isVoidType())
3021 // An initializer for a non-class type can have at most one argument.
3022 if (!RT->isRecordType() && FTI.NumParams > 1)
3025 // An initializer for a reference must have exactly one argument.
3026 if (RT->isReferenceType() && FTI.NumParams != 1)
3029 // Only warn if this declarator is declaring a function at block scope, and
3030 // doesn't have a storage class (such as 'extern') specified.
3031 if (!D.isFunctionDeclarator() ||
3032 D.getFunctionDefinitionKind() != FDK_Declaration ||
3033 !S.CurContext->isFunctionOrMethod() ||
3034 D.getDeclSpec().getStorageClassSpec()
3035 != DeclSpec::SCS_unspecified)
3038 // Inside a condition, a direct initializer is not permitted. We allow one to
3039 // be parsed in order to give better diagnostics in condition parsing.
3040 if (D.getContext() == Declarator::ConditionContext)
3043 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3045 S.Diag(DeclType.Loc,
3046 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3047 : diag::warn_empty_parens_are_function_decl)
3050 // If the declaration looks like:
3053 // and name lookup finds a function named 'f', then the ',' was
3054 // probably intended to be a ';'.
3055 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3056 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3057 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3058 if (Comma.getFileID() != Name.getFileID() ||
3059 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3060 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3061 Sema::LookupOrdinaryName);
3062 if (S.LookupName(Result, S.getCurScope()))
3063 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3064 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3065 << D.getIdentifier();
3069 if (FTI.NumParams > 0) {
3070 // For a declaration with parameters, eg. "T var(T());", suggest adding
3071 // parens around the first parameter to turn the declaration into a
3072 // variable declaration.
3073 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3074 SourceLocation B = Range.getBegin();
3075 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3076 // FIXME: Maybe we should suggest adding braces instead of parens
3077 // in C++11 for classes that don't have an initializer_list constructor.
3078 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3079 << FixItHint::CreateInsertion(B, "(")
3080 << FixItHint::CreateInsertion(E, ")");
3082 // For a declaration without parameters, eg. "T var();", suggest replacing
3083 // the parens with an initializer to turn the declaration into a variable
3085 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3087 // Empty parens mean value-initialization, and no parens mean
3088 // default initialization. These are equivalent if the default
3089 // constructor is user-provided or if zero-initialization is a
3091 if (RD && RD->hasDefinition() &&
3092 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3093 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3094 << FixItHint::CreateRemoval(ParenRange);
3097 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3098 if (Init.empty() && S.LangOpts.CPlusPlus11)
3101 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3102 << FixItHint::CreateReplacement(ParenRange, Init);
3107 /// Helper for figuring out the default CC for a function declarator type. If
3108 /// this is the outermost chunk, then we can determine the CC from the
3109 /// declarator context. If not, then this could be either a member function
3110 /// type or normal function type.
3112 getCCForDeclaratorChunk(Sema &S, Declarator &D,
3113 const DeclaratorChunk::FunctionTypeInfo &FTI,
3114 unsigned ChunkIndex) {
3115 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3117 // Check for an explicit CC attribute.
3118 for (auto Attr = FTI.AttrList; Attr; Attr = Attr->getNext()) {
3119 switch (Attr->getKind()) {
3120 CALLING_CONV_ATTRS_CASELIST: {
3121 // Ignore attributes that don't validate or can't apply to the
3122 // function type. We'll diagnose the failure to apply them in
3123 // handleFunctionTypeAttr.
3125 if (!S.CheckCallingConvAttr(*Attr, CC) &&
3126 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3137 bool IsCXXInstanceMethod = false;
3139 if (S.getLangOpts().CPlusPlus) {
3140 // Look inwards through parentheses to see if this chunk will form a
3141 // member pointer type or if we're the declarator. Any type attributes
3142 // between here and there will override the CC we choose here.
3143 unsigned I = ChunkIndex;
3144 bool FoundNonParen = false;
3145 while (I && !FoundNonParen) {
3147 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3148 FoundNonParen = true;
3151 if (FoundNonParen) {
3152 // If we're not the declarator, we're a regular function type unless we're
3153 // in a member pointer.
3154 IsCXXInstanceMethod =
3155 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3156 } else if (D.getContext() == Declarator::LambdaExprContext) {
3157 // This can only be a call operator for a lambda, which is an instance
3159 IsCXXInstanceMethod = true;
3161 // We're the innermost decl chunk, so must be a function declarator.
3162 assert(D.isFunctionDeclarator());
3164 // If we're inside a record, we're declaring a method, but it could be
3165 // explicitly or implicitly static.
3166 IsCXXInstanceMethod =
3167 D.isFirstDeclarationOfMember() &&
3168 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3169 !D.isStaticMember();
3173 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3174 IsCXXInstanceMethod);
3176 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3177 // and AMDGPU targets, hence it cannot be treated as a calling
3178 // convention attribute. This is the simplest place to infer
3179 // calling convention for OpenCL kernels.
3180 if (S.getLangOpts().OpenCL) {
3181 for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
3182 Attr; Attr = Attr->getNext()) {
3183 if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
3184 CC = CC_OpenCLKernel;
3194 /// A simple notion of pointer kinds, which matches up with the various
3195 /// pointer declarators.
3196 enum class SimplePointerKind {
3202 } // end anonymous namespace
3204 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3205 switch (nullability) {
3206 case NullabilityKind::NonNull:
3207 if (!Ident__Nonnull)
3208 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3209 return Ident__Nonnull;
3211 case NullabilityKind::Nullable:
3212 if (!Ident__Nullable)
3213 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3214 return Ident__Nullable;
3216 case NullabilityKind::Unspecified:
3217 if (!Ident__Null_unspecified)
3218 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3219 return Ident__Null_unspecified;
3221 llvm_unreachable("Unknown nullability kind.");
3224 /// Retrieve the identifier "NSError".
3225 IdentifierInfo *Sema::getNSErrorIdent() {
3227 Ident_NSError = PP.getIdentifierInfo("NSError");
3229 return Ident_NSError;
3232 /// Check whether there is a nullability attribute of any kind in the given
3234 static bool hasNullabilityAttr(const AttributeList *attrs) {
3235 for (const AttributeList *attr = attrs; attr;
3236 attr = attr->getNext()) {
3237 if (attr->getKind() == AttributeList::AT_TypeNonNull ||
3238 attr->getKind() == AttributeList::AT_TypeNullable ||
3239 attr->getKind() == AttributeList::AT_TypeNullUnspecified)
3247 /// Describes the kind of a pointer a declarator describes.
3248 enum class PointerDeclaratorKind {
3251 // Single-level pointer.
3253 // Multi-level pointer (of any pointer kind).
3256 MaybePointerToCFRef,
3260 NSErrorPointerPointer,
3263 /// Describes a declarator chunk wrapping a pointer that marks inference as
3265 // These values must be kept in sync with diagnostics.
3266 enum class PointerWrappingDeclaratorKind {
3267 /// Pointer is top-level.
3269 /// Pointer is an array element.
3271 /// Pointer is the referent type of a C++ reference.
3274 } // end anonymous namespace
3276 /// Classify the given declarator, whose type-specified is \c type, based on
3277 /// what kind of pointer it refers to.
3279 /// This is used to determine the default nullability.
3280 static PointerDeclaratorKind
3281 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
3282 PointerWrappingDeclaratorKind &wrappingKind) {
3283 unsigned numNormalPointers = 0;
3285 // For any dependent type, we consider it a non-pointer.
3286 if (type->isDependentType())
3287 return PointerDeclaratorKind::NonPointer;
3289 // Look through the declarator chunks to identify pointers.
3290 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3291 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3292 switch (chunk.Kind) {
3293 case DeclaratorChunk::Array:
3294 if (numNormalPointers == 0)
3295 wrappingKind = PointerWrappingDeclaratorKind::Array;
3298 case DeclaratorChunk::Function:
3299 case DeclaratorChunk::Pipe:
3302 case DeclaratorChunk::BlockPointer:
3303 case DeclaratorChunk::MemberPointer:
3304 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3305 : PointerDeclaratorKind::SingleLevelPointer;
3307 case DeclaratorChunk::Paren:
3310 case DeclaratorChunk::Reference:
3311 if (numNormalPointers == 0)
3312 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3315 case DeclaratorChunk::Pointer:
3316 ++numNormalPointers;
3317 if (numNormalPointers > 2)
3318 return PointerDeclaratorKind::MultiLevelPointer;
3323 // Then, dig into the type specifier itself.
3324 unsigned numTypeSpecifierPointers = 0;
3326 // Decompose normal pointers.
3327 if (auto ptrType = type->getAs<PointerType>()) {
3328 ++numNormalPointers;
3330 if (numNormalPointers > 2)
3331 return PointerDeclaratorKind::MultiLevelPointer;
3333 type = ptrType->getPointeeType();
3334 ++numTypeSpecifierPointers;
3338 // Decompose block pointers.
3339 if (type->getAs<BlockPointerType>()) {
3340 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3341 : PointerDeclaratorKind::SingleLevelPointer;
3344 // Decompose member pointers.
3345 if (type->getAs<MemberPointerType>()) {
3346 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3347 : PointerDeclaratorKind::SingleLevelPointer;
3350 // Look at Objective-C object pointers.
3351 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3352 ++numNormalPointers;
3353 ++numTypeSpecifierPointers;
3355 // If this is NSError**, report that.
3356 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3357 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3358 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3359 return PointerDeclaratorKind::NSErrorPointerPointer;
3366 // Look at Objective-C class types.
3367 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3368 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3369 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3370 return PointerDeclaratorKind::NSErrorPointerPointer;
3376 // If at this point we haven't seen a pointer, we won't see one.
3377 if (numNormalPointers == 0)
3378 return PointerDeclaratorKind::NonPointer;
3380 if (auto recordType = type->getAs<RecordType>()) {
3381 RecordDecl *recordDecl = recordType->getDecl();
3383 bool isCFError = false;
3385 // If we already know about CFError, test it directly.
3386 isCFError = (S.CFError == recordDecl);
3388 // Check whether this is CFError, which we identify based on its bridge
3390 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3391 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) {
3392 if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) {
3393 S.CFError = recordDecl;
3400 // If this is CFErrorRef*, report it as such.
3401 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3402 return PointerDeclaratorKind::CFErrorRefPointer;
3410 switch (numNormalPointers) {
3412 return PointerDeclaratorKind::NonPointer;
3415 return PointerDeclaratorKind::SingleLevelPointer;
3418 return PointerDeclaratorKind::MaybePointerToCFRef;
3421 return PointerDeclaratorKind::MultiLevelPointer;
3425 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
3426 SourceLocation loc) {
3427 // If we're anywhere in a function, method, or closure context, don't perform
3428 // completeness checks.
3429 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3430 if (ctx->isFunctionOrMethod())
3433 if (ctx->isFileContext())
3437 // We only care about the expansion location.
3438 loc = S.SourceMgr.getExpansionLoc(loc);
3439 FileID file = S.SourceMgr.getFileID(loc);
3440 if (file.isInvalid())
3443 // Retrieve file information.
3444 bool invalid = false;
3445 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3446 if (invalid || !sloc.isFile())
3449 // We don't want to perform completeness checks on the main file or in
3451 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3452 if (fileInfo.getIncludeLoc().isInvalid())
3454 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3455 S.Diags.getSuppressSystemWarnings()) {
3462 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
3463 /// taking into account whitespace before and after.
3464 static void fixItNullability(Sema &S, DiagnosticBuilder &Diag,
3465 SourceLocation PointerLoc,
3466 NullabilityKind Nullability) {
3467 assert(PointerLoc.isValid());
3468 if (PointerLoc.isMacroID())
3471 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
3472 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
3475 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
3479 SmallString<32> InsertionTextBuf{" "};
3480 InsertionTextBuf += getNullabilitySpelling(Nullability);
3481 InsertionTextBuf += " ";
3482 StringRef InsertionText = InsertionTextBuf.str();
3484 if (isWhitespace(*NextChar)) {
3485 InsertionText = InsertionText.drop_back();
3486 } else if (NextChar[-1] == '[') {
3487 if (NextChar[0] == ']')
3488 InsertionText = InsertionText.drop_back().drop_front();
3490 InsertionText = InsertionText.drop_front();
3491 } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
3492 !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
3493 InsertionText = InsertionText.drop_back().drop_front();
3496 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
3499 static void emitNullabilityConsistencyWarning(Sema &S,
3500 SimplePointerKind PointerKind,
3501 SourceLocation PointerLoc) {
3502 assert(PointerLoc.isValid());
3504 if (PointerKind == SimplePointerKind::Array) {
3505 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
3507 S.Diag(PointerLoc, diag::warn_nullability_missing)
3508 << static_cast<unsigned>(PointerKind);
3511 if (PointerLoc.isMacroID())
3514 auto addFixIt = [&](NullabilityKind Nullability) {
3515 auto Diag = S.Diag(PointerLoc, diag::note_nullability_fix_it);
3516 Diag << static_cast<unsigned>(Nullability);
3517 Diag << static_cast<unsigned>(PointerKind);
3518 fixItNullability(S, Diag, PointerLoc, Nullability);
3520 addFixIt(NullabilityKind::Nullable);
3521 addFixIt(NullabilityKind::NonNull);
3524 /// Complains about missing nullability if the file containing \p pointerLoc
3525 /// has other uses of nullability (either the keywords or the \c assume_nonnull
3528 /// If the file has \e not seen other uses of nullability, this particular
3529 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
3530 static void checkNullabilityConsistency(Sema &S,
3531 SimplePointerKind pointerKind,
3532 SourceLocation pointerLoc) {
3533 // Determine which file we're performing consistency checking for.
3534 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3535 if (file.isInvalid())
3538 // If we haven't seen any type nullability in this file, we won't warn now
3540 FileNullability &fileNullability = S.NullabilityMap[file];
3541 if (!fileNullability.SawTypeNullability) {
3542 // If this is the first pointer declarator in the file, and the appropriate
3543 // warning is on, record it in case we need to diagnose it retroactively.
3544 diag::kind diagKind;
3545 if (pointerKind == SimplePointerKind::Array)
3546 diagKind = diag::warn_nullability_missing_array;
3548 diagKind = diag::warn_nullability_missing;
3550 if (fileNullability.PointerLoc.isInvalid() &&
3551 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
3552 fileNullability.PointerLoc = pointerLoc;
3553 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3559 // Complain about missing nullability.
3560 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc);
3563 /// Marks that a nullability feature has been used in the file containing
3566 /// If this file already had pointer types in it that were missing nullability,
3567 /// the first such instance is retroactively diagnosed.
3569 /// \sa checkNullabilityConsistency
3570 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
3571 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
3572 if (file.isInvalid())
3575 FileNullability &fileNullability = S.NullabilityMap[file];
3576 if (fileNullability.SawTypeNullability)
3578 fileNullability.SawTypeNullability = true;
3580 // If we haven't seen any type nullability before, now we have. Retroactively
3581 // diagnose the first unannotated pointer, if there was one.
3582 if (fileNullability.PointerLoc.isInvalid())
3585 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
3586 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc);
3589 /// Returns true if any of the declarator chunks before \p endIndex include a
3590 /// level of indirection: array, pointer, reference, or pointer-to-member.
3592 /// Because declarator chunks are stored in outer-to-inner order, testing
3593 /// every chunk before \p endIndex is testing all chunks that embed the current
3594 /// chunk as part of their type.
3596 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
3597 /// end index, in which case all chunks are tested.
3598 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
3599 unsigned i = endIndex;
3601 // Walk outwards along the declarator chunks.
3603 const DeclaratorChunk &DC = D.getTypeObject(i);
3605 case DeclaratorChunk::Paren:
3607 case DeclaratorChunk::Array:
3608 case DeclaratorChunk::Pointer:
3609 case DeclaratorChunk::Reference:
3610 case DeclaratorChunk::MemberPointer:
3612 case DeclaratorChunk::Function:
3613 case DeclaratorChunk::BlockPointer:
3614 case DeclaratorChunk::Pipe:
3615 // These are invalid anyway, so just ignore.
3622 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3623 QualType declSpecType,
3624 TypeSourceInfo *TInfo) {
3625 // The TypeSourceInfo that this function returns will not be a null type.
3626 // If there is an error, this function will fill in a dummy type as fallback.
3627 QualType T = declSpecType;
3628 Declarator &D = state.getDeclarator();
3629 Sema &S = state.getSema();
3630 ASTContext &Context = S.Context;
3631 const LangOptions &LangOpts = S.getLangOpts();
3633 // The name we're declaring, if any.
3634 DeclarationName Name;
3635 if (D.getIdentifier())
3636 Name = D.getIdentifier();
3638 // Does this declaration declare a typedef-name?
3639 bool IsTypedefName =
3640 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
3641 D.getContext() == Declarator::AliasDeclContext ||
3642 D.getContext() == Declarator::AliasTemplateContext;
3644 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3645 bool IsQualifiedFunction = T->isFunctionProtoType() &&
3646 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3647 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3649 // If T is 'decltype(auto)', the only declarators we can have are parens
3650 // and at most one function declarator if this is a function declaration.
3651 // If T is a deduced class template specialization type, we can have no
3652 // declarator chunks at all.
3653 if (auto *DT = T->getAs<DeducedType>()) {
3654 const AutoType *AT = T->getAs<AutoType>();
3655 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
3656 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
3657 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3658 unsigned Index = E - I - 1;
3659 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3660 unsigned DiagId = IsClassTemplateDeduction
3661 ? diag::err_deduced_class_template_compound_type
3662 : diag::err_decltype_auto_compound_type;
3663 unsigned DiagKind = 0;
3664 switch (DeclChunk.Kind) {
3665 case DeclaratorChunk::Paren:
3666 // FIXME: Rejecting this is a little silly.
3667 if (IsClassTemplateDeduction) {
3672 case DeclaratorChunk::Function: {
3673 if (IsClassTemplateDeduction) {
3678 if (D.isFunctionDeclarationContext() &&
3679 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3681 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3684 case DeclaratorChunk::Pointer:
3685 case DeclaratorChunk::BlockPointer:
3686 case DeclaratorChunk::MemberPointer:
3689 case DeclaratorChunk::Reference:
3692 case DeclaratorChunk::Array:
3695 case DeclaratorChunk::Pipe:
3699 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3700 D.setInvalidType(true);
3706 // Determine whether we should infer _Nonnull on pointer types.
3707 Optional<NullabilityKind> inferNullability;
3708 bool inferNullabilityCS = false;
3709 bool inferNullabilityInnerOnly = false;
3710 bool inferNullabilityInnerOnlyComplete = false;
3712 // Are we in an assume-nonnull region?
3713 bool inAssumeNonNullRegion = false;
3714 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
3715 if (assumeNonNullLoc.isValid()) {
3716 inAssumeNonNullRegion = true;
3717 recordNullabilitySeen(S, assumeNonNullLoc);
3720 // Whether to complain about missing nullability specifiers or not.
3724 /// Complain on the inner pointers (but not the outermost
3727 /// Complain about any pointers that don't have nullability
3728 /// specified or inferred.
3730 } complainAboutMissingNullability = CAMN_No;
3731 unsigned NumPointersRemaining = 0;
3732 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
3734 if (IsTypedefName) {
3735 // For typedefs, we do not infer any nullability (the default),
3736 // and we only complain about missing nullability specifiers on
3738 complainAboutMissingNullability = CAMN_InnerPointers;
3740 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
3741 !T->getNullability(S.Context)) {
3742 // Note that we allow but don't require nullability on dependent types.
3743 ++NumPointersRemaining;
3746 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3747 DeclaratorChunk &chunk = D.getTypeObject(i);
3748 switch (chunk.Kind) {
3749 case DeclaratorChunk::Array:
3750 case DeclaratorChunk::Function:
3751 case DeclaratorChunk::Pipe:
3754 case DeclaratorChunk::BlockPointer:
3755 case DeclaratorChunk::MemberPointer:
3756 ++NumPointersRemaining;
3759 case DeclaratorChunk::Paren:
3760 case DeclaratorChunk::Reference:
3763 case DeclaratorChunk::Pointer:
3764 ++NumPointersRemaining;
3769 bool isFunctionOrMethod = false;
3770 switch (auto context = state.getDeclarator().getContext()) {
3771 case Declarator::ObjCParameterContext:
3772 case Declarator::ObjCResultContext:
3773 case Declarator::PrototypeContext:
3774 case Declarator::TrailingReturnContext:
3775 isFunctionOrMethod = true;
3778 case Declarator::MemberContext:
3779 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3780 complainAboutMissingNullability = CAMN_No;
3784 // Weak properties are inferred to be nullable.
3785 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
3786 inferNullability = NullabilityKind::Nullable;
3792 case Declarator::FileContext:
3793 case Declarator::KNRTypeListContext: {
3794 complainAboutMissingNullability = CAMN_Yes;
3796 // Nullability inference depends on the type and declarator.
3797 auto wrappingKind = PointerWrappingDeclaratorKind::None;
3798 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
3799 case PointerDeclaratorKind::NonPointer:
3800 case PointerDeclaratorKind::MultiLevelPointer:
3801 // Cannot infer nullability.
3804 case PointerDeclaratorKind::SingleLevelPointer:
3805 // Infer _Nonnull if we are in an assumes-nonnull region.
3806 if (inAssumeNonNullRegion) {
3807 complainAboutInferringWithinChunk = wrappingKind;
3808 inferNullability = NullabilityKind::NonNull;
3809 inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3810 context == Declarator::ObjCResultContext);
3814 case PointerDeclaratorKind::CFErrorRefPointer:
3815 case PointerDeclaratorKind::NSErrorPointerPointer:
3816 // Within a function or method signature, infer _Nullable at both
3818 if (isFunctionOrMethod && inAssumeNonNullRegion)
3819 inferNullability = NullabilityKind::Nullable;
3822 case PointerDeclaratorKind::MaybePointerToCFRef:
3823 if (isFunctionOrMethod) {
3824 // On pointer-to-pointer parameters marked cf_returns_retained or
3825 // cf_returns_not_retained, if the outer pointer is explicit then
3826 // infer the inner pointer as _Nullable.
3827 auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3829 if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3830 NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3832 NextAttr = NextAttr->getNext();
3836 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3837 if (hasCFReturnsAttr(D.getAttributes()) ||
3838 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3839 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3840 inferNullability = NullabilityKind::Nullable;
3841 inferNullabilityInnerOnly = true;
3850 case Declarator::ConversionIdContext:
3851 complainAboutMissingNullability = CAMN_Yes;
3854 case Declarator::AliasDeclContext:
3855 case Declarator::AliasTemplateContext:
3856 case Declarator::BlockContext:
3857 case Declarator::BlockLiteralContext:
3858 case Declarator::ConditionContext:
3859 case Declarator::CXXCatchContext:
3860 case Declarator::CXXNewContext:
3861 case Declarator::ForContext:
3862 case Declarator::InitStmtContext:
3863 case Declarator::LambdaExprContext:
3864 case Declarator::LambdaExprParameterContext:
3865 case Declarator::ObjCCatchContext:
3866 case Declarator::TemplateParamContext:
3867 case Declarator::TemplateTypeArgContext:
3868 case Declarator::TypeNameContext:
3869 case Declarator::FunctionalCastContext:
3870 // Don't infer in these contexts.
3875 // Local function that returns true if its argument looks like a va_list.
3876 auto isVaList = [&S](QualType T) -> bool {
3877 auto *typedefTy = T->getAs<TypedefType>();
3880 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
3882 if (typedefTy->getDecl() == vaListTypedef)
3884 if (auto *name = typedefTy->getDecl()->getIdentifier())
3885 if (name->isStr("va_list"))
3887 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
3888 } while (typedefTy);
3892 // Local function that checks the nullability for a given pointer declarator.
3893 // Returns true if _Nonnull was inferred.
3894 auto inferPointerNullability = [&](SimplePointerKind pointerKind,
3895 SourceLocation pointerLoc,
3896 AttributeList *&attrs) -> AttributeList * {
3897 // We've seen a pointer.
3898 if (NumPointersRemaining > 0)
3899 --NumPointersRemaining;
3901 // If a nullability attribute is present, there's nothing to do.
3902 if (hasNullabilityAttr(attrs))
3905 // If we're supposed to infer nullability, do so now.
3906 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3907 AttributeList::Syntax syntax
3908 = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3909 : AttributeList::AS_Keyword;
3910 AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3912 S.getNullabilityKeyword(
3914 SourceRange(pointerLoc),
3915 nullptr, SourceLocation(),
3916 nullptr, 0, syntax);
3918 spliceAttrIntoList(*nullabilityAttr, attrs);
3920 if (inferNullabilityCS) {
3921 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
3922 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
3925 if (pointerLoc.isValid() &&
3926 complainAboutInferringWithinChunk !=
3927 PointerWrappingDeclaratorKind::None) {
3929 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
3930 Diag << static_cast<int>(complainAboutInferringWithinChunk);
3931 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
3934 if (inferNullabilityInnerOnly)
3935 inferNullabilityInnerOnlyComplete = true;
3936 return nullabilityAttr;
3939 // If we're supposed to complain about missing nullability, do so
3940 // now if it's truly missing.
3941 switch (complainAboutMissingNullability) {
3945 case CAMN_InnerPointers:
3946 if (NumPointersRemaining == 0)
3951 checkNullabilityConsistency(S, pointerKind, pointerLoc);
3956 // If the type itself could have nullability but does not, infer pointer
3957 // nullability and perform consistency checking.
3958 if (S.CodeSynthesisContexts.empty()) {
3959 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
3960 !T->getNullability(S.Context)) {
3962 // Record that we've seen a pointer, but do nothing else.
3963 if (NumPointersRemaining > 0)
3964 --NumPointersRemaining;
3966 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
3967 if (T->isBlockPointerType())
3968 pointerKind = SimplePointerKind::BlockPointer;
3969 else if (T->isMemberPointerType())
3970 pointerKind = SimplePointerKind::MemberPointer;
3972 if (auto *attr = inferPointerNullability(
3973 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3974 D.getMutableDeclSpec().getAttributes().getListRef())) {
3975 T = Context.getAttributedType(
3976 AttributedType::getNullabilityAttrKind(*inferNullability),T,T);
3977 attr->setUsedAsTypeAttr();
3982 if (complainAboutMissingNullability == CAMN_Yes &&
3983 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
3984 D.isPrototypeContext() &&
3985 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
3986 checkNullabilityConsistency(S, SimplePointerKind::Array,
3987 D.getDeclSpec().getTypeSpecTypeLoc());
3991 // Walk the DeclTypeInfo, building the recursive type as we go.
3992 // DeclTypeInfos are ordered from the identifier out, which is
3993 // opposite of what we want :).
3994 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3995 unsigned chunkIndex = e - i - 1;
3996 state.setCurrentChunkIndex(chunkIndex);
3997 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
3998 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
3999 switch (DeclType.Kind) {
4000 case DeclaratorChunk::Paren:
4001 T = S.BuildParenType(T);
4003 case DeclaratorChunk::BlockPointer:
4004 // If blocks are disabled, emit an error.
4005 if (!LangOpts.Blocks)
4006 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4008 // Handle pointer nullability.
4009 inferPointerNullability(SimplePointerKind::BlockPointer,
4010 DeclType.Loc, DeclType.getAttrListRef());
4012 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4013 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4014 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4015 // qualified with const.
4016 if (LangOpts.OpenCL)
4017 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4018 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4021 case DeclaratorChunk::Pointer:
4022 // Verify that we're not building a pointer to pointer to function with
4023 // exception specification.
4024 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4025 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4026 D.setInvalidType(true);
4027 // Build the type anyway.
4030 // Handle pointer nullability
4031 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4032 DeclType.getAttrListRef());
4034 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
4035 T = Context.getObjCObjectPointerType(T);
4036 if (DeclType.Ptr.TypeQuals)
4037 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4041 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4042 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4043 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4044 if (LangOpts.OpenCL) {
4045 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4046 T->isBlockPointerType()) {
4047 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4048 D.setInvalidType(true);
4052 T = S.BuildPointerType(T, DeclType.Loc, Name);
4053 if (DeclType.Ptr.TypeQuals)
4054 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4056 case DeclaratorChunk::Reference: {
4057 // Verify that we're not building a reference to pointer to function with
4058 // exception specification.
4059 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4060 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4061 D.setInvalidType(true);
4062 // Build the type anyway.
4064 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4066 if (DeclType.Ref.HasRestrict)
4067 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4070 case DeclaratorChunk::Array: {
4071 // Verify that we're not building an array of pointers to function with
4072 // exception specification.
4073 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4074 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4075 D.setInvalidType(true);
4076 // Build the type anyway.
4078 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4079 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4080 ArrayType::ArraySizeModifier ASM;
4082 ASM = ArrayType::Star;
4083 else if (ATI.hasStatic)
4084 ASM = ArrayType::Static;
4086 ASM = ArrayType::Normal;
4087 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4088 // FIXME: This check isn't quite right: it allows star in prototypes
4089 // for function definitions, and disallows some edge cases detailed
4090 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4091 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4092 ASM = ArrayType::Normal;
4093 D.setInvalidType(true);
4096 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4097 // shall appear only in a declaration of a function parameter with an
4099 if (ASM == ArrayType::Static || ATI.TypeQuals) {
4100 if (!(D.isPrototypeContext() ||
4101 D.getContext() == Declarator::KNRTypeListContext)) {
4102 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4103 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4104 // Remove the 'static' and the type qualifiers.
4105 if (ASM == ArrayType::Static)
4106 ASM = ArrayType::Normal;
4108 D.setInvalidType(true);
4111 // C99 6.7.5.2p1: ... and then only in the outermost array type
4113 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4114 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4115 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4116 if (ASM == ArrayType::Static)
4117 ASM = ArrayType::Normal;
4119 D.setInvalidType(true);
4122 const AutoType *AT = T->getContainedAutoType();
4123 // Allow arrays of auto if we are a generic lambda parameter.
4124 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4125 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
4126 // We've already diagnosed this for decltype(auto).
4127 if (!AT->isDecltypeAuto())
4128 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4129 << getPrintableNameForEntity(Name) << T;
4134 // Array parameters can be marked nullable as well, although it's not
4135 // necessary if they're marked 'static'.
4136 if (complainAboutMissingNullability == CAMN_Yes &&
4137 !hasNullabilityAttr(DeclType.getAttrs()) &&
4138 ASM != ArrayType::Static &&
4139 D.isPrototypeContext() &&
4140 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4141 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4144 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4145 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4148 case DeclaratorChunk::Function: {
4149 // If the function declarator has a prototype (i.e. it is not () and
4150 // does not have a K&R-style identifier list), then the arguments are part
4151 // of the type, otherwise the argument list is ().
4152 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4153 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
4155 // Check for auto functions and trailing return type and adjust the
4156 // return type accordingly.
4157 if (!D.isInvalidType()) {
4158 // trailing-return-type is only required if we're declaring a function,
4159 // and not, for instance, a pointer to a function.
4160 if (D.getDeclSpec().hasAutoTypeSpec() &&
4161 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
4162 !S.getLangOpts().CPlusPlus14) {
4163 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4164 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4165 ? diag::err_auto_missing_trailing_return
4166 : diag::err_deduced_return_type);
4168 D.setInvalidType(true);
4169 } else if (FTI.hasTrailingReturnType()) {
4170 // T must be exactly 'auto' at this point. See CWG issue 681.
4171 if (isa<ParenType>(T)) {
4172 S.Diag(D.getLocStart(),
4173 diag::err_trailing_return_in_parens)
4174 << T << D.getSourceRange();
4175 D.setInvalidType(true);
4176 } else if (D.getName().getKind() ==
4177 UnqualifiedId::IK_DeductionGuideName) {
4178 if (T != Context.DependentTy) {
4179 S.Diag(D.getDeclSpec().getLocStart(),
4180 diag::err_deduction_guide_with_complex_decl)
4181 << D.getSourceRange();
4182 D.setInvalidType(true);
4184 } else if (D.getContext() != Declarator::LambdaExprContext &&
4185 (T.hasQualifiers() || !isa<AutoType>(T) ||
4186 cast<AutoType>(T)->getKeyword() !=
4187 AutoTypeKeyword::Auto)) {
4188 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4189 diag::err_trailing_return_without_auto)
4190 << T << D.getDeclSpec().getSourceRange();
4191 D.setInvalidType(true);
4193 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4195 // An error occurred parsing the trailing return type.
4197 D.setInvalidType(true);
4202 // C99 6.7.5.3p1: The return type may not be a function or array type.
4203 // For conversion functions, we'll diagnose this particular error later.
4204 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4205 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
4206 unsigned diagID = diag::err_func_returning_array_function;
4207 // Last processing chunk in block context means this function chunk
4208 // represents the block.
4209 if (chunkIndex == 0 &&
4210 D.getContext() == Declarator::BlockLiteralContext)
4211 diagID = diag::err_block_returning_array_function;
4212 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4214 D.setInvalidType(true);
4217 // Do not allow returning half FP value.
4218 // FIXME: This really should be in BuildFunctionType.
4219 if (T->isHalfType()) {
4220 if (S.getLangOpts().OpenCL) {
4221 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4222 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4223 << T << 0 /*pointer hint*/;
4224 D.setInvalidType(true);
4226 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4227 S.Diag(D.getIdentifierLoc(),
4228 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4229 D.setInvalidType(true);
4233 if (LangOpts.OpenCL) {
4234 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4236 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4238 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4239 << T << 1 /*hint off*/;
4240 D.setInvalidType(true);
4242 // OpenCL doesn't support variadic functions and blocks
4243 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4244 // We also allow here any toolchain reserved identifiers.
4245 if (FTI.isVariadic &&
4246 !(D.getIdentifier() &&
4247 ((D.getIdentifier()->getName() == "printf" &&
4248 LangOpts.OpenCLVersion >= 120) ||
4249 D.getIdentifier()->getName().startswith("__")))) {
4250 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4251 D.setInvalidType(true);
4255 // Methods cannot return interface types. All ObjC objects are
4256 // passed by reference.
4257 if (T->isObjCObjectType()) {
4258 SourceLocation DiagLoc, FixitLoc;
4260 DiagLoc = TInfo->getTypeLoc().getLocStart();
4261 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
4263 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4264 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
4266 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4268 << FixItHint::CreateInsertion(FixitLoc, "*");
4270 T = Context.getObjCObjectPointerType(T);
4273 TLB.pushFullCopy(TInfo->getTypeLoc());
4274 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4275 TLoc.setStarLoc(FixitLoc);
4276 TInfo = TLB.getTypeSourceInfo(Context, T);
4279 D.setInvalidType(true);
4282 // cv-qualifiers on return types are pointless except when the type is a
4283 // class type in C++.
4284 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4285 !(S.getLangOpts().CPlusPlus &&
4286 (T->isDependentType() || T->isRecordType()))) {
4287 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4288 D.getFunctionDefinitionKind() == FDK_Definition) {
4289 // [6.9.1/3] qualified void return is invalid on a C
4290 // function definition. Apparently ok on declarations and
4291 // in C++ though (!)
4292 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4294 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4297 // Objective-C ARC ownership qualifiers are ignored on the function
4298 // return type (by type canonicalization). Complain if this attribute
4299 // was written here.
4300 if (T.getQualifiers().hasObjCLifetime()) {
4301 SourceLocation AttrLoc;
4302 if (chunkIndex + 1 < D.getNumTypeObjects()) {
4303 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4304 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
4305 Attr; Attr = Attr->getNext()) {
4306 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4307 AttrLoc = Attr->getLoc();
4312 if (AttrLoc.isInvalid()) {
4313 for (const AttributeList *Attr
4314 = D.getDeclSpec().getAttributes().getList();
4315 Attr; Attr = Attr->getNext()) {
4316 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4317 AttrLoc = Attr->getLoc();
4323 if (AttrLoc.isValid()) {
4324 // The ownership attributes are almost always written via
4326 // __strong/__weak/__autoreleasing/__unsafe_unretained.
4327 if (AttrLoc.isMacroID())
4328 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
4330 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4331 << T.getQualifiers().getObjCLifetime();
4335 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4337 // Types shall not be defined in return or parameter types.
4338 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4339 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4340 << Context.getTypeDeclType(Tag);
4343 // Exception specs are not allowed in typedefs. Complain, but add it
4345 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus1z)
4346 S.Diag(FTI.getExceptionSpecLocBeg(),
4347 diag::err_exception_spec_in_typedef)
4348 << (D.getContext() == Declarator::AliasDeclContext ||
4349 D.getContext() == Declarator::AliasTemplateContext);
4351 // If we see "T var();" or "T var(T());" at block scope, it is probably
4352 // an attempt to initialize a variable, not a function declaration.
4353 if (FTI.isAmbiguous)
4354 warnAboutAmbiguousFunction(S, D, DeclType, T);
4356 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
4358 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
4359 // Simple void foo(), where the incoming T is the result type.
4360 T = Context.getFunctionNoProtoType(T, EI);
4362 // We allow a zero-parameter variadic function in C if the
4363 // function is marked with the "overloadable" attribute. Scan
4364 // for this attribute now.
4365 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
4366 bool Overloadable = false;
4367 for (const AttributeList *Attrs = D.getAttributes();
4368 Attrs; Attrs = Attrs->getNext()) {
4369 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
4370 Overloadable = true;
4376 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4379 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4380 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4382 S.Diag(FTI.Params[0].IdentLoc,
4383 diag::err_ident_list_in_fn_declaration);
4384 D.setInvalidType(true);
4385 // Recover by creating a K&R-style function type.
4386 T = Context.getFunctionNoProtoType(T, EI);
4390 FunctionProtoType::ExtProtoInfo EPI;
4392 EPI.Variadic = FTI.isVariadic;
4393 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
4394 EPI.TypeQuals = FTI.TypeQuals;
4395 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4396 : FTI.RefQualifierIsLValueRef? RQ_LValue
4399 // Otherwise, we have a function with a parameter list that is
4400 // potentially variadic.
4401 SmallVector<QualType, 16> ParamTys;
4402 ParamTys.reserve(FTI.NumParams);
4404 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
4405 ExtParameterInfos(FTI.NumParams);
4406 bool HasAnyInterestingExtParameterInfos = false;
4408 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4409 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4410 QualType ParamTy = Param->getType();
4411 assert(!ParamTy.isNull() && "Couldn't parse type?");
4413 // Look for 'void'. void is allowed only as a single parameter to a
4414 // function with no other parameters (C99 6.7.5.3p10). We record
4415 // int(void) as a FunctionProtoType with an empty parameter list.
4416 if (ParamTy->isVoidType()) {
4417 // If this is something like 'float(int, void)', reject it. 'void'
4418 // is an incomplete type (C99 6.2.5p19) and function decls cannot
4419 // have parameters of incomplete type.
4420 if (FTI.NumParams != 1 || FTI.isVariadic) {
4421 S.Diag(DeclType.Loc, diag::err_void_only_param);
4422 ParamTy = Context.IntTy;
4423 Param->setType(ParamTy);
4424 } else if (FTI.Params[i].Ident) {
4425 // Reject, but continue to parse 'int(void abc)'.
4426 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4427 ParamTy = Context.IntTy;
4428 Param->setType(ParamTy);
4430 // Reject, but continue to parse 'float(const void)'.
4431 if (ParamTy.hasQualifiers())
4432 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4434 // Do not add 'void' to the list.
4437 } else if (ParamTy->isHalfType()) {
4438 // Disallow half FP parameters.
4439 // FIXME: This really should be in BuildFunctionType.
4440 if (S.getLangOpts().OpenCL) {
4441 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4442 S.Diag(Param->getLocation(),
4443 diag::err_opencl_half_param) << ParamTy;
4445 Param->setInvalidDecl();
4447 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4448 S.Diag(Param->getLocation(),
4449 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4452 } else if (!FTI.hasPrototype) {
4453 if (ParamTy->isPromotableIntegerType()) {
4454 ParamTy = Context.getPromotedIntegerType(ParamTy);
4455 Param->setKNRPromoted(true);
4456 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4457 if (BTy->getKind() == BuiltinType::Float) {
4458 ParamTy = Context.DoubleTy;
4459 Param->setKNRPromoted(true);
4464 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4465 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4466 HasAnyInterestingExtParameterInfos = true;
4469 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4470 ExtParameterInfos[i] =
4471 ExtParameterInfos[i].withABI(attr->getABI());
4472 HasAnyInterestingExtParameterInfos = true;
4475 if (Param->hasAttr<PassObjectSizeAttr>()) {
4476 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
4477 HasAnyInterestingExtParameterInfos = true;
4480 ParamTys.push_back(ParamTy);
4483 if (HasAnyInterestingExtParameterInfos) {
4484 EPI.ExtParameterInfos = ExtParameterInfos.data();
4485 checkExtParameterInfos(S, ParamTys, EPI,
4486 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4489 SmallVector<QualType, 4> Exceptions;
4490 SmallVector<ParsedType, 2> DynamicExceptions;
4491 SmallVector<SourceRange, 2> DynamicExceptionRanges;
4492 Expr *NoexceptExpr = nullptr;
4494 if (FTI.getExceptionSpecType() == EST_Dynamic) {
4495 // FIXME: It's rather inefficient to have to split into two vectors
4497 unsigned N = FTI.getNumExceptions();
4498 DynamicExceptions.reserve(N);
4499 DynamicExceptionRanges.reserve(N);
4500 for (unsigned I = 0; I != N; ++I) {
4501 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4502 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4504 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
4505 NoexceptExpr = FTI.NoexceptExpr;
4508 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4509 FTI.getExceptionSpecType(),
4511 DynamicExceptionRanges,
4516 T = Context.getFunctionType(T, ParamTys, EPI);
4520 case DeclaratorChunk::MemberPointer: {
4521 // The scope spec must refer to a class, or be dependent.
4522 CXXScopeSpec &SS = DeclType.Mem.Scope();
4525 // Handle pointer nullability.
4526 inferPointerNullability(SimplePointerKind::MemberPointer,
4527 DeclType.Loc, DeclType.getAttrListRef());
4529 if (SS.isInvalid()) {
4530 // Avoid emitting extra errors if we already errored on the scope.
4531 D.setInvalidType(true);
4532 } else if (S.isDependentScopeSpecifier(SS) ||
4533 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4534 NestedNameSpecifier *NNS = SS.getScopeRep();
4535 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4536 switch (NNS->getKind()) {
4537 case NestedNameSpecifier::Identifier:
4538 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4539 NNS->getAsIdentifier());
4542 case NestedNameSpecifier::Namespace:
4543 case NestedNameSpecifier::NamespaceAlias:
4544 case NestedNameSpecifier::Global:
4545 case NestedNameSpecifier::Super:
4546 llvm_unreachable("Nested-name-specifier must name a type");
4548 case NestedNameSpecifier::TypeSpec:
4549 case NestedNameSpecifier::TypeSpecWithTemplate:
4550 ClsType = QualType(NNS->getAsType(), 0);
4551 // Note: if the NNS has a prefix and ClsType is a nondependent
4552 // TemplateSpecializationType, then the NNS prefix is NOT included
4553 // in ClsType; hence we wrap ClsType into an ElaboratedType.
4554 // NOTE: in particular, no wrap occurs if ClsType already is an
4555 // Elaborated, DependentName, or DependentTemplateSpecialization.
4556 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4557 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4561 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4562 diag::err_illegal_decl_mempointer_in_nonclass)
4563 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4564 << DeclType.Mem.Scope().getRange();
4565 D.setInvalidType(true);
4568 if (!ClsType.isNull())
4569 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4573 D.setInvalidType(true);
4574 } else if (DeclType.Mem.TypeQuals) {
4575 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4580 case DeclaratorChunk::Pipe: {
4581 T = S.BuildReadPipeType(T, DeclType.Loc);
4582 processTypeAttrs(state, T, TAL_DeclSpec,
4583 D.getDeclSpec().getAttributes().getList());
4589 D.setInvalidType(true);
4593 // See if there are any attributes on this declarator chunk.
4594 processTypeAttrs(state, T, TAL_DeclChunk,
4595 const_cast<AttributeList *>(DeclType.getAttrs()));
4598 // GNU warning -Wstrict-prototypes
4599 // Warn if a function declaration is without a prototype.
4600 // This warning is issued for all kinds of unprototyped function
4601 // declarations (i.e. function type typedef, function pointer etc.)
4603 // The empty list in a function declarator that is not part of a definition
4604 // of that function specifies that no information about the number or types
4605 // of the parameters is supplied.
4606 if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) {
4607 bool IsBlock = false;
4608 for (const DeclaratorChunk &DeclType : D.type_objects()) {
4609 switch (DeclType.Kind) {
4610 case DeclaratorChunk::BlockPointer:
4613 case DeclaratorChunk::Function: {
4614 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4615 if (FTI.NumParams == 0)
4616 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
4618 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
4628 assert(!T.isNull() && "T must not be null after this point");
4630 if (LangOpts.CPlusPlus && T->isFunctionType()) {
4631 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4632 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4635 // A cv-qualifier-seq shall only be part of the function type
4636 // for a nonstatic member function, the function type to which a pointer
4637 // to member refers, or the top-level function type of a function typedef
4640 // Core issue 547 also allows cv-qualifiers on function types that are
4641 // top-level template type arguments.
4642 enum { NonMember, Member, DeductionGuide } Kind = NonMember;
4643 if (D.getName().getKind() == UnqualifiedId::IK_DeductionGuideName)
4644 Kind = DeductionGuide;
4645 else if (!D.getCXXScopeSpec().isSet()) {
4646 if ((D.getContext() == Declarator::MemberContext ||
4647 D.getContext() == Declarator::LambdaExprContext) &&
4648 !D.getDeclSpec().isFriendSpecified())
4651 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4652 if (!DC || DC->isRecord())
4656 // C++11 [dcl.fct]p6 (w/DR1417):
4657 // An attempt to specify a function type with a cv-qualifier-seq or a
4658 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4659 // - the function type for a non-static member function,
4660 // - the function type to which a pointer to member refers,
4661 // - the top-level function type of a function typedef declaration or
4662 // alias-declaration,
4663 // - the type-id in the default argument of a type-parameter, or
4664 // - the type-id of a template-argument for a type-parameter
4666 // FIXME: Checking this here is insufficient. We accept-invalid on:
4668 // template<typename T> struct S { void f(T); };
4669 // S<int() const> s;
4671 // ... for instance.
4672 if (IsQualifiedFunction &&
4674 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4676 D.getContext() != Declarator::TemplateTypeArgContext) {
4677 SourceLocation Loc = D.getLocStart();
4678 SourceRange RemovalRange;
4680 if (D.isFunctionDeclarator(I)) {
4681 SmallVector<SourceLocation, 4> RemovalLocs;
4682 const DeclaratorChunk &Chunk = D.getTypeObject(I);
4683 assert(Chunk.Kind == DeclaratorChunk::Function);
4684 if (Chunk.Fun.hasRefQualifier())
4685 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4686 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4687 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4688 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4689 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4690 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4691 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4692 if (!RemovalLocs.empty()) {
4693 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
4694 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4695 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4696 Loc = RemovalLocs.front();
4700 S.Diag(Loc, diag::err_invalid_qualified_function_type)
4701 << Kind << D.isFunctionDeclarator() << T
4702 << getFunctionQualifiersAsString(FnTy)
4703 << FixItHint::CreateRemoval(RemovalRange);
4705 // Strip the cv-qualifiers and ref-qualifiers from the type.
4706 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4708 EPI.RefQualifier = RQ_None;
4710 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4712 // Rebuild any parens around the identifier in the function type.
4713 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4714 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4716 T = S.BuildParenType(T);
4721 // Apply any undistributed attributes from the declarator.
4722 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
4724 // Diagnose any ignored type attributes.
4725 state.diagnoseIgnoredTypeAttrs(T);
4727 // C++0x [dcl.constexpr]p9:
4728 // A constexpr specifier used in an object declaration declares the object
4730 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4734 // If there was an ellipsis in the declarator, the declaration declares a
4735 // parameter pack whose type may be a pack expansion type.
4736 if (D.hasEllipsis()) {
4737 // C++0x [dcl.fct]p13:
4738 // A declarator-id or abstract-declarator containing an ellipsis shall
4739 // only be used in a parameter-declaration. Such a parameter-declaration
4740 // is a parameter pack (14.5.3). [...]
4741 switch (D.getContext()) {
4742 case Declarator::PrototypeContext:
4743 case Declarator::LambdaExprParameterContext:
4744 // C++0x [dcl.fct]p13:
4745 // [...] When it is part of a parameter-declaration-clause, the
4746 // parameter pack is a function parameter pack (14.5.3). The type T
4747 // of the declarator-id of the function parameter pack shall contain
4748 // a template parameter pack; each template parameter pack in T is
4749 // expanded by the function parameter pack.
4751 // We represent function parameter packs as function parameters whose
4752 // type is a pack expansion.
4753 if (!T->containsUnexpandedParameterPack()) {
4754 S.Diag(D.getEllipsisLoc(),
4755 diag::err_function_parameter_pack_without_parameter_packs)
4756 << T << D.getSourceRange();
4757 D.setEllipsisLoc(SourceLocation());
4759 T = Context.getPackExpansionType(T, None);
4762 case Declarator::TemplateParamContext:
4763 // C++0x [temp.param]p15:
4764 // If a template-parameter is a [...] is a parameter-declaration that
4765 // declares a parameter pack (8.3.5), then the template-parameter is a
4766 // template parameter pack (14.5.3).
4768 // Note: core issue 778 clarifies that, if there are any unexpanded
4769 // parameter packs in the type of the non-type template parameter, then
4770 // it expands those parameter packs.
4771 if (T->containsUnexpandedParameterPack())
4772 T = Context.getPackExpansionType(T, None);
4774 S.Diag(D.getEllipsisLoc(),
4775 LangOpts.CPlusPlus11
4776 ? diag::warn_cxx98_compat_variadic_templates
4777 : diag::ext_variadic_templates);
4780 case Declarator::FileContext:
4781 case Declarator::KNRTypeListContext:
4782 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
4783 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
4784 case Declarator::TypeNameContext:
4785 case Declarator::FunctionalCastContext:
4786 case Declarator::CXXNewContext:
4787 case Declarator::AliasDeclContext:
4788 case Declarator::AliasTemplateContext:
4789 case Declarator::MemberContext:
4790 case Declarator::BlockContext:
4791 case Declarator::ForContext:
4792 case Declarator::InitStmtContext:
4793 case Declarator::ConditionContext:
4794 case Declarator::CXXCatchContext:
4795 case Declarator::ObjCCatchContext:
4796 case Declarator::BlockLiteralContext:
4797 case Declarator::LambdaExprContext:
4798 case Declarator::ConversionIdContext:
4799 case Declarator::TrailingReturnContext:
4800 case Declarator::TemplateTypeArgContext:
4801 // FIXME: We may want to allow parameter packs in block-literal contexts
4803 S.Diag(D.getEllipsisLoc(),
4804 diag::err_ellipsis_in_declarator_not_parameter);
4805 D.setEllipsisLoc(SourceLocation());
4810 assert(!T.isNull() && "T must not be null at the end of this function");
4811 if (D.isInvalidType())
4812 return Context.getTrivialTypeSourceInfo(T);
4814 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
4817 /// GetTypeForDeclarator - Convert the type for the specified
4818 /// declarator to Type instances.
4820 /// The result of this call will never be null, but the associated
4821 /// type may be a null type if there's an unrecoverable error.
4822 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
4823 // Determine the type of the declarator. Not all forms of declarator
4826 TypeProcessingState state(*this, D);
4828 TypeSourceInfo *ReturnTypeInfo = nullptr;
4829 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4831 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
4832 inferARCWriteback(state, T);
4834 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
4837 static void transferARCOwnershipToDeclSpec(Sema &S,
4838 QualType &declSpecTy,
4839 Qualifiers::ObjCLifetime ownership) {
4840 if (declSpecTy->isObjCRetainableType() &&
4841 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
4843 qs.addObjCLifetime(ownership);
4844 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
4848 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
4849 Qualifiers::ObjCLifetime ownership,
4850 unsigned chunkIndex) {
4851 Sema &S = state.getSema();
4852 Declarator &D = state.getDeclarator();
4854 // Look for an explicit lifetime attribute.
4855 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
4856 for (const AttributeList *attr = chunk.getAttrs(); attr;
4857 attr = attr->getNext())
4858 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
4861 const char *attrStr = nullptr;
4862 switch (ownership) {
4863 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
4864 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
4865 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
4866 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
4867 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
4870 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
4871 Arg->Ident = &S.Context.Idents.get(attrStr);
4872 Arg->Loc = SourceLocation();
4874 ArgsUnion Args(Arg);
4876 // If there wasn't one, add one (with an invalid source location
4877 // so that we don't make an AttributedType for it).
4878 AttributeList *attr = D.getAttributePool()
4879 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
4880 /*scope*/ nullptr, SourceLocation(),
4881 /*args*/ &Args, 1, AttributeList::AS_GNU);
4882 spliceAttrIntoList(*attr, chunk.getAttrListRef());
4884 // TODO: mark whether we did this inference?
4887 /// \brief Used for transferring ownership in casts resulting in l-values.
4888 static void transferARCOwnership(TypeProcessingState &state,
4889 QualType &declSpecTy,
4890 Qualifiers::ObjCLifetime ownership) {
4891 Sema &S = state.getSema();
4892 Declarator &D = state.getDeclarator();
4895 bool hasIndirection = false;
4896 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4897 DeclaratorChunk &chunk = D.getTypeObject(i);
4898 switch (chunk.Kind) {
4899 case DeclaratorChunk::Paren:
4903 case DeclaratorChunk::Array:
4904 case DeclaratorChunk::Reference:
4905 case DeclaratorChunk::Pointer:
4907 hasIndirection = true;
4911 case DeclaratorChunk::BlockPointer:
4913 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
4916 case DeclaratorChunk::Function:
4917 case DeclaratorChunk::MemberPointer:
4918 case DeclaratorChunk::Pipe:
4926 DeclaratorChunk &chunk = D.getTypeObject(inner);
4927 if (chunk.Kind == DeclaratorChunk::Pointer) {
4928 if (declSpecTy->isObjCRetainableType())
4929 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4930 if (declSpecTy->isObjCObjectType() && hasIndirection)
4931 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
4933 assert(chunk.Kind == DeclaratorChunk::Array ||
4934 chunk.Kind == DeclaratorChunk::Reference);
4935 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4939 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
4940 TypeProcessingState state(*this, D);
4942 TypeSourceInfo *ReturnTypeInfo = nullptr;
4943 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4945 if (getLangOpts().ObjC1) {
4946 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
4947 if (ownership != Qualifiers::OCL_None)
4948 transferARCOwnership(state, declSpecTy, ownership);
4951 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4954 /// Map an AttributedType::Kind to an AttributeList::Kind.
4955 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
4957 case AttributedType::attr_address_space:
4958 return AttributeList::AT_AddressSpace;
4959 case AttributedType::attr_regparm:
4960 return AttributeList::AT_Regparm;
4961 case AttributedType::attr_vector_size:
4962 return AttributeList::AT_VectorSize;
4963 case AttributedType::attr_neon_vector_type:
4964 return AttributeList::AT_NeonVectorType;
4965 case AttributedType::attr_neon_polyvector_type:
4966 return AttributeList::AT_NeonPolyVectorType;
4967 case AttributedType::attr_objc_gc:
4968 return AttributeList::AT_ObjCGC;
4969 case AttributedType::attr_objc_ownership:
4970 case AttributedType::attr_objc_inert_unsafe_unretained:
4971 return AttributeList::AT_ObjCOwnership;
4972 case AttributedType::attr_noreturn:
4973 return AttributeList::AT_NoReturn;
4974 case AttributedType::attr_cdecl:
4975 return AttributeList::AT_CDecl;
4976 case AttributedType::attr_fastcall:
4977 return AttributeList::AT_FastCall;
4978 case AttributedType::attr_stdcall:
4979 return AttributeList::AT_StdCall;
4980 case AttributedType::attr_thiscall:
4981 return AttributeList::AT_ThisCall;
4982 case AttributedType::attr_regcall:
4983 return AttributeList::AT_RegCall;
4984 case AttributedType::attr_pascal:
4985 return AttributeList::AT_Pascal;
4986 case AttributedType::attr_swiftcall:
4987 return AttributeList::AT_SwiftCall;
4988 case AttributedType::attr_vectorcall:
4989 return AttributeList::AT_VectorCall;
4990 case AttributedType::attr_pcs:
4991 case AttributedType::attr_pcs_vfp:
4992 return AttributeList::AT_Pcs;
4993 case AttributedType::attr_inteloclbicc:
4994 return AttributeList::AT_IntelOclBicc;
4995 case AttributedType::attr_ms_abi:
4996 return AttributeList::AT_MSABI;
4997 case AttributedType::attr_sysv_abi:
4998 return AttributeList::AT_SysVABI;
4999 case AttributedType::attr_preserve_most:
5000 return AttributeList::AT_PreserveMost;
5001 case AttributedType::attr_preserve_all:
5002 return AttributeList::AT_PreserveAll;
5003 case AttributedType::attr_ptr32:
5004 return AttributeList::AT_Ptr32;
5005 case AttributedType::attr_ptr64:
5006 return AttributeList::AT_Ptr64;
5007 case AttributedType::attr_sptr:
5008 return AttributeList::AT_SPtr;
5009 case AttributedType::attr_uptr:
5010 return AttributeList::AT_UPtr;
5011 case AttributedType::attr_nonnull:
5012 return AttributeList::AT_TypeNonNull;
5013 case AttributedType::attr_nullable:
5014 return AttributeList::AT_TypeNullable;
5015 case AttributedType::attr_null_unspecified:
5016 return AttributeList::AT_TypeNullUnspecified;
5017 case AttributedType::attr_objc_kindof:
5018 return AttributeList::AT_ObjCKindOf;
5020 llvm_unreachable("unexpected attribute kind!");
5023 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5024 const AttributeList *attrs,
5025 const AttributeList *DeclAttrs = nullptr) {
5026 // DeclAttrs and attrs cannot be both empty.
5027 assert((attrs || DeclAttrs) &&
5028 "no type attributes in the expected location!");
5030 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
5031 // Try to search for an attribute of matching kind in attrs list.
5032 while (attrs && attrs->getKind() != parsedKind)
5033 attrs = attrs->getNext();
5035 // No matching type attribute in attrs list found.
5036 // Try searching through C++11 attributes in the declarator attribute list.
5037 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
5038 DeclAttrs->getKind() != parsedKind))
5039 DeclAttrs = DeclAttrs->getNext();
5043 assert(attrs && "no matching type attribute in expected location!");
5045 TL.setAttrNameLoc(attrs->getLoc());
5046 if (TL.hasAttrExprOperand()) {
5047 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
5048 TL.setAttrExprOperand(attrs->getArgAsExpr(0));
5049 } else if (TL.hasAttrEnumOperand()) {
5050 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
5051 "unexpected attribute operand kind");
5052 if (attrs->isArgIdent(0))
5053 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
5055 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
5058 // FIXME: preserve this information to here.
5059 if (TL.hasAttrOperand())
5060 TL.setAttrOperandParensRange(SourceRange());
5064 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5065 ASTContext &Context;
5069 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
5070 : Context(Context), DS(DS) {}
5072 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5073 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
5074 Visit(TL.getModifiedLoc());
5076 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5077 Visit(TL.getUnqualifiedLoc());
5079 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5080 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5082 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5083 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5084 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5085 // addition field. What we have is good enough for dispay of location
5086 // of 'fixit' on interface name.
5087 TL.setNameEndLoc(DS.getLocEnd());
5089 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5090 TypeSourceInfo *RepTInfo = nullptr;
5091 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5092 TL.copy(RepTInfo->getTypeLoc());
5094 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5095 TypeSourceInfo *RepTInfo = nullptr;
5096 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5097 TL.copy(RepTInfo->getTypeLoc());
5099 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5100 TypeSourceInfo *TInfo = nullptr;
5101 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5103 // If we got no declarator info from previous Sema routines,
5104 // just fill with the typespec loc.
5106 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5110 TypeLoc OldTL = TInfo->getTypeLoc();
5111 if (TInfo->getType()->getAs<ElaboratedType>()) {
5112 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5113 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5114 .castAs<TemplateSpecializationTypeLoc>();
5117 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5118 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
5122 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5123 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
5124 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5125 TL.setParensRange(DS.getTypeofParensRange());
5127 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5128 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
5129 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5130 TL.setParensRange(DS.getTypeofParensRange());
5131 assert(DS.getRepAsType());
5132 TypeSourceInfo *TInfo = nullptr;
5133 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5134 TL.setUnderlyingTInfo(TInfo);
5136 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5137 // FIXME: This holds only because we only have one unary transform.
5138 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
5139 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5140 TL.setParensRange(DS.getTypeofParensRange());
5141 assert(DS.getRepAsType());
5142 TypeSourceInfo *TInfo = nullptr;
5143 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5144 TL.setUnderlyingTInfo(TInfo);
5146 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5147 // By default, use the source location of the type specifier.
5148 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5149 if (TL.needsExtraLocalData()) {
5150 // Set info for the written builtin specifiers.
5151 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5152 // Try to have a meaningful source location.
5153 if (TL.getWrittenSignSpec() != TSS_unspecified)
5154 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5155 if (TL.getWrittenWidthSpec() != TSW_unspecified)
5156 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5159 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5160 ElaboratedTypeKeyword Keyword
5161 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5162 if (DS.getTypeSpecType() == TST_typename) {
5163 TypeSourceInfo *TInfo = nullptr;
5164 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5166 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5170 TL.setElaboratedKeywordLoc(Keyword != ETK_None
5171 ? DS.getTypeSpecTypeLoc()
5172 : SourceLocation());
5173 const CXXScopeSpec& SS = DS.getTypeSpecScope();
5174 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5175 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5177 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5178 assert(DS.getTypeSpecType() == TST_typename);
5179 TypeSourceInfo *TInfo = nullptr;
5180 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5182 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
5184 void VisitDependentTemplateSpecializationTypeLoc(
5185 DependentTemplateSpecializationTypeLoc TL) {
5186 assert(DS.getTypeSpecType() == TST_typename);
5187 TypeSourceInfo *TInfo = nullptr;
5188 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5191 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
5193 void VisitTagTypeLoc(TagTypeLoc TL) {
5194 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
5196 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5197 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
5198 // or an _Atomic qualifier.
5199 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
5200 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5201 TL.setParensRange(DS.getTypeofParensRange());
5203 TypeSourceInfo *TInfo = nullptr;
5204 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5206 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5208 TL.setKWLoc(DS.getAtomicSpecLoc());
5209 // No parens, to indicate this was spelled as an _Atomic qualifier.
5210 TL.setParensRange(SourceRange());
5211 Visit(TL.getValueLoc());
5215 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5216 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5218 TypeSourceInfo *TInfo = nullptr;
5219 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5220 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5223 void VisitTypeLoc(TypeLoc TL) {
5224 // FIXME: add other typespec types and change this to an assert.
5225 TL.initialize(Context, DS.getTypeSpecTypeLoc());
5229 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
5230 ASTContext &Context;
5231 const DeclaratorChunk &Chunk;
5234 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
5235 : Context(Context), Chunk(Chunk) {}
5237 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5238 llvm_unreachable("qualified type locs not expected here!");
5240 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5241 llvm_unreachable("decayed type locs not expected here!");
5244 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5245 fillAttributedTypeLoc(TL, Chunk.getAttrs());
5247 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5250 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5251 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
5252 TL.setCaretLoc(Chunk.Loc);
5254 void VisitPointerTypeLoc(PointerTypeLoc TL) {
5255 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5256 TL.setStarLoc(Chunk.Loc);
5258 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5259 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5260 TL.setStarLoc(Chunk.Loc);
5262 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5263 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
5264 const CXXScopeSpec& SS = Chunk.Mem.Scope();
5265 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
5267 const Type* ClsTy = TL.getClass();
5268 QualType ClsQT = QualType(ClsTy, 0);
5269 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5270 // Now copy source location info into the type loc component.
5271 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5272 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5273 case NestedNameSpecifier::Identifier:
5274 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
5276 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
5277 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
5278 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5279 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5283 case NestedNameSpecifier::TypeSpec:
5284 case NestedNameSpecifier::TypeSpecWithTemplate:
5285 if (isa<ElaboratedType>(ClsTy)) {
5286 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5287 ETLoc.setElaboratedKeywordLoc(SourceLocation());
5288 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5289 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5290 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5292 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
5296 case NestedNameSpecifier::Namespace:
5297 case NestedNameSpecifier::NamespaceAlias:
5298 case NestedNameSpecifier::Global:
5299 case NestedNameSpecifier::Super:
5300 llvm_unreachable("Nested-name-specifier must name a type");
5303 // Finally fill in MemberPointerLocInfo fields.
5304 TL.setStarLoc(Chunk.Loc);
5305 TL.setClassTInfo(ClsTInfo);
5307 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5308 assert(Chunk.Kind == DeclaratorChunk::Reference);
5309 // 'Amp' is misleading: this might have been originally
5310 /// spelled with AmpAmp.
5311 TL.setAmpLoc(Chunk.Loc);
5313 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5314 assert(Chunk.Kind == DeclaratorChunk::Reference);
5315 assert(!Chunk.Ref.LValueRef);
5316 TL.setAmpAmpLoc(Chunk.Loc);
5318 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
5319 assert(Chunk.Kind == DeclaratorChunk::Array);
5320 TL.setLBracketLoc(Chunk.Loc);
5321 TL.setRBracketLoc(Chunk.EndLoc);
5322 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
5324 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5325 assert(Chunk.Kind == DeclaratorChunk::Function);
5326 TL.setLocalRangeBegin(Chunk.Loc);
5327 TL.setLocalRangeEnd(Chunk.EndLoc);
5329 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
5330 TL.setLParenLoc(FTI.getLParenLoc());
5331 TL.setRParenLoc(FTI.getRParenLoc());
5332 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
5333 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5334 TL.setParam(tpi++, Param);
5336 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
5338 void VisitParenTypeLoc(ParenTypeLoc TL) {
5339 assert(Chunk.Kind == DeclaratorChunk::Paren);
5340 TL.setLParenLoc(Chunk.Loc);
5341 TL.setRParenLoc(Chunk.EndLoc);
5343 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5344 assert(Chunk.Kind == DeclaratorChunk::Pipe);
5345 TL.setKWLoc(Chunk.Loc);
5348 void VisitTypeLoc(TypeLoc TL) {
5349 llvm_unreachable("unsupported TypeLoc kind in declarator!");
5352 } // end anonymous namespace
5354 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5356 switch (Chunk.Kind) {
5357 case DeclaratorChunk::Function:
5358 case DeclaratorChunk::Array:
5359 case DeclaratorChunk::Paren:
5360 case DeclaratorChunk::Pipe:
5361 llvm_unreachable("cannot be _Atomic qualified");
5363 case DeclaratorChunk::Pointer:
5364 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
5367 case DeclaratorChunk::BlockPointer:
5368 case DeclaratorChunk::Reference:
5369 case DeclaratorChunk::MemberPointer:
5370 // FIXME: Provide a source location for the _Atomic keyword.
5375 ATL.setParensRange(SourceRange());
5378 /// \brief Create and instantiate a TypeSourceInfo with type source information.
5380 /// \param T QualType referring to the type as written in source code.
5382 /// \param ReturnTypeInfo For declarators whose return type does not show
5383 /// up in the normal place in the declaration specifiers (such as a C++
5384 /// conversion function), this pointer will refer to a type source information
5385 /// for that return type.
5387 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
5388 TypeSourceInfo *ReturnTypeInfo) {
5389 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
5390 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
5391 const AttributeList *DeclAttrs = D.getAttributes();
5393 // Handle parameter packs whose type is a pack expansion.
5394 if (isa<PackExpansionType>(T)) {
5395 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
5396 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5399 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5400 // An AtomicTypeLoc might be produced by an atomic qualifier in this
5401 // declarator chunk.
5402 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
5403 fillAtomicQualLoc(ATL, D.getTypeObject(i));
5404 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
5407 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
5408 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
5409 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5412 // FIXME: Ordering here?
5413 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
5414 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5416 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
5417 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5420 // If we have different source information for the return type, use
5421 // that. This really only applies to C++ conversion functions.
5422 if (ReturnTypeInfo) {
5423 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
5424 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
5425 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
5427 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
5433 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
5434 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
5435 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
5436 // and Sema during declaration parsing. Try deallocating/caching them when
5437 // it's appropriate, instead of allocating them and keeping them around.
5438 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
5440 new (LocT) LocInfoType(T, TInfo);
5441 assert(LocT->getTypeClass() != T->getTypeClass() &&
5442 "LocInfoType's TypeClass conflicts with an existing Type class");
5443 return ParsedType::make(QualType(LocT, 0));
5446 void LocInfoType::getAsStringInternal(std::string &Str,
5447 const PrintingPolicy &Policy) const {
5448 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
5449 " was used directly instead of getting the QualType through"
5450 " GetTypeFromParser");
5453 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
5454 // C99 6.7.6: Type names have no identifier. This is already validated by
5456 assert(D.getIdentifier() == nullptr &&
5457 "Type name should have no identifier!");
5459 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5460 QualType T = TInfo->getType();
5461 if (D.isInvalidType())
5464 // Make sure there are no unused decl attributes on the declarator.
5465 // We don't want to do this for ObjC parameters because we're going
5466 // to apply them to the actual parameter declaration.
5467 // Likewise, we don't want to do this for alias declarations, because
5468 // we are actually going to build a declaration from this eventually.
5469 if (D.getContext() != Declarator::ObjCParameterContext &&
5470 D.getContext() != Declarator::AliasDeclContext &&
5471 D.getContext() != Declarator::AliasTemplateContext)
5472 checkUnusedDeclAttributes(D);
5474 if (getLangOpts().CPlusPlus) {
5475 // Check that there are no default arguments (C++ only).
5476 CheckExtraCXXDefaultArguments(D);
5479 return CreateParsedType(T, TInfo);
5482 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
5483 QualType T = Context.getObjCInstanceType();
5484 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
5485 return CreateParsedType(T, TInfo);
5488 //===----------------------------------------------------------------------===//
5489 // Type Attribute Processing
5490 //===----------------------------------------------------------------------===//
5492 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5493 /// specified type. The attribute contains 1 argument, the id of the address
5494 /// space for the type.
5495 static void HandleAddressSpaceTypeAttribute(QualType &Type,
5496 const AttributeList &Attr, Sema &S){
5498 // If this type is already address space qualified, reject it.
5499 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5500 // qualifiers for two or more different address spaces."
5501 if (Type.getAddressSpace()) {
5502 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5507 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5508 // qualified by an address-space qualifier."
5509 if (Type->isFunctionType()) {
5510 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5516 if (Attr.getKind() == AttributeList::AT_AddressSpace) {
5517 // Check the attribute arguments.
5518 if (Attr.getNumArgs() != 1) {
5519 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5520 << Attr.getName() << 1;
5524 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5525 llvm::APSInt addrSpace(32);
5526 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
5527 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
5528 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5529 << Attr.getName() << AANT_ArgumentIntegerConstant
5530 << ASArgExpr->getSourceRange();
5536 if (addrSpace.isSigned()) {
5537 if (addrSpace.isNegative()) {
5538 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
5539 << ASArgExpr->getSourceRange();
5543 addrSpace.setIsSigned(false);
5545 llvm::APSInt max(addrSpace.getBitWidth());
5546 max = Qualifiers::MaxAddressSpace - LangAS::FirstTargetAddressSpace;
5547 if (addrSpace > max) {
5548 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
5549 << (unsigned)max.getZExtValue() << ASArgExpr->getSourceRange();
5553 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()) +
5554 LangAS::FirstTargetAddressSpace;
5556 // The keyword-based type attributes imply which address space to use.
5557 switch (Attr.getKind()) {
5558 case AttributeList::AT_OpenCLGlobalAddressSpace:
5559 ASIdx = LangAS::opencl_global; break;
5560 case AttributeList::AT_OpenCLLocalAddressSpace:
5561 ASIdx = LangAS::opencl_local; break;
5562 case AttributeList::AT_OpenCLConstantAddressSpace:
5563 ASIdx = LangAS::opencl_constant; break;
5564 case AttributeList::AT_OpenCLGenericAddressSpace:
5565 ASIdx = LangAS::opencl_generic; break;
5567 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
5572 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5575 /// Does this type have a "direct" ownership qualifier? That is,
5576 /// is it written like "__strong id", as opposed to something like
5577 /// "typeof(foo)", where that happens to be strong?
5578 static bool hasDirectOwnershipQualifier(QualType type) {
5579 // Fast path: no qualifier at all.
5580 assert(type.getQualifiers().hasObjCLifetime());
5584 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5585 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5588 type = attr->getModifiedType();
5590 // X *__strong (...)
5591 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5592 type = paren->getInnerType();
5594 // That's it for things we want to complain about. In particular,
5595 // we do not want to look through typedefs, typeof(expr),
5596 // typeof(type), or any other way that the type is somehow
5605 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5606 /// attribute on the specified type.
5608 /// Returns 'true' if the attribute was handled.
5609 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5610 AttributeList &attr,
5612 bool NonObjCPointer = false;
5614 if (!type->isDependentType() && !type->isUndeducedType()) {
5615 if (const PointerType *ptr = type->getAs<PointerType>()) {
5616 QualType pointee = ptr->getPointeeType();
5617 if (pointee->isObjCRetainableType() || pointee->isPointerType())
5619 // It is important not to lose the source info that there was an attribute
5620 // applied to non-objc pointer. We will create an attributed type but
5621 // its type will be the same as the original type.
5622 NonObjCPointer = true;
5623 } else if (!type->isObjCRetainableType()) {
5627 // Don't accept an ownership attribute in the declspec if it would
5628 // just be the return type of a block pointer.
5629 if (state.isProcessingDeclSpec()) {
5630 Declarator &D = state.getDeclarator();
5631 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5632 /*onlyBlockPointers=*/true))
5637 Sema &S = state.getSema();
5638 SourceLocation AttrLoc = attr.getLoc();
5639 if (AttrLoc.isMacroID())
5640 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
5642 if (!attr.isArgIdent(0)) {
5643 S.Diag(AttrLoc, diag::err_attribute_argument_type)
5644 << attr.getName() << AANT_ArgumentString;
5649 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5650 Qualifiers::ObjCLifetime lifetime;
5651 if (II->isStr("none"))
5652 lifetime = Qualifiers::OCL_ExplicitNone;
5653 else if (II->isStr("strong"))
5654 lifetime = Qualifiers::OCL_Strong;
5655 else if (II->isStr("weak"))
5656 lifetime = Qualifiers::OCL_Weak;
5657 else if (II->isStr("autoreleasing"))
5658 lifetime = Qualifiers::OCL_Autoreleasing;
5660 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5661 << attr.getName() << II;
5666 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
5667 // outside of ARC mode.
5668 if (!S.getLangOpts().ObjCAutoRefCount &&
5669 lifetime != Qualifiers::OCL_Weak &&
5670 lifetime != Qualifiers::OCL_ExplicitNone) {
5674 SplitQualType underlyingType = type.split();
5676 // Check for redundant/conflicting ownership qualifiers.
5677 if (Qualifiers::ObjCLifetime previousLifetime
5678 = type.getQualifiers().getObjCLifetime()) {
5679 // If it's written directly, that's an error.
5680 if (hasDirectOwnershipQualifier(type)) {
5681 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5686 // Otherwise, if the qualifiers actually conflict, pull sugar off
5687 // and remove the ObjCLifetime qualifiers.
5688 if (previousLifetime != lifetime) {
5689 // It's possible to have multiple local ObjCLifetime qualifiers. We
5690 // can't stop after we reach a type that is directly qualified.
5691 const Type *prevTy = nullptr;
5692 while (!prevTy || prevTy != underlyingType.Ty) {
5693 prevTy = underlyingType.Ty;
5694 underlyingType = underlyingType.getSingleStepDesugaredType();
5696 underlyingType.Quals.removeObjCLifetime();
5700 underlyingType.Quals.addObjCLifetime(lifetime);
5702 if (NonObjCPointer) {
5703 StringRef name = attr.getName()->getName();
5705 case Qualifiers::OCL_None:
5706 case Qualifiers::OCL_ExplicitNone:
5708 case Qualifiers::OCL_Strong: name = "__strong"; break;
5709 case Qualifiers::OCL_Weak: name = "__weak"; break;
5710 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5712 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5713 << TDS_ObjCObjOrBlock << type;
5716 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
5717 // because having both 'T' and '__unsafe_unretained T' exist in the type
5718 // system causes unfortunate widespread consistency problems. (For example,
5719 // they're not considered compatible types, and we mangle them identicially
5720 // as template arguments.) These problems are all individually fixable,
5721 // but it's easier to just not add the qualifier and instead sniff it out
5722 // in specific places using isObjCInertUnsafeUnretainedType().
5724 // Doing this does means we miss some trivial consistency checks that
5725 // would've triggered in ARC, but that's better than trying to solve all
5726 // the coexistence problems with __unsafe_unretained.
5727 if (!S.getLangOpts().ObjCAutoRefCount &&
5728 lifetime == Qualifiers::OCL_ExplicitNone) {
5729 type = S.Context.getAttributedType(
5730 AttributedType::attr_objc_inert_unsafe_unretained,
5735 QualType origType = type;
5736 if (!NonObjCPointer)
5737 type = S.Context.getQualifiedType(underlyingType);
5739 // If we have a valid source location for the attribute, use an
5740 // AttributedType instead.
5741 if (AttrLoc.isValid())
5742 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
5745 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
5746 unsigned diagnostic, QualType type) {
5747 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
5748 S.DelayedDiagnostics.add(
5749 sema::DelayedDiagnostic::makeForbiddenType(
5750 S.getSourceManager().getExpansionLoc(loc),
5751 diagnostic, type, /*ignored*/ 0));
5753 S.Diag(loc, diagnostic);
5757 // Sometimes, __weak isn't allowed.
5758 if (lifetime == Qualifiers::OCL_Weak &&
5759 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
5761 // Use a specialized diagnostic if the runtime just doesn't support them.
5762 unsigned diagnostic =
5763 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
5764 : diag::err_arc_weak_no_runtime);
5766 // In any case, delay the diagnostic until we know what we're parsing.
5767 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
5773 // Forbid __weak for class objects marked as
5774 // objc_arc_weak_reference_unavailable
5775 if (lifetime == Qualifiers::OCL_Weak) {
5776 if (const ObjCObjectPointerType *ObjT =
5777 type->getAs<ObjCObjectPointerType>()) {
5778 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
5779 if (Class->isArcWeakrefUnavailable()) {
5780 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
5781 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
5782 diag::note_class_declared);
5791 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
5792 /// attribute on the specified type. Returns true to indicate that
5793 /// the attribute was handled, false to indicate that the type does
5794 /// not permit the attribute.
5795 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
5796 AttributeList &attr,
5798 Sema &S = state.getSema();
5800 // Delay if this isn't some kind of pointer.
5801 if (!type->isPointerType() &&
5802 !type->isObjCObjectPointerType() &&
5803 !type->isBlockPointerType())
5806 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
5807 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
5812 // Check the attribute arguments.
5813 if (!attr.isArgIdent(0)) {
5814 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
5815 << attr.getName() << AANT_ArgumentString;
5819 Qualifiers::GC GCAttr;
5820 if (attr.getNumArgs() > 1) {
5821 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5822 << attr.getName() << 1;
5827 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5828 if (II->isStr("weak"))
5829 GCAttr = Qualifiers::Weak;
5830 else if (II->isStr("strong"))
5831 GCAttr = Qualifiers::Strong;
5833 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
5834 << attr.getName() << II;
5839 QualType origType = type;
5840 type = S.Context.getObjCGCQualType(origType, GCAttr);
5842 // Make an attributed type to preserve the source information.
5843 if (attr.getLoc().isValid())
5844 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
5851 /// A helper class to unwrap a type down to a function for the
5852 /// purposes of applying attributes there.
5855 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
5856 /// if (unwrapped.isFunctionType()) {
5857 /// const FunctionType *fn = unwrapped.get();
5858 /// // change fn somehow
5859 /// T = unwrapped.wrap(fn);
5861 struct FunctionTypeUnwrapper {
5873 const FunctionType *Fn;
5874 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
5876 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
5878 const Type *Ty = T.getTypePtr();
5879 if (isa<FunctionType>(Ty)) {
5880 Fn = cast<FunctionType>(Ty);
5882 } else if (isa<ParenType>(Ty)) {
5883 T = cast<ParenType>(Ty)->getInnerType();
5884 Stack.push_back(Parens);
5885 } else if (isa<PointerType>(Ty)) {
5886 T = cast<PointerType>(Ty)->getPointeeType();
5887 Stack.push_back(Pointer);
5888 } else if (isa<BlockPointerType>(Ty)) {
5889 T = cast<BlockPointerType>(Ty)->getPointeeType();
5890 Stack.push_back(BlockPointer);
5891 } else if (isa<MemberPointerType>(Ty)) {
5892 T = cast<MemberPointerType>(Ty)->getPointeeType();
5893 Stack.push_back(MemberPointer);
5894 } else if (isa<ReferenceType>(Ty)) {
5895 T = cast<ReferenceType>(Ty)->getPointeeType();
5896 Stack.push_back(Reference);
5897 } else if (isa<AttributedType>(Ty)) {
5898 T = cast<AttributedType>(Ty)->getEquivalentType();
5899 Stack.push_back(Attributed);
5901 const Type *DTy = Ty->getUnqualifiedDesugaredType();
5907 T = QualType(DTy, 0);
5908 Stack.push_back(Desugar);
5913 bool isFunctionType() const { return (Fn != nullptr); }
5914 const FunctionType *get() const { return Fn; }
5916 QualType wrap(Sema &S, const FunctionType *New) {
5917 // If T wasn't modified from the unwrapped type, do nothing.
5918 if (New == get()) return Original;
5921 return wrap(S.Context, Original, 0);
5925 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
5926 if (I == Stack.size())
5927 return C.getQualifiedType(Fn, Old.getQualifiers());
5929 // Build up the inner type, applying the qualifiers from the old
5930 // type to the new type.
5931 SplitQualType SplitOld = Old.split();
5933 // As a special case, tail-recurse if there are no qualifiers.
5934 if (SplitOld.Quals.empty())
5935 return wrap(C, SplitOld.Ty, I);
5936 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
5939 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
5940 if (I == Stack.size()) return QualType(Fn, 0);
5942 switch (static_cast<WrapKind>(Stack[I++])) {
5944 // This is the point at which we potentially lose source
5946 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
5949 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
5952 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
5953 return C.getParenType(New);
5957 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
5958 return C.getPointerType(New);
5961 case BlockPointer: {
5962 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
5963 return C.getBlockPointerType(New);
5966 case MemberPointer: {
5967 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
5968 QualType New = wrap(C, OldMPT->getPointeeType(), I);
5969 return C.getMemberPointerType(New, OldMPT->getClass());
5973 const ReferenceType *OldRef = cast<ReferenceType>(Old);
5974 QualType New = wrap(C, OldRef->getPointeeType(), I);
5975 if (isa<LValueReferenceType>(OldRef))
5976 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
5978 return C.getRValueReferenceType(New);
5982 llvm_unreachable("unknown wrapping kind");
5985 } // end anonymous namespace
5987 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
5988 AttributeList &Attr,
5990 Sema &S = State.getSema();
5992 AttributeList::Kind Kind = Attr.getKind();
5993 QualType Desugared = Type;
5994 const AttributedType *AT = dyn_cast<AttributedType>(Type);
5996 AttributedType::Kind CurAttrKind = AT->getAttrKind();
5998 // You cannot specify duplicate type attributes, so if the attribute has
5999 // already been applied, flag it.
6000 if (getAttrListKind(CurAttrKind) == Kind) {
6001 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
6006 // You cannot have both __sptr and __uptr on the same type, nor can you
6007 // have __ptr32 and __ptr64.
6008 if ((CurAttrKind == AttributedType::attr_ptr32 &&
6009 Kind == AttributeList::AT_Ptr64) ||
6010 (CurAttrKind == AttributedType::attr_ptr64 &&
6011 Kind == AttributeList::AT_Ptr32)) {
6012 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
6013 << "'__ptr32'" << "'__ptr64'";
6015 } else if ((CurAttrKind == AttributedType::attr_sptr &&
6016 Kind == AttributeList::AT_UPtr) ||
6017 (CurAttrKind == AttributedType::attr_uptr &&
6018 Kind == AttributeList::AT_SPtr)) {
6019 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
6020 << "'__sptr'" << "'__uptr'";
6024 Desugared = AT->getEquivalentType();
6025 AT = dyn_cast<AttributedType>(Desugared);
6028 // Pointer type qualifiers can only operate on pointer types, but not
6029 // pointer-to-member types.
6030 if (!isa<PointerType>(Desugared)) {
6031 if (Type->isMemberPointerType())
6032 S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers)
6035 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
6036 << Attr.getName() << 0;
6040 AttributedType::Kind TAK;
6042 default: llvm_unreachable("Unknown attribute kind");
6043 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
6044 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
6045 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
6046 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
6049 Type = S.Context.getAttributedType(TAK, Type, Type);
6053 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
6054 NullabilityKind nullability,
6055 SourceLocation nullabilityLoc,
6056 bool isContextSensitive,
6057 bool allowOnArrayType) {
6058 recordNullabilitySeen(*this, nullabilityLoc);
6060 // Check for existing nullability attributes on the type.
6061 QualType desugared = type;
6062 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
6063 // Check whether there is already a null
6064 if (auto existingNullability = attributed->getImmediateNullability()) {
6065 // Duplicated nullability.
6066 if (nullability == *existingNullability) {
6067 Diag(nullabilityLoc, diag::warn_nullability_duplicate)
6068 << DiagNullabilityKind(nullability, isContextSensitive)
6069 << FixItHint::CreateRemoval(nullabilityLoc);
6074 // Conflicting nullability.
6075 Diag(nullabilityLoc, diag::err_nullability_conflicting)
6076 << DiagNullabilityKind(nullability, isContextSensitive)
6077 << DiagNullabilityKind(*existingNullability, false);
6081 desugared = attributed->getModifiedType();
6084 // If there is already a different nullability specifier, complain.
6085 // This (unlike the code above) looks through typedefs that might
6086 // have nullability specifiers on them, which means we cannot
6087 // provide a useful Fix-It.
6088 if (auto existingNullability = desugared->getNullability(Context)) {
6089 if (nullability != *existingNullability) {
6090 Diag(nullabilityLoc, diag::err_nullability_conflicting)
6091 << DiagNullabilityKind(nullability, isContextSensitive)
6092 << DiagNullabilityKind(*existingNullability, false);
6094 // Try to find the typedef with the existing nullability specifier.
6095 if (auto typedefType = desugared->getAs<TypedefType>()) {
6096 TypedefNameDecl *typedefDecl = typedefType->getDecl();
6097 QualType underlyingType = typedefDecl->getUnderlyingType();
6098 if (auto typedefNullability
6099 = AttributedType::stripOuterNullability(underlyingType)) {
6100 if (*typedefNullability == *existingNullability) {
6101 Diag(typedefDecl->getLocation(), diag::note_nullability_here)
6102 << DiagNullabilityKind(*existingNullability, false);
6111 // If this definitely isn't a pointer type, reject the specifier.
6112 if (!desugared->canHaveNullability() &&
6113 !(allowOnArrayType && desugared->isArrayType())) {
6114 Diag(nullabilityLoc, diag::err_nullability_nonpointer)
6115 << DiagNullabilityKind(nullability, isContextSensitive) << type;
6119 // For the context-sensitive keywords/Objective-C property
6120 // attributes, require that the type be a single-level pointer.
6121 if (isContextSensitive) {
6122 // Make sure that the pointee isn't itself a pointer type.
6123 const Type *pointeeType;
6124 if (desugared->isArrayType())
6125 pointeeType = desugared->getArrayElementTypeNoTypeQual();
6127 pointeeType = desugared->getPointeeType().getTypePtr();
6129 if (pointeeType->isAnyPointerType() ||
6130 pointeeType->isObjCObjectPointerType() ||
6131 pointeeType->isMemberPointerType()) {
6132 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
6133 << DiagNullabilityKind(nullability, true)
6135 Diag(nullabilityLoc, diag::note_nullability_type_specifier)
6136 << DiagNullabilityKind(nullability, false)
6138 << FixItHint::CreateReplacement(nullabilityLoc,
6139 getNullabilitySpelling(nullability));
6144 // Form the attributed type.
6145 type = Context.getAttributedType(
6146 AttributedType::getNullabilityAttrKind(nullability), type, type);
6150 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
6151 if (isa<ObjCTypeParamType>(type)) {
6152 // Build the attributed type to record where __kindof occurred.
6153 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6158 // Find out if it's an Objective-C object or object pointer type;
6159 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
6160 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
6161 : type->getAs<ObjCObjectType>();
6163 // If not, we can't apply __kindof.
6165 // FIXME: Handle dependent types that aren't yet object types.
6166 Diag(loc, diag::err_objc_kindof_nonobject)
6171 // Rebuild the "equivalent" type, which pushes __kindof down into
6173 // There is no need to apply kindof on an unqualified id type.
6174 QualType equivType = Context.getObjCObjectType(
6175 objType->getBaseType(), objType->getTypeArgsAsWritten(),
6176 objType->getProtocols(),
6177 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
6179 // If we started with an object pointer type, rebuild it.
6181 equivType = Context.getObjCObjectPointerType(equivType);
6182 if (auto nullability = type->getNullability(Context)) {
6183 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
6184 equivType = Context.getAttributedType(attrKind, equivType, equivType);
6188 // Build the attributed type to record where __kindof occurred.
6189 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6196 /// Map a nullability attribute kind to a nullability kind.
6197 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
6199 case AttributeList::AT_TypeNonNull:
6200 return NullabilityKind::NonNull;
6202 case AttributeList::AT_TypeNullable:
6203 return NullabilityKind::Nullable;
6205 case AttributeList::AT_TypeNullUnspecified:
6206 return NullabilityKind::Unspecified;
6209 llvm_unreachable("not a nullability attribute kind");
6213 /// Distribute a nullability type attribute that cannot be applied to
6214 /// the type specifier to a pointer, block pointer, or member pointer
6215 /// declarator, complaining if necessary.
6217 /// \returns true if the nullability annotation was distributed, false
6219 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
6221 AttributeList &attr) {
6222 Declarator &declarator = state.getDeclarator();
6224 /// Attempt to move the attribute to the specified chunk.
6225 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
6226 // If there is already a nullability attribute there, don't add
6228 if (hasNullabilityAttr(chunk.getAttrListRef()))
6231 // Complain about the nullability qualifier being in the wrong
6238 PK_MemberFunctionPointer,
6240 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
6242 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
6243 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
6245 auto diag = state.getSema().Diag(attr.getLoc(),
6246 diag::warn_nullability_declspec)
6247 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
6248 attr.isContextSensitiveKeywordAttribute())
6250 << static_cast<unsigned>(pointerKind);
6252 // FIXME: MemberPointer chunks don't carry the location of the *.
6253 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
6254 diag << FixItHint::CreateRemoval(attr.getLoc())
6255 << FixItHint::CreateInsertion(
6256 state.getSema().getPreprocessor()
6257 .getLocForEndOfToken(chunk.Loc),
6258 " " + attr.getName()->getName().str() + " ");
6261 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
6262 chunk.getAttrListRef());
6266 // Move it to the outermost pointer, member pointer, or block
6267 // pointer declarator.
6268 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
6269 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6270 switch (chunk.Kind) {
6271 case DeclaratorChunk::Pointer:
6272 case DeclaratorChunk::BlockPointer:
6273 case DeclaratorChunk::MemberPointer:
6274 return moveToChunk(chunk, false);
6276 case DeclaratorChunk::Paren:
6277 case DeclaratorChunk::Array:
6280 case DeclaratorChunk::Function:
6281 // Try to move past the return type to a function/block/member
6282 // function pointer.
6283 if (DeclaratorChunk *dest = maybeMovePastReturnType(
6285 /*onlyBlockPointers=*/false)) {
6286 return moveToChunk(*dest, true);
6291 // Don't walk through these.
6292 case DeclaratorChunk::Reference:
6293 case DeclaratorChunk::Pipe:
6301 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
6302 assert(!Attr.isInvalid());
6303 switch (Attr.getKind()) {
6305 llvm_unreachable("not a calling convention attribute");
6306 case AttributeList::AT_CDecl:
6307 return AttributedType::attr_cdecl;
6308 case AttributeList::AT_FastCall:
6309 return AttributedType::attr_fastcall;
6310 case AttributeList::AT_StdCall:
6311 return AttributedType::attr_stdcall;
6312 case AttributeList::AT_ThisCall:
6313 return AttributedType::attr_thiscall;
6314 case AttributeList::AT_RegCall:
6315 return AttributedType::attr_regcall;
6316 case AttributeList::AT_Pascal:
6317 return AttributedType::attr_pascal;
6318 case AttributeList::AT_SwiftCall:
6319 return AttributedType::attr_swiftcall;
6320 case AttributeList::AT_VectorCall:
6321 return AttributedType::attr_vectorcall;
6322 case AttributeList::AT_Pcs: {
6323 // The attribute may have had a fixit applied where we treated an
6324 // identifier as a string literal. The contents of the string are valid,
6325 // but the form may not be.
6327 if (Attr.isArgExpr(0))
6328 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6330 Str = Attr.getArgAsIdent(0)->Ident->getName();
6331 return llvm::StringSwitch<AttributedType::Kind>(Str)
6332 .Case("aapcs", AttributedType::attr_pcs)
6333 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
6335 case AttributeList::AT_IntelOclBicc:
6336 return AttributedType::attr_inteloclbicc;
6337 case AttributeList::AT_MSABI:
6338 return AttributedType::attr_ms_abi;
6339 case AttributeList::AT_SysVABI:
6340 return AttributedType::attr_sysv_abi;
6341 case AttributeList::AT_PreserveMost:
6342 return AttributedType::attr_preserve_most;
6343 case AttributeList::AT_PreserveAll:
6344 return AttributedType::attr_preserve_all;
6346 llvm_unreachable("unexpected attribute kind!");
6349 /// Process an individual function attribute. Returns true to
6350 /// indicate that the attribute was handled, false if it wasn't.
6351 static bool handleFunctionTypeAttr(TypeProcessingState &state,
6352 AttributeList &attr,
6354 Sema &S = state.getSema();
6356 FunctionTypeUnwrapper unwrapped(S, type);
6358 if (attr.getKind() == AttributeList::AT_NoReturn) {
6359 if (S.CheckNoReturnAttr(attr))
6362 // Delay if this is not a function type.
6363 if (!unwrapped.isFunctionType())
6366 // Otherwise we can process right away.
6367 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6368 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6372 // ns_returns_retained is not always a type attribute, but if we got
6373 // here, we're treating it as one right now.
6374 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
6375 assert(S.getLangOpts().ObjCAutoRefCount &&
6376 "ns_returns_retained treated as type attribute in non-ARC");
6377 if (attr.getNumArgs()) return true;
6379 // Delay if this is not a function type.
6380 if (!unwrapped.isFunctionType())
6383 FunctionType::ExtInfo EI
6384 = unwrapped.get()->getExtInfo().withProducesResult(true);
6385 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6389 if (attr.getKind() == AttributeList::AT_AnyX86NoCallerSavedRegisters) {
6390 if (S.CheckNoCallerSavedRegsAttr(attr))
6393 // Delay if this is not a function type.
6394 if (!unwrapped.isFunctionType())
6397 FunctionType::ExtInfo EI =
6398 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
6399 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6403 if (attr.getKind() == AttributeList::AT_Regparm) {
6405 if (S.CheckRegparmAttr(attr, value))
6408 // Delay if this is not a function type.
6409 if (!unwrapped.isFunctionType())
6412 // Diagnose regparm with fastcall.
6413 const FunctionType *fn = unwrapped.get();
6414 CallingConv CC = fn->getCallConv();
6415 if (CC == CC_X86FastCall) {
6416 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6417 << FunctionType::getNameForCallConv(CC)
6423 FunctionType::ExtInfo EI =
6424 unwrapped.get()->getExtInfo().withRegParm(value);
6425 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6429 // Delay if the type didn't work out to a function.
6430 if (!unwrapped.isFunctionType()) return false;
6432 // Otherwise, a calling convention.
6434 if (S.CheckCallingConvAttr(attr, CC))
6437 const FunctionType *fn = unwrapped.get();
6438 CallingConv CCOld = fn->getCallConv();
6439 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
6442 // Error out on when there's already an attribute on the type
6443 // and the CCs don't match.
6444 const AttributedType *AT = S.getCallingConvAttributedType(type);
6445 if (AT && AT->getAttrKind() != CCAttrKind) {
6446 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6447 << FunctionType::getNameForCallConv(CC)
6448 << FunctionType::getNameForCallConv(CCOld);
6454 // Diagnose use of variadic functions with calling conventions that
6455 // don't support them (e.g. because they're callee-cleanup).
6456 // We delay warning about this on unprototyped function declarations
6457 // until after redeclaration checking, just in case we pick up a
6458 // prototype that way. And apparently we also "delay" warning about
6459 // unprototyped function types in general, despite not necessarily having
6460 // much ability to diagnose it later.
6461 if (!supportsVariadicCall(CC)) {
6462 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6463 if (FnP && FnP->isVariadic()) {
6464 unsigned DiagID = diag::err_cconv_varargs;
6466 // stdcall and fastcall are ignored with a warning for GCC and MS
6468 bool IsInvalid = true;
6469 if (CC == CC_X86StdCall || CC == CC_X86FastCall) {
6470 DiagID = diag::warn_cconv_varargs;
6474 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
6475 if (IsInvalid) attr.setInvalid();
6480 // Also diagnose fastcall with regparm.
6481 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
6482 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6483 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
6488 // Modify the CC from the wrapped function type, wrap it all back, and then
6489 // wrap the whole thing in an AttributedType as written. The modified type
6490 // might have a different CC if we ignored the attribute.
6491 QualType Equivalent;
6495 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
6497 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6499 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
6503 bool Sema::hasExplicitCallingConv(QualType &T) {
6504 QualType R = T.IgnoreParens();
6505 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
6506 if (AT->isCallingConv())
6508 R = AT->getModifiedType().IgnoreParens();
6513 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
6514 SourceLocation Loc) {
6515 FunctionTypeUnwrapper Unwrapped(*this, T);
6516 const FunctionType *FT = Unwrapped.get();
6517 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
6518 cast<FunctionProtoType>(FT)->isVariadic());
6519 CallingConv CurCC = FT->getCallConv();
6520 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
6525 // MS compiler ignores explicit calling convention attributes on structors. We
6526 // should do the same.
6527 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
6528 // Issue a warning on ignored calling convention -- except of __stdcall.
6529 // Again, this is what MS compiler does.
6530 if (CurCC != CC_X86StdCall)
6531 Diag(Loc, diag::warn_cconv_structors)
6532 << FunctionType::getNameForCallConv(CurCC);
6533 // Default adjustment.
6535 // Only adjust types with the default convention. For example, on Windows
6536 // we should adjust a __cdecl type to __thiscall for instance methods, and a
6537 // __thiscall type to __cdecl for static methods.
6538 CallingConv DefaultCC =
6539 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6541 if (CurCC != DefaultCC || DefaultCC == ToCC)
6544 if (hasExplicitCallingConv(T))
6548 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6549 QualType Wrapped = Unwrapped.wrap(*this, FT);
6550 T = Context.getAdjustedType(T, Wrapped);
6553 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6554 /// and float scalars, although arrays, pointers, and function return values are
6555 /// allowed in conjunction with this construct. Aggregates with this attribute
6556 /// are invalid, even if they are of the same size as a corresponding scalar.
6557 /// The raw attribute should contain precisely 1 argument, the vector size for
6558 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6559 /// this routine will return a new vector type.
6560 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
6562 // Check the attribute arguments.
6563 if (Attr.getNumArgs() != 1) {
6564 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6565 << Attr.getName() << 1;
6569 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6570 llvm::APSInt vecSize(32);
6571 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
6572 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
6573 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6574 << Attr.getName() << AANT_ArgumentIntegerConstant
6575 << sizeExpr->getSourceRange();
6579 // The base type must be integer (not Boolean or enumeration) or float, and
6580 // can't already be a vector.
6581 if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
6582 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
6583 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6587 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6588 // vecSize is specified in bytes - convert to bits.
6589 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
6591 // the vector size needs to be an integral multiple of the type size.
6592 if (vectorSize % typeSize) {
6593 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
6594 << sizeExpr->getSourceRange();
6598 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
6599 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
6600 << sizeExpr->getSourceRange();
6604 if (vectorSize == 0) {
6605 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
6606 << sizeExpr->getSourceRange();
6611 // Success! Instantiate the vector type, the number of elements is > 0, and
6612 // not required to be a power of 2, unlike GCC.
6613 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
6614 VectorType::GenericVector);
6617 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
6619 static void HandleExtVectorTypeAttr(QualType &CurType,
6620 const AttributeList &Attr,
6622 // check the attribute arguments.
6623 if (Attr.getNumArgs() != 1) {
6624 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6625 << Attr.getName() << 1;
6631 // Special case where the argument is a template id.
6632 if (Attr.isArgIdent(0)) {
6634 SourceLocation TemplateKWLoc;
6636 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6638 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6640 if (Size.isInvalid())
6643 sizeExpr = Size.get();
6645 sizeExpr = Attr.getArgAsExpr(0);
6648 // Create the vector type.
6649 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6654 static bool isPermittedNeonBaseType(QualType &Ty,
6655 VectorType::VectorKind VecKind, Sema &S) {
6656 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6660 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6662 // Signed poly is mathematically wrong, but has been baked into some ABIs by
6664 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6665 Triple.getArch() == llvm::Triple::aarch64_be;
6666 if (VecKind == VectorType::NeonPolyVector) {
6667 if (IsPolyUnsigned) {
6668 // AArch64 polynomial vectors are unsigned and support poly64.
6669 return BTy->getKind() == BuiltinType::UChar ||
6670 BTy->getKind() == BuiltinType::UShort ||
6671 BTy->getKind() == BuiltinType::ULong ||
6672 BTy->getKind() == BuiltinType::ULongLong;
6674 // AArch32 polynomial vector are signed.
6675 return BTy->getKind() == BuiltinType::SChar ||
6676 BTy->getKind() == BuiltinType::Short;
6680 // Non-polynomial vector types: the usual suspects are allowed, as well as
6681 // float64_t on AArch64.
6682 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6683 Triple.getArch() == llvm::Triple::aarch64_be;
6685 if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6688 return BTy->getKind() == BuiltinType::SChar ||
6689 BTy->getKind() == BuiltinType::UChar ||
6690 BTy->getKind() == BuiltinType::Short ||
6691 BTy->getKind() == BuiltinType::UShort ||
6692 BTy->getKind() == BuiltinType::Int ||
6693 BTy->getKind() == BuiltinType::UInt ||
6694 BTy->getKind() == BuiltinType::Long ||
6695 BTy->getKind() == BuiltinType::ULong ||
6696 BTy->getKind() == BuiltinType::LongLong ||
6697 BTy->getKind() == BuiltinType::ULongLong ||
6698 BTy->getKind() == BuiltinType::Float ||
6699 BTy->getKind() == BuiltinType::Half;
6702 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6703 /// "neon_polyvector_type" attributes are used to create vector types that
6704 /// are mangled according to ARM's ABI. Otherwise, these types are identical
6705 /// to those created with the "vector_size" attribute. Unlike "vector_size"
6706 /// the argument to these Neon attributes is the number of vector elements,
6707 /// not the vector size in bytes. The vector width and element type must
6708 /// match one of the standard Neon vector types.
6709 static void HandleNeonVectorTypeAttr(QualType& CurType,
6710 const AttributeList &Attr, Sema &S,
6711 VectorType::VectorKind VecKind) {
6712 // Target must have NEON
6713 if (!S.Context.getTargetInfo().hasFeature("neon")) {
6714 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6718 // Check the attribute arguments.
6719 if (Attr.getNumArgs() != 1) {
6720 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6721 << Attr.getName() << 1;
6725 // The number of elements must be an ICE.
6726 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6727 llvm::APSInt numEltsInt(32);
6728 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6729 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6730 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6731 << Attr.getName() << AANT_ArgumentIntegerConstant
6732 << numEltsExpr->getSourceRange();
6736 // Only certain element types are supported for Neon vectors.
6737 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6738 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6743 // The total size of the vector must be 64 or 128 bits.
6744 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6745 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6746 unsigned vecSize = typeSize * numElts;
6747 if (vecSize != 64 && vecSize != 128) {
6748 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6753 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6756 /// Handle OpenCL Access Qualifier Attribute.
6757 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr,
6759 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
6760 if (!(CurType->isImageType() || CurType->isPipeType())) {
6761 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
6766 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
6767 QualType PointeeTy = TypedefTy->desugar();
6768 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
6770 std::string PrevAccessQual;
6771 switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) {
6772 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6773 case BuiltinType::Id: \
6774 PrevAccessQual = #Access; \
6776 #include "clang/Basic/OpenCLImageTypes.def"
6778 assert(0 && "Unable to find corresponding image type.");
6781 S.Diag(TypedefTy->getDecl()->getLocStart(),
6782 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
6783 } else if (CurType->isPipeType()) {
6784 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
6785 QualType ElemType = CurType->getAs<PipeType>()->getElementType();
6786 CurType = S.Context.getWritePipeType(ElemType);
6791 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
6792 TypeAttrLocation TAL, AttributeList *attrs) {
6793 // Scan through and apply attributes to this type where it makes sense. Some
6794 // attributes (such as __address_space__, __vector_size__, etc) apply to the
6795 // type, but others can be present in the type specifiers even though they
6796 // apply to the decl. Here we apply type attributes and ignore the rest.
6798 bool hasOpenCLAddressSpace = false;
6800 AttributeList &attr = *attrs;
6801 attrs = attr.getNext(); // reset to the next here due to early loop continue
6804 // Skip attributes that were marked to be invalid.
6805 if (attr.isInvalid())
6808 if (attr.isCXX11Attribute()) {
6809 // [[gnu::...]] attributes are treated as declaration attributes, so may
6810 // not appertain to a DeclaratorChunk, even if we handle them as type
6812 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
6813 if (TAL == TAL_DeclChunk) {
6814 state.getSema().Diag(attr.getLoc(),
6815 diag::warn_cxx11_gnu_attribute_on_type)
6819 } else if (TAL != TAL_DeclChunk) {
6820 // Otherwise, only consider type processing for a C++11 attribute if
6821 // it's actually been applied to a type.
6826 // If this is an attribute we can handle, do so now,
6827 // otherwise, add it to the FnAttrs list for rechaining.
6828 switch (attr.getKind()) {
6830 // A C++11 attribute on a declarator chunk must appertain to a type.
6831 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
6832 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
6834 attr.setUsedAsTypeAttr();
6838 case AttributeList::UnknownAttribute:
6839 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6840 state.getSema().Diag(attr.getLoc(),
6841 diag::warn_unknown_attribute_ignored)
6845 case AttributeList::IgnoredAttribute:
6848 case AttributeList::AT_MayAlias:
6849 // FIXME: This attribute needs to actually be handled, but if we ignore
6850 // it it breaks large amounts of Linux software.
6851 attr.setUsedAsTypeAttr();
6853 case AttributeList::AT_OpenCLPrivateAddressSpace:
6854 case AttributeList::AT_OpenCLGlobalAddressSpace:
6855 case AttributeList::AT_OpenCLLocalAddressSpace:
6856 case AttributeList::AT_OpenCLConstantAddressSpace:
6857 case AttributeList::AT_OpenCLGenericAddressSpace:
6858 case AttributeList::AT_AddressSpace:
6859 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
6860 attr.setUsedAsTypeAttr();
6861 hasOpenCLAddressSpace = true;
6863 OBJC_POINTER_TYPE_ATTRS_CASELIST:
6864 if (!handleObjCPointerTypeAttr(state, attr, type))
6865 distributeObjCPointerTypeAttr(state, attr, type);
6866 attr.setUsedAsTypeAttr();
6868 case AttributeList::AT_VectorSize:
6869 HandleVectorSizeAttr(type, attr, state.getSema());
6870 attr.setUsedAsTypeAttr();
6872 case AttributeList::AT_ExtVectorType:
6873 HandleExtVectorTypeAttr(type, attr, state.getSema());
6874 attr.setUsedAsTypeAttr();
6876 case AttributeList::AT_NeonVectorType:
6877 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6878 VectorType::NeonVector);
6879 attr.setUsedAsTypeAttr();
6881 case AttributeList::AT_NeonPolyVectorType:
6882 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6883 VectorType::NeonPolyVector);
6884 attr.setUsedAsTypeAttr();
6886 case AttributeList::AT_OpenCLAccess:
6887 HandleOpenCLAccessAttr(type, attr, state.getSema());
6888 attr.setUsedAsTypeAttr();
6891 MS_TYPE_ATTRS_CASELIST:
6892 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6893 attr.setUsedAsTypeAttr();
6897 NULLABILITY_TYPE_ATTRS_CASELIST:
6898 // Either add nullability here or try to distribute it. We
6899 // don't want to distribute the nullability specifier past any
6900 // dependent type, because that complicates the user model.
6901 if (type->canHaveNullability() || type->isDependentType() ||
6902 type->isArrayType() ||
6903 !distributeNullabilityTypeAttr(state, type, attr)) {
6905 if (TAL == TAL_DeclChunk)
6906 endIndex = state.getCurrentChunkIndex();
6908 endIndex = state.getDeclarator().getNumTypeObjects();
6909 bool allowOnArrayType =
6910 state.getDeclarator().isPrototypeContext() &&
6911 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
6912 if (state.getSema().checkNullabilityTypeSpecifier(
6914 mapNullabilityAttrKind(attr.getKind()),
6916 attr.isContextSensitiveKeywordAttribute(),
6917 allowOnArrayType)) {
6921 attr.setUsedAsTypeAttr();
6925 case AttributeList::AT_ObjCKindOf:
6926 // '__kindof' must be part of the decl-specifiers.
6933 state.getSema().Diag(attr.getLoc(),
6934 diag::err_objc_kindof_wrong_position)
6935 << FixItHint::CreateRemoval(attr.getLoc())
6936 << FixItHint::CreateInsertion(
6937 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6941 // Apply it regardless.
6942 if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6944 attr.setUsedAsTypeAttr();
6947 case AttributeList::AT_NSReturnsRetained:
6948 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6950 // fallthrough into the function attrs
6953 FUNCTION_TYPE_ATTRS_CASELIST:
6954 attr.setUsedAsTypeAttr();
6956 // Never process function type attributes as part of the
6957 // declaration-specifiers.
6958 if (TAL == TAL_DeclSpec)
6959 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6961 // Otherwise, handle the possible delays.
6962 else if (!handleFunctionTypeAttr(state, attr, type))
6963 distributeFunctionTypeAttr(state, attr, type);
6968 // If address space is not set, OpenCL 2.0 defines non private default
6969 // address spaces for some cases:
6970 // OpenCL 2.0, section 6.5:
6971 // The address space for a variable at program scope or a static variable
6972 // inside a function can either be __global or __constant, but defaults to
6973 // __global if not specified.
6975 // Pointers that are declared without pointing to a named address space point
6976 // to the generic address space.
6977 if (state.getSema().getLangOpts().OpenCLVersion >= 200 &&
6978 !hasOpenCLAddressSpace && type.getAddressSpace() == 0 &&
6979 (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) {
6980 Declarator &D = state.getDeclarator();
6981 if (state.getCurrentChunkIndex() > 0 &&
6982 (D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6983 DeclaratorChunk::Pointer ||
6984 D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6985 DeclaratorChunk::BlockPointer)) {
6986 type = state.getSema().Context.getAddrSpaceQualType(
6987 type, LangAS::opencl_generic);
6988 } else if (state.getCurrentChunkIndex() == 0 &&
6989 D.getContext() == Declarator::FileContext &&
6990 !D.isFunctionDeclarator() && !D.isFunctionDefinition() &&
6991 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6992 !type->isSamplerT())
6993 type = state.getSema().Context.getAddrSpaceQualType(
6994 type, LangAS::opencl_global);
6995 else if (state.getCurrentChunkIndex() == 0 &&
6996 D.getContext() == Declarator::BlockContext &&
6997 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
6998 type = state.getSema().Context.getAddrSpaceQualType(
6999 type, LangAS::opencl_global);
7003 void Sema::completeExprArrayBound(Expr *E) {
7004 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7005 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7006 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
7007 SourceLocation PointOfInstantiation = E->getExprLoc();
7009 if (MemberSpecializationInfo *MSInfo =
7010 Var->getMemberSpecializationInfo()) {
7011 // If we don't already have a point of instantiation, this is it.
7012 if (MSInfo->getPointOfInstantiation().isInvalid()) {
7013 MSInfo->setPointOfInstantiation(PointOfInstantiation);
7015 // This is a modification of an existing AST node. Notify
7017 if (ASTMutationListener *L = getASTMutationListener())
7018 L->StaticDataMemberInstantiated(Var);
7021 VarTemplateSpecializationDecl *VarSpec =
7022 cast<VarTemplateSpecializationDecl>(Var);
7023 if (VarSpec->getPointOfInstantiation().isInvalid())
7024 VarSpec->setPointOfInstantiation(PointOfInstantiation);
7027 InstantiateVariableDefinition(PointOfInstantiation, Var);
7029 // Update the type to the newly instantiated definition's type both
7030 // here and within the expression.
7031 if (VarDecl *Def = Var->getDefinition()) {
7033 QualType T = Def->getType();
7035 // FIXME: Update the type on all intervening expressions.
7039 // We still go on to try to complete the type independently, as it
7040 // may also require instantiations or diagnostics if it remains
7047 /// \brief Ensure that the type of the given expression is complete.
7049 /// This routine checks whether the expression \p E has a complete type. If the
7050 /// expression refers to an instantiable construct, that instantiation is
7051 /// performed as needed to complete its type. Furthermore
7052 /// Sema::RequireCompleteType is called for the expression's type (or in the
7053 /// case of a reference type, the referred-to type).
7055 /// \param E The expression whose type is required to be complete.
7056 /// \param Diagnoser The object that will emit a diagnostic if the type is
7059 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
7061 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
7062 QualType T = E->getType();
7064 // Incomplete array types may be completed by the initializer attached to
7065 // their definitions. For static data members of class templates and for
7066 // variable templates, we need to instantiate the definition to get this
7067 // initializer and complete the type.
7068 if (T->isIncompleteArrayType()) {
7069 completeExprArrayBound(E);
7073 // FIXME: Are there other cases which require instantiating something other
7074 // than the type to complete the type of an expression?
7076 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
7079 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
7080 BoundTypeDiagnoser<> Diagnoser(DiagID);
7081 return RequireCompleteExprType(E, Diagnoser);
7084 /// @brief Ensure that the type T is a complete type.
7086 /// This routine checks whether the type @p T is complete in any
7087 /// context where a complete type is required. If @p T is a complete
7088 /// type, returns false. If @p T is a class template specialization,
7089 /// this routine then attempts to perform class template
7090 /// instantiation. If instantiation fails, or if @p T is incomplete
7091 /// and cannot be completed, issues the diagnostic @p diag (giving it
7092 /// the type @p T) and returns true.
7094 /// @param Loc The location in the source that the incomplete type
7095 /// diagnostic should refer to.
7097 /// @param T The type that this routine is examining for completeness.
7099 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
7100 /// @c false otherwise.
7101 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7102 TypeDiagnoser &Diagnoser) {
7103 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
7105 if (const TagType *Tag = T->getAs<TagType>()) {
7106 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
7107 Tag->getDecl()->setCompleteDefinitionRequired();
7108 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
7114 /// \brief Determine whether there is any declaration of \p D that was ever a
7115 /// definition (perhaps before module merging) and is currently visible.
7116 /// \param D The definition of the entity.
7117 /// \param Suggested Filled in with the declaration that should be made visible
7118 /// in order to provide a definition of this entity.
7119 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
7120 /// not defined. This only matters for enums with a fixed underlying
7121 /// type, since in all other cases, a type is complete if and only if it
7123 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
7124 bool OnlyNeedComplete) {
7125 // Easy case: if we don't have modules, all declarations are visible.
7126 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
7129 // If this definition was instantiated from a template, map back to the
7130 // pattern from which it was instantiated.
7131 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
7132 // We're in the middle of defining it; this definition should be treated
7135 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
7136 if (auto *Pattern = RD->getTemplateInstantiationPattern())
7138 D = RD->getDefinition();
7139 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
7140 if (auto *Pattern = ED->getTemplateInstantiationPattern())
7142 if (OnlyNeedComplete && ED->isFixed()) {
7143 // If the enum has a fixed underlying type, and we're only looking for a
7144 // complete type (not a definition), any visible declaration of it will
7146 *Suggested = nullptr;
7147 for (auto *Redecl : ED->redecls()) {
7148 if (isVisible(Redecl))
7150 if (Redecl->isThisDeclarationADefinition() ||
7151 (Redecl->isCanonicalDecl() && !*Suggested))
7152 *Suggested = Redecl;
7156 D = ED->getDefinition();
7157 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7158 if (auto *Pattern = FD->getTemplateInstantiationPattern())
7160 D = FD->getDefinition();
7161 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
7162 if (auto *Pattern = VD->getTemplateInstantiationPattern())
7164 D = VD->getDefinition();
7166 assert(D && "missing definition for pattern of instantiated definition");
7172 // The external source may have additional definitions of this entity that are
7173 // visible, so complete the redeclaration chain now and ask again.
7174 if (auto *Source = Context.getExternalSource()) {
7175 Source->CompleteRedeclChain(D);
7176 return isVisible(D);
7182 /// Locks in the inheritance model for the given class and all of its bases.
7183 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
7184 RD = RD->getMostRecentDecl();
7185 if (!RD->hasAttr<MSInheritanceAttr>()) {
7186 MSInheritanceAttr::Spelling IM;
7188 switch (S.MSPointerToMemberRepresentationMethod) {
7189 case LangOptions::PPTMK_BestCase:
7190 IM = RD->calculateInheritanceModel();
7192 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
7193 IM = MSInheritanceAttr::Keyword_single_inheritance;
7195 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
7196 IM = MSInheritanceAttr::Keyword_multiple_inheritance;
7198 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
7199 IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
7203 RD->addAttr(MSInheritanceAttr::CreateImplicit(
7204 S.getASTContext(), IM,
7205 /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
7206 LangOptions::PPTMK_BestCase,
7207 S.ImplicitMSInheritanceAttrLoc.isValid()
7208 ? S.ImplicitMSInheritanceAttrLoc
7209 : RD->getSourceRange()));
7210 S.Consumer.AssignInheritanceModel(RD);
7214 /// \brief The implementation of RequireCompleteType
7215 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
7216 TypeDiagnoser *Diagnoser) {
7217 // FIXME: Add this assertion to make sure we always get instantiation points.
7218 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
7219 // FIXME: Add this assertion to help us flush out problems with
7220 // checking for dependent types and type-dependent expressions.
7222 // assert(!T->isDependentType() &&
7223 // "Can't ask whether a dependent type is complete");
7225 // We lock in the inheritance model once somebody has asked us to ensure
7226 // that a pointer-to-member type is complete.
7227 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7228 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
7229 if (!MPTy->getClass()->isDependentType()) {
7230 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
7231 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
7236 NamedDecl *Def = nullptr;
7237 bool Incomplete = T->isIncompleteType(&Def);
7239 // Check that any necessary explicit specializations are visible. For an
7240 // enum, we just need the declaration, so don't check this.
7241 if (Def && !isa<EnumDecl>(Def))
7242 checkSpecializationVisibility(Loc, Def);
7244 // If we have a complete type, we're done.
7246 // If we know about the definition but it is not visible, complain.
7247 NamedDecl *SuggestedDef = nullptr;
7249 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
7250 // If the user is going to see an error here, recover by making the
7251 // definition visible.
7252 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
7254 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
7255 /*Recover*/TreatAsComplete);
7256 return !TreatAsComplete;
7262 const TagType *Tag = T->getAs<TagType>();
7263 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
7265 // If there's an unimported definition of this type in a module (for
7266 // instance, because we forward declared it, then imported the definition),
7267 // import that definition now.
7269 // FIXME: What about other cases where an import extends a redeclaration
7270 // chain for a declaration that can be accessed through a mechanism other
7271 // than name lookup (eg, referenced in a template, or a variable whose type
7272 // could be completed by the module)?
7274 // FIXME: Should we map through to the base array element type before
7275 // checking for a tag type?
7278 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
7280 // Avoid diagnosing invalid decls as incomplete.
7281 if (D->isInvalidDecl())
7284 // Give the external AST source a chance to complete the type.
7285 if (auto *Source = Context.getExternalSource()) {
7287 Source->CompleteType(Tag->getDecl());
7289 Source->CompleteType(IFace->getDecl());
7291 // If the external source completed the type, go through the motions
7292 // again to ensure we're allowed to use the completed type.
7293 if (!T->isIncompleteType())
7294 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7298 // If we have a class template specialization or a class member of a
7299 // class template specialization, or an array with known size of such,
7300 // try to instantiate it.
7301 QualType MaybeTemplate = T;
7302 while (const ConstantArrayType *Array
7303 = Context.getAsConstantArrayType(MaybeTemplate))
7304 MaybeTemplate = Array->getElementType();
7305 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
7306 bool Instantiated = false;
7307 bool Diagnosed = false;
7308 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
7309 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
7310 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
7311 Diagnosed = InstantiateClassTemplateSpecialization(
7312 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
7313 /*Complain=*/Diagnoser);
7314 Instantiated = true;
7316 } else if (CXXRecordDecl *Rec
7317 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
7318 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
7319 if (!Rec->isBeingDefined() && Pattern) {
7320 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
7321 assert(MSI && "Missing member specialization information?");
7322 // This record was instantiated from a class within a template.
7323 if (MSI->getTemplateSpecializationKind() !=
7324 TSK_ExplicitSpecialization) {
7325 Diagnosed = InstantiateClass(Loc, Rec, Pattern,
7326 getTemplateInstantiationArgs(Rec),
7327 TSK_ImplicitInstantiation,
7328 /*Complain=*/Diagnoser);
7329 Instantiated = true;
7335 // Instantiate* might have already complained that the template is not
7336 // defined, if we asked it to.
7337 if (Diagnoser && Diagnosed)
7339 // If we instantiated a definition, check that it's usable, even if
7340 // instantiation produced an error, so that repeated calls to this
7341 // function give consistent answers.
7342 if (!T->isIncompleteType())
7343 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7347 // FIXME: If we didn't instantiate a definition because of an explicit
7348 // specialization declaration, check that it's visible.
7353 Diagnoser->diagnose(*this, Loc, T);
7355 // If the type was a forward declaration of a class/struct/union
7356 // type, produce a note.
7357 if (Tag && !Tag->getDecl()->isInvalidDecl())
7358 Diag(Tag->getDecl()->getLocation(),
7359 Tag->isBeingDefined() ? diag::note_type_being_defined
7360 : diag::note_forward_declaration)
7361 << QualType(Tag, 0);
7363 // If the Objective-C class was a forward declaration, produce a note.
7364 if (IFace && !IFace->getDecl()->isInvalidDecl())
7365 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
7367 // If we have external information that we can use to suggest a fix,
7370 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
7375 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7377 BoundTypeDiagnoser<> Diagnoser(DiagID);
7378 return RequireCompleteType(Loc, T, Diagnoser);
7381 /// \brief Get diagnostic %select index for tag kind for
7382 /// literal type diagnostic message.
7383 /// WARNING: Indexes apply to particular diagnostics only!
7385 /// \returns diagnostic %select index.
7386 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
7388 case TTK_Struct: return 0;
7389 case TTK_Interface: return 1;
7390 case TTK_Class: return 2;
7391 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
7395 /// @brief Ensure that the type T is a literal type.
7397 /// This routine checks whether the type @p T is a literal type. If @p T is an
7398 /// incomplete type, an attempt is made to complete it. If @p T is a literal
7399 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
7400 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
7401 /// it the type @p T), along with notes explaining why the type is not a
7402 /// literal type, and returns true.
7404 /// @param Loc The location in the source that the non-literal type
7405 /// diagnostic should refer to.
7407 /// @param T The type that this routine is examining for literalness.
7409 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
7411 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
7412 /// @c false otherwise.
7413 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
7414 TypeDiagnoser &Diagnoser) {
7415 assert(!T->isDependentType() && "type should not be dependent");
7417 QualType ElemType = Context.getBaseElementType(T);
7418 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
7419 T->isLiteralType(Context))
7422 Diagnoser.diagnose(*this, Loc, T);
7424 if (T->isVariableArrayType())
7427 const RecordType *RT = ElemType->getAs<RecordType>();
7431 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7433 // A partially-defined class type can't be a literal type, because a literal
7434 // class type must have a trivial destructor (which can't be checked until
7435 // the class definition is complete).
7436 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
7439 // If the class has virtual base classes, then it's not an aggregate, and
7440 // cannot have any constexpr constructors or a trivial default constructor,
7441 // so is non-literal. This is better to diagnose than the resulting absence
7442 // of constexpr constructors.
7443 if (RD->getNumVBases()) {
7444 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
7445 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
7446 for (const auto &I : RD->vbases())
7447 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
7448 << I.getSourceRange();
7449 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
7450 !RD->hasTrivialDefaultConstructor()) {
7451 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
7452 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
7453 for (const auto &I : RD->bases()) {
7454 if (!I.getType()->isLiteralType(Context)) {
7455 Diag(I.getLocStart(),
7456 diag::note_non_literal_base_class)
7457 << RD << I.getType() << I.getSourceRange();
7461 for (const auto *I : RD->fields()) {
7462 if (!I->getType()->isLiteralType(Context) ||
7463 I->getType().isVolatileQualified()) {
7464 Diag(I->getLocation(), diag::note_non_literal_field)
7465 << RD << I << I->getType()
7466 << I->getType().isVolatileQualified();
7470 } else if (!RD->hasTrivialDestructor()) {
7471 // All fields and bases are of literal types, so have trivial destructors.
7472 // If this class's destructor is non-trivial it must be user-declared.
7473 CXXDestructorDecl *Dtor = RD->getDestructor();
7474 assert(Dtor && "class has literal fields and bases but no dtor?");
7478 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
7479 diag::note_non_literal_user_provided_dtor :
7480 diag::note_non_literal_nontrivial_dtor) << RD;
7481 if (!Dtor->isUserProvided())
7482 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
7488 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
7489 BoundTypeDiagnoser<> Diagnoser(DiagID);
7490 return RequireLiteralType(Loc, T, Diagnoser);
7493 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
7494 /// and qualified by the nested-name-specifier contained in SS.
7495 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
7496 const CXXScopeSpec &SS, QualType T) {
7499 NestedNameSpecifier *NNS;
7501 NNS = SS.getScopeRep();
7503 if (Keyword == ETK_None)
7507 return Context.getElaboratedType(Keyword, NNS, T);
7510 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
7511 ExprResult ER = CheckPlaceholderExpr(E);
7512 if (ER.isInvalid()) return QualType();
7515 if (!getLangOpts().CPlusPlus && E->refersToBitField())
7516 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
7518 if (!E->isTypeDependent()) {
7519 QualType T = E->getType();
7520 if (const TagType *TT = T->getAs<TagType>())
7521 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
7523 return Context.getTypeOfExprType(E);
7526 /// getDecltypeForExpr - Given an expr, will return the decltype for
7527 /// that expression, according to the rules in C++11
7528 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
7529 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
7530 if (E->isTypeDependent())
7531 return S.Context.DependentTy;
7533 // C++11 [dcl.type.simple]p4:
7534 // The type denoted by decltype(e) is defined as follows:
7536 // - if e is an unparenthesized id-expression or an unparenthesized class
7537 // member access (5.2.5), decltype(e) is the type of the entity named
7538 // by e. If there is no such entity, or if e names a set of overloaded
7539 // functions, the program is ill-formed;
7541 // We apply the same rules for Objective-C ivar and property references.
7542 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7543 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
7544 return VD->getType();
7545 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7546 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
7547 return FD->getType();
7548 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
7549 return IR->getDecl()->getType();
7550 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
7551 if (PR->isExplicitProperty())
7552 return PR->getExplicitProperty()->getType();
7553 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
7554 return PE->getType();
7557 // C++11 [expr.lambda.prim]p18:
7558 // Every occurrence of decltype((x)) where x is a possibly
7559 // parenthesized id-expression that names an entity of automatic
7560 // storage duration is treated as if x were transformed into an
7561 // access to a corresponding data member of the closure type that
7562 // would have been declared if x were an odr-use of the denoted
7564 using namespace sema;
7565 if (S.getCurLambda()) {
7566 if (isa<ParenExpr>(E)) {
7567 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7568 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7569 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
7571 return S.Context.getLValueReferenceType(T);
7578 // C++11 [dcl.type.simple]p4:
7580 QualType T = E->getType();
7581 switch (E->getValueKind()) {
7582 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
7584 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
7585 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
7587 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
7588 // - otherwise, decltype(e) is the type of e.
7589 case VK_RValue: break;
7595 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
7596 bool AsUnevaluated) {
7597 ExprResult ER = CheckPlaceholderExpr(E);
7598 if (ER.isInvalid()) return QualType();
7601 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
7602 E->HasSideEffects(Context, false)) {
7603 // The expression operand for decltype is in an unevaluated expression
7604 // context, so side effects could result in unintended consequences.
7605 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7608 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
7611 QualType Sema::BuildUnaryTransformType(QualType BaseType,
7612 UnaryTransformType::UTTKind UKind,
7613 SourceLocation Loc) {
7615 case UnaryTransformType::EnumUnderlyingType:
7616 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
7617 Diag(Loc, diag::err_only_enums_have_underlying_types);
7620 QualType Underlying = BaseType;
7621 if (!BaseType->isDependentType()) {
7622 // The enum could be incomplete if we're parsing its definition or
7623 // recovering from an error.
7624 NamedDecl *FwdDecl = nullptr;
7625 if (BaseType->isIncompleteType(&FwdDecl)) {
7626 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
7627 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
7631 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
7632 assert(ED && "EnumType has no EnumDecl");
7634 DiagnoseUseOfDecl(ED, Loc);
7636 Underlying = ED->getIntegerType();
7637 assert(!Underlying.isNull());
7639 return Context.getUnaryTransformType(BaseType, Underlying,
7640 UnaryTransformType::EnumUnderlyingType);
7643 llvm_unreachable("unknown unary transform type");
7646 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
7647 if (!T->isDependentType()) {
7648 // FIXME: It isn't entirely clear whether incomplete atomic types
7649 // are allowed or not; for simplicity, ban them for the moment.
7650 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
7653 int DisallowedKind = -1;
7654 if (T->isArrayType())
7656 else if (T->isFunctionType())
7658 else if (T->isReferenceType())
7660 else if (T->isAtomicType())
7662 else if (T.hasQualifiers())
7664 else if (!T.isTriviallyCopyableType(Context))
7665 // Some other non-trivially-copyable type (probably a C++ class)
7668 if (DisallowedKind != -1) {
7669 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
7673 // FIXME: Do we need any handling for ARC here?
7676 // Build the pointer type.
7677 return Context.getAtomicType(T);