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/ASTStructuralEquivalence.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/ScopeInfo.h"
32 #include "clang/Sema/SemaInternal.h"
33 #include "clang/Sema/Template.h"
34 #include "clang/Sema/TemplateInstCallback.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/Support/ErrorHandling.h"
40 using namespace clang;
42 enum TypeDiagSelector {
48 /// isOmittedBlockReturnType - Return true if this declarator is missing a
49 /// return type because this is a omitted return type on a block literal.
50 static bool isOmittedBlockReturnType(const Declarator &D) {
51 if (D.getContext() != DeclaratorContext::BlockLiteralContext ||
52 D.getDeclSpec().hasTypeSpecifier())
55 if (D.getNumTypeObjects() == 0)
56 return true; // ^{ ... }
58 if (D.getNumTypeObjects() == 1 &&
59 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
60 return true; // ^(int X, float Y) { ... }
65 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
66 /// doesn't apply to the given type.
67 static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
69 TypeDiagSelector WhichType;
70 bool useExpansionLoc = true;
71 switch (attr.getKind()) {
72 case ParsedAttr::AT_ObjCGC:
73 WhichType = TDS_Pointer;
75 case ParsedAttr::AT_ObjCOwnership:
76 WhichType = TDS_ObjCObjOrBlock;
79 // Assume everything else was a function attribute.
80 WhichType = TDS_Function;
81 useExpansionLoc = false;
85 SourceLocation loc = attr.getLoc();
86 StringRef name = attr.getName()->getName();
88 // The GC attributes are usually written with macros; special-case them.
89 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
91 if (useExpansionLoc && loc.isMacroID() && II) {
92 if (II->isStr("strong")) {
93 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
94 } else if (II->isStr("weak")) {
95 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
99 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
103 // objc_gc applies to Objective-C pointers or, otherwise, to the
104 // smallest available pointer type (i.e. 'void*' in 'void**').
105 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
106 case ParsedAttr::AT_ObjCGC: \
107 case ParsedAttr::AT_ObjCOwnership
109 // Calling convention attributes.
110 #define CALLING_CONV_ATTRS_CASELIST \
111 case ParsedAttr::AT_CDecl: \
112 case ParsedAttr::AT_FastCall: \
113 case ParsedAttr::AT_StdCall: \
114 case ParsedAttr::AT_ThisCall: \
115 case ParsedAttr::AT_RegCall: \
116 case ParsedAttr::AT_Pascal: \
117 case ParsedAttr::AT_SwiftCall: \
118 case ParsedAttr::AT_VectorCall: \
119 case ParsedAttr::AT_MSABI: \
120 case ParsedAttr::AT_SysVABI: \
121 case ParsedAttr::AT_Pcs: \
122 case ParsedAttr::AT_IntelOclBicc: \
123 case ParsedAttr::AT_PreserveMost: \
124 case ParsedAttr::AT_PreserveAll
126 // Function type attributes.
127 #define FUNCTION_TYPE_ATTRS_CASELIST \
128 case ParsedAttr::AT_NSReturnsRetained: \
129 case ParsedAttr::AT_NoReturn: \
130 case ParsedAttr::AT_Regparm: \
131 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
132 case ParsedAttr::AT_AnyX86NoCfCheck: \
133 CALLING_CONV_ATTRS_CASELIST
135 // Microsoft-specific type qualifiers.
136 #define MS_TYPE_ATTRS_CASELIST \
137 case ParsedAttr::AT_Ptr32: \
138 case ParsedAttr::AT_Ptr64: \
139 case ParsedAttr::AT_SPtr: \
140 case ParsedAttr::AT_UPtr
142 // Nullability qualifiers.
143 #define NULLABILITY_TYPE_ATTRS_CASELIST \
144 case ParsedAttr::AT_TypeNonNull: \
145 case ParsedAttr::AT_TypeNullable: \
146 case ParsedAttr::AT_TypeNullUnspecified
149 /// An object which stores processing state for the entire
150 /// GetTypeForDeclarator process.
151 class TypeProcessingState {
154 /// The declarator being processed.
155 Declarator &declarator;
157 /// The index of the declarator chunk we're currently processing.
158 /// May be the total number of valid chunks, indicating the
162 /// Whether there are non-trivial modifications to the decl spec.
165 /// Whether we saved the attributes in the decl spec.
168 /// The original set of attributes on the DeclSpec.
169 SmallVector<ParsedAttr *, 2> savedAttrs;
171 /// A list of attributes to diagnose the uselessness of when the
172 /// processing is complete.
173 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
176 TypeProcessingState(Sema &sema, Declarator &declarator)
177 : sema(sema), declarator(declarator),
178 chunkIndex(declarator.getNumTypeObjects()),
179 trivial(true), hasSavedAttrs(false) {}
181 Sema &getSema() const {
185 Declarator &getDeclarator() const {
189 bool isProcessingDeclSpec() const {
190 return chunkIndex == declarator.getNumTypeObjects();
193 unsigned getCurrentChunkIndex() const {
197 void setCurrentChunkIndex(unsigned idx) {
198 assert(idx <= declarator.getNumTypeObjects());
202 ParsedAttributesView &getCurrentAttributes() const {
203 if (isProcessingDeclSpec())
204 return getMutableDeclSpec().getAttributes();
205 return declarator.getTypeObject(chunkIndex).getAttrs();
208 /// Save the current set of attributes on the DeclSpec.
209 void saveDeclSpecAttrs() {
210 // Don't try to save them multiple times.
211 if (hasSavedAttrs) return;
213 DeclSpec &spec = getMutableDeclSpec();
214 for (ParsedAttr &AL : spec.getAttributes())
215 savedAttrs.push_back(&AL);
216 trivial &= savedAttrs.empty();
217 hasSavedAttrs = true;
220 /// Record that we had nowhere to put the given type attribute.
221 /// We will diagnose such attributes later.
222 void addIgnoredTypeAttr(ParsedAttr &attr) {
223 ignoredTypeAttrs.push_back(&attr);
226 /// Diagnose all the ignored type attributes, given that the
227 /// declarator worked out to the given type.
228 void diagnoseIgnoredTypeAttrs(QualType type) const {
229 for (auto *Attr : ignoredTypeAttrs)
230 diagnoseBadTypeAttribute(getSema(), *Attr, type);
233 ~TypeProcessingState() {
236 restoreDeclSpecAttrs();
240 DeclSpec &getMutableDeclSpec() const {
241 return const_cast<DeclSpec&>(declarator.getDeclSpec());
244 void restoreDeclSpecAttrs() {
245 assert(hasSavedAttrs);
247 getMutableDeclSpec().getAttributes().clearListOnly();
248 for (ParsedAttr *AL : savedAttrs)
249 getMutableDeclSpec().getAttributes().addAtStart(AL);
252 } // end anonymous namespace
254 static void moveAttrFromListToList(ParsedAttr &attr,
255 ParsedAttributesView &fromList,
256 ParsedAttributesView &toList) {
257 fromList.remove(&attr);
258 toList.addAtStart(&attr);
261 /// The location of a type attribute.
262 enum TypeAttrLocation {
263 /// The attribute is in the decl-specifier-seq.
265 /// The attribute is part of a DeclaratorChunk.
267 /// The attribute is immediately after the declaration's name.
271 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
272 TypeAttrLocation TAL, ParsedAttributesView &attrs);
274 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
277 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
278 ParsedAttr &attr, QualType &type);
280 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
283 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
284 ParsedAttr &attr, QualType &type);
286 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
287 ParsedAttr &attr, QualType &type) {
288 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
289 return handleObjCGCTypeAttr(state, attr, type);
290 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
291 return handleObjCOwnershipTypeAttr(state, attr, type);
294 /// Given the index of a declarator chunk, check whether that chunk
295 /// directly specifies the return type of a function and, if so, find
296 /// an appropriate place for it.
298 /// \param i - a notional index which the search will start
299 /// immediately inside
301 /// \param onlyBlockPointers Whether we should only look into block
302 /// pointer types (vs. all pointer types).
303 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
305 bool onlyBlockPointers) {
306 assert(i <= declarator.getNumTypeObjects());
308 DeclaratorChunk *result = nullptr;
310 // First, look inwards past parens for a function declarator.
311 for (; i != 0; --i) {
312 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
313 switch (fnChunk.Kind) {
314 case DeclaratorChunk::Paren:
317 // If we find anything except a function, bail out.
318 case DeclaratorChunk::Pointer:
319 case DeclaratorChunk::BlockPointer:
320 case DeclaratorChunk::Array:
321 case DeclaratorChunk::Reference:
322 case DeclaratorChunk::MemberPointer:
323 case DeclaratorChunk::Pipe:
326 // If we do find a function declarator, scan inwards from that,
327 // looking for a (block-)pointer declarator.
328 case DeclaratorChunk::Function:
329 for (--i; i != 0; --i) {
330 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
331 switch (ptrChunk.Kind) {
332 case DeclaratorChunk::Paren:
333 case DeclaratorChunk::Array:
334 case DeclaratorChunk::Function:
335 case DeclaratorChunk::Reference:
336 case DeclaratorChunk::Pipe:
339 case DeclaratorChunk::MemberPointer:
340 case DeclaratorChunk::Pointer:
341 if (onlyBlockPointers)
346 case DeclaratorChunk::BlockPointer:
350 llvm_unreachable("bad declarator chunk kind");
353 // If we run out of declarators doing that, we're done.
356 llvm_unreachable("bad declarator chunk kind");
358 // Okay, reconsider from our new point.
362 // Ran out of chunks, bail out.
366 /// Given that an objc_gc attribute was written somewhere on a
367 /// declaration *other* than on the declarator itself (for which, use
368 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
369 /// didn't apply in whatever position it was written in, try to move
370 /// it to a more appropriate position.
371 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
372 ParsedAttr &attr, QualType type) {
373 Declarator &declarator = state.getDeclarator();
375 // Move it to the outermost normal or block pointer declarator.
376 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
377 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
378 switch (chunk.Kind) {
379 case DeclaratorChunk::Pointer:
380 case DeclaratorChunk::BlockPointer: {
381 // But don't move an ARC ownership attribute to the return type
383 DeclaratorChunk *destChunk = nullptr;
384 if (state.isProcessingDeclSpec() &&
385 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
386 destChunk = maybeMovePastReturnType(declarator, i - 1,
387 /*onlyBlockPointers=*/true);
388 if (!destChunk) destChunk = &chunk;
390 moveAttrFromListToList(attr, state.getCurrentAttributes(),
391 destChunk->getAttrs());
395 case DeclaratorChunk::Paren:
396 case DeclaratorChunk::Array:
399 // We may be starting at the return type of a block.
400 case DeclaratorChunk::Function:
401 if (state.isProcessingDeclSpec() &&
402 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
403 if (DeclaratorChunk *dest = maybeMovePastReturnType(
405 /*onlyBlockPointers=*/true)) {
406 moveAttrFromListToList(attr, state.getCurrentAttributes(),
413 // Don't walk through these.
414 case DeclaratorChunk::Reference:
415 case DeclaratorChunk::MemberPointer:
416 case DeclaratorChunk::Pipe:
422 diagnoseBadTypeAttribute(state.getSema(), attr, type);
425 /// Distribute an objc_gc type attribute that was written on the
427 static void distributeObjCPointerTypeAttrFromDeclarator(
428 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
429 Declarator &declarator = state.getDeclarator();
431 // objc_gc goes on the innermost pointer to something that's not a
433 unsigned innermost = -1U;
434 bool considerDeclSpec = true;
435 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
436 DeclaratorChunk &chunk = declarator.getTypeObject(i);
437 switch (chunk.Kind) {
438 case DeclaratorChunk::Pointer:
439 case DeclaratorChunk::BlockPointer:
443 case DeclaratorChunk::Reference:
444 case DeclaratorChunk::MemberPointer:
445 case DeclaratorChunk::Paren:
446 case DeclaratorChunk::Array:
447 case DeclaratorChunk::Pipe:
450 case DeclaratorChunk::Function:
451 considerDeclSpec = false;
457 // That might actually be the decl spec if we weren't blocked by
458 // anything in the declarator.
459 if (considerDeclSpec) {
460 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
461 // Splice the attribute into the decl spec. Prevents the
462 // attribute from being applied multiple times and gives
463 // the source-location-filler something to work with.
464 state.saveDeclSpecAttrs();
465 moveAttrFromListToList(attr, declarator.getAttributes(),
466 declarator.getMutableDeclSpec().getAttributes());
471 // Otherwise, if we found an appropriate chunk, splice the attribute
473 if (innermost != -1U) {
474 moveAttrFromListToList(attr, declarator.getAttributes(),
475 declarator.getTypeObject(innermost).getAttrs());
479 // Otherwise, diagnose when we're done building the type.
480 declarator.getAttributes().remove(&attr);
481 state.addIgnoredTypeAttr(attr);
484 /// A function type attribute was written somewhere in a declaration
485 /// *other* than on the declarator itself or in the decl spec. Given
486 /// that it didn't apply in whatever position it was written in, try
487 /// to move it to a more appropriate position.
488 static void distributeFunctionTypeAttr(TypeProcessingState &state,
489 ParsedAttr &attr, QualType type) {
490 Declarator &declarator = state.getDeclarator();
492 // Try to push the attribute from the return type of a function to
493 // the function itself.
494 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
495 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
496 switch (chunk.Kind) {
497 case DeclaratorChunk::Function:
498 moveAttrFromListToList(attr, state.getCurrentAttributes(),
502 case DeclaratorChunk::Paren:
503 case DeclaratorChunk::Pointer:
504 case DeclaratorChunk::BlockPointer:
505 case DeclaratorChunk::Array:
506 case DeclaratorChunk::Reference:
507 case DeclaratorChunk::MemberPointer:
508 case DeclaratorChunk::Pipe:
513 diagnoseBadTypeAttribute(state.getSema(), attr, type);
516 /// Try to distribute a function type attribute to the innermost
517 /// function chunk or type. Returns true if the attribute was
518 /// distributed, false if no location was found.
519 static bool distributeFunctionTypeAttrToInnermost(
520 TypeProcessingState &state, ParsedAttr &attr,
521 ParsedAttributesView &attrList, QualType &declSpecType) {
522 Declarator &declarator = state.getDeclarator();
524 // Put it on the innermost function chunk, if there is one.
525 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
526 DeclaratorChunk &chunk = declarator.getTypeObject(i);
527 if (chunk.Kind != DeclaratorChunk::Function) continue;
529 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
533 return handleFunctionTypeAttr(state, attr, declSpecType);
536 /// A function type attribute was written in the decl spec. Try to
537 /// apply it somewhere.
538 static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
540 QualType &declSpecType) {
541 state.saveDeclSpecAttrs();
543 // C++11 attributes before the decl specifiers actually appertain to
544 // the declarators. Move them straight there. We don't support the
545 // 'put them wherever you like' semantics we allow for GNU attributes.
546 if (attr.isCXX11Attribute()) {
547 moveAttrFromListToList(attr, state.getCurrentAttributes(),
548 state.getDeclarator().getAttributes());
552 // Try to distribute to the innermost.
553 if (distributeFunctionTypeAttrToInnermost(
554 state, attr, state.getCurrentAttributes(), declSpecType))
557 // If that failed, diagnose the bad attribute when the declarator is
559 state.addIgnoredTypeAttr(attr);
562 /// A function type attribute was written on the declarator. Try to
563 /// apply it somewhere.
564 static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
566 QualType &declSpecType) {
567 Declarator &declarator = state.getDeclarator();
569 // Try to distribute to the innermost.
570 if (distributeFunctionTypeAttrToInnermost(
571 state, attr, declarator.getAttributes(), declSpecType))
574 // If that failed, diagnose the bad attribute when the declarator is
576 declarator.getAttributes().remove(&attr);
577 state.addIgnoredTypeAttr(attr);
580 /// Given that there are attributes written on the declarator
581 /// itself, try to distribute any type attributes to the appropriate
582 /// declarator chunk.
584 /// These are attributes like the following:
587 /// but not necessarily this:
589 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
590 QualType &declSpecType) {
591 // Collect all the type attributes from the declarator itself.
592 assert(!state.getDeclarator().getAttributes().empty() &&
593 "declarator has no attrs!");
594 // The called functions in this loop actually remove things from the current
595 // list, so iterating over the existing list isn't possible. Instead, make a
596 // non-owning copy and iterate over that.
597 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
598 for (ParsedAttr &attr : AttrsCopy) {
599 // Do not distribute C++11 attributes. They have strict rules for what
600 // they appertain to.
601 if (attr.isCXX11Attribute())
604 switch (attr.getKind()) {
605 OBJC_POINTER_TYPE_ATTRS_CASELIST:
606 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
609 FUNCTION_TYPE_ATTRS_CASELIST:
610 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
613 MS_TYPE_ATTRS_CASELIST:
614 // Microsoft type attributes cannot go after the declarator-id.
617 NULLABILITY_TYPE_ATTRS_CASELIST:
618 // Nullability specifiers cannot go after the declarator-id.
620 // Objective-C __kindof does not get distributed.
621 case ParsedAttr::AT_ObjCKindOf:
630 /// Add a synthetic '()' to a block-literal declarator if it is
631 /// required, given the return type.
632 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
633 QualType declSpecType) {
634 Declarator &declarator = state.getDeclarator();
636 // First, check whether the declarator would produce a function,
637 // i.e. whether the innermost semantic chunk is a function.
638 if (declarator.isFunctionDeclarator()) {
639 // If so, make that declarator a prototyped declarator.
640 declarator.getFunctionTypeInfo().hasPrototype = true;
644 // If there are any type objects, the type as written won't name a
645 // function, regardless of the decl spec type. This is because a
646 // block signature declarator is always an abstract-declarator, and
647 // abstract-declarators can't just be parentheses chunks. Therefore
648 // we need to build a function chunk unless there are no type
649 // objects and the decl spec type is a function.
650 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
653 // Note that there *are* cases with invalid declarators where
654 // declarators consist solely of parentheses. In general, these
655 // occur only in failed efforts to make function declarators, so
656 // faking up the function chunk is still the right thing to do.
658 // Otherwise, we need to fake up a function declarator.
659 SourceLocation loc = declarator.getLocStart();
661 // ...and *prepend* it to the declarator.
662 SourceLocation NoLoc;
663 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
665 /*IsAmbiguous=*/false,
669 /*EllipsisLoc=*/NoLoc,
672 /*RefQualifierIsLvalueRef=*/true,
673 /*RefQualifierLoc=*/NoLoc,
674 /*ConstQualifierLoc=*/NoLoc,
675 /*VolatileQualifierLoc=*/NoLoc,
676 /*RestrictQualifierLoc=*/NoLoc,
677 /*MutableLoc=*/NoLoc, EST_None,
678 /*ESpecRange=*/SourceRange(),
679 /*Exceptions=*/nullptr,
680 /*ExceptionRanges=*/nullptr,
682 /*NoexceptExpr=*/nullptr,
683 /*ExceptionSpecTokens=*/nullptr,
684 /*DeclsInPrototype=*/None,
685 loc, loc, declarator));
687 // For consistency, make sure the state still has us as processing
689 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
690 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
693 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
698 // If this occurs outside a template instantiation, warn the user about
699 // it; they probably didn't mean to specify a redundant qualifier.
700 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
701 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
702 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
703 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
704 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
705 if (!(RemoveTQs & Qual.first))
708 if (!S.inTemplateInstantiation()) {
709 if (TypeQuals & Qual.first)
710 S.Diag(Qual.second, DiagID)
711 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
712 << FixItHint::CreateRemoval(Qual.second);
715 TypeQuals &= ~Qual.first;
719 /// Return true if this is omitted block return type. Also check type
720 /// attributes and type qualifiers when returning true.
721 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
723 if (!isOmittedBlockReturnType(declarator))
726 // Warn if we see type attributes for omitted return type on a block literal.
727 SmallVector<ParsedAttr *, 2> ToBeRemoved;
728 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
729 if (AL.isInvalid() || !AL.isTypeAttr())
732 diag::warn_block_literal_attributes_on_omitted_return_type)
734 ToBeRemoved.push_back(&AL);
736 // Remove bad attributes from the list.
737 for (ParsedAttr *AL : ToBeRemoved)
738 declarator.getMutableDeclSpec().getAttributes().remove(AL);
740 // Warn if we see type qualifiers for omitted return type on a block literal.
741 const DeclSpec &DS = declarator.getDeclSpec();
742 unsigned TypeQuals = DS.getTypeQualifiers();
743 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
744 diag::warn_block_literal_qualifiers_on_omitted_return_type);
745 declarator.getMutableDeclSpec().ClearTypeQualifiers();
750 /// Apply Objective-C type arguments to the given type.
751 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
752 ArrayRef<TypeSourceInfo *> typeArgs,
753 SourceRange typeArgsRange,
754 bool failOnError = false) {
755 // We can only apply type arguments to an Objective-C class type.
756 const auto *objcObjectType = type->getAs<ObjCObjectType>();
757 if (!objcObjectType || !objcObjectType->getInterface()) {
758 S.Diag(loc, diag::err_objc_type_args_non_class)
767 // The class type must be parameterized.
768 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
769 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
771 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
772 << objcClass->getDeclName()
773 << FixItHint::CreateRemoval(typeArgsRange);
781 // The type must not already be specialized.
782 if (objcObjectType->isSpecialized()) {
783 S.Diag(loc, diag::err_objc_type_args_specialized_class)
785 << FixItHint::CreateRemoval(typeArgsRange);
793 // Check the type arguments.
794 SmallVector<QualType, 4> finalTypeArgs;
795 unsigned numTypeParams = typeParams->size();
796 bool anyPackExpansions = false;
797 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
798 TypeSourceInfo *typeArgInfo = typeArgs[i];
799 QualType typeArg = typeArgInfo->getType();
801 // Type arguments cannot have explicit qualifiers or nullability.
802 // We ignore indirect sources of these, e.g. behind typedefs or
803 // template arguments.
804 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
805 bool diagnosed = false;
806 SourceRange rangeToRemove;
807 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
808 rangeToRemove = attr.getLocalSourceRange();
809 if (attr.getTypePtr()->getImmediateNullability()) {
810 typeArg = attr.getTypePtr()->getModifiedType();
811 S.Diag(attr.getLocStart(),
812 diag::err_objc_type_arg_explicit_nullability)
813 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
819 S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified)
820 << typeArg << typeArg.getQualifiers().getAsString()
821 << FixItHint::CreateRemoval(rangeToRemove);
825 // Remove qualifiers even if they're non-local.
826 typeArg = typeArg.getUnqualifiedType();
828 finalTypeArgs.push_back(typeArg);
830 if (typeArg->getAs<PackExpansionType>())
831 anyPackExpansions = true;
833 // Find the corresponding type parameter, if there is one.
834 ObjCTypeParamDecl *typeParam = nullptr;
835 if (!anyPackExpansions) {
836 if (i < numTypeParams) {
837 typeParam = typeParams->begin()[i];
839 // Too many arguments.
840 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
842 << objcClass->getDeclName()
843 << (unsigned)typeArgs.size()
845 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
855 // Objective-C object pointer types must be substitutable for the bounds.
856 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
857 // If we don't have a type parameter to match against, assume
858 // everything is fine. There was a prior pack expansion that
859 // means we won't be able to match anything.
861 assert(anyPackExpansions && "Too many arguments?");
865 // Retrieve the bound.
866 QualType bound = typeParam->getUnderlyingType();
867 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
869 // Determine whether the type argument is substitutable for the bound.
870 if (typeArgObjC->isObjCIdType()) {
871 // When the type argument is 'id', the only acceptable type
872 // parameter bound is 'id'.
873 if (boundObjC->isObjCIdType())
875 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
876 // Otherwise, we follow the assignability rules.
880 // Diagnose the mismatch.
881 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
882 diag::err_objc_type_arg_does_not_match_bound)
883 << typeArg << bound << typeParam->getDeclName();
884 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
885 << typeParam->getDeclName();
893 // Block pointer types are permitted for unqualified 'id' bounds.
894 if (typeArg->isBlockPointerType()) {
895 // If we don't have a type parameter to match against, assume
896 // everything is fine. There was a prior pack expansion that
897 // means we won't be able to match anything.
899 assert(anyPackExpansions && "Too many arguments?");
903 // Retrieve the bound.
904 QualType bound = typeParam->getUnderlyingType();
905 if (bound->isBlockCompatibleObjCPointerType(S.Context))
908 // Diagnose the mismatch.
909 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
910 diag::err_objc_type_arg_does_not_match_bound)
911 << typeArg << bound << typeParam->getDeclName();
912 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
913 << typeParam->getDeclName();
921 // Dependent types will be checked at instantiation time.
922 if (typeArg->isDependentType()) {
926 // Diagnose non-id-compatible type arguments.
927 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
928 diag::err_objc_type_arg_not_id_compatible)
930 << typeArgInfo->getTypeLoc().getSourceRange();
938 // Make sure we didn't have the wrong number of arguments.
939 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
940 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
941 << (typeArgs.size() < typeParams->size())
942 << objcClass->getDeclName()
943 << (unsigned)finalTypeArgs.size()
944 << (unsigned)numTypeParams;
945 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
954 // Success. Form the specialized type.
955 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
958 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
959 SourceLocation ProtocolLAngleLoc,
960 ArrayRef<ObjCProtocolDecl *> Protocols,
961 ArrayRef<SourceLocation> ProtocolLocs,
962 SourceLocation ProtocolRAngleLoc,
964 QualType Result = QualType(Decl->getTypeForDecl(), 0);
965 if (!Protocols.empty()) {
967 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
970 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
971 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
972 if (FailOnError) Result = QualType();
974 if (FailOnError && Result.isNull())
981 QualType Sema::BuildObjCObjectType(QualType BaseType,
983 SourceLocation TypeArgsLAngleLoc,
984 ArrayRef<TypeSourceInfo *> TypeArgs,
985 SourceLocation TypeArgsRAngleLoc,
986 SourceLocation ProtocolLAngleLoc,
987 ArrayRef<ObjCProtocolDecl *> Protocols,
988 ArrayRef<SourceLocation> ProtocolLocs,
989 SourceLocation ProtocolRAngleLoc,
991 QualType Result = BaseType;
992 if (!TypeArgs.empty()) {
993 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
994 SourceRange(TypeArgsLAngleLoc,
997 if (FailOnError && Result.isNull())
1001 if (!Protocols.empty()) {
1003 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1006 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1007 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1008 if (FailOnError) Result = QualType();
1010 if (FailOnError && Result.isNull())
1017 TypeResult Sema::actOnObjCProtocolQualifierType(
1018 SourceLocation lAngleLoc,
1019 ArrayRef<Decl *> protocols,
1020 ArrayRef<SourceLocation> protocolLocs,
1021 SourceLocation rAngleLoc) {
1022 // Form id<protocol-list>.
1023 QualType Result = Context.getObjCObjectType(
1024 Context.ObjCBuiltinIdTy, { },
1026 (ObjCProtocolDecl * const *)protocols.data(),
1029 Result = Context.getObjCObjectPointerType(Result);
1031 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1032 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1034 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1035 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1037 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1038 .castAs<ObjCObjectTypeLoc>();
1039 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1040 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1042 // No type arguments.
1043 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1044 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1046 // Fill in protocol qualifiers.
1047 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1048 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1049 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1050 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1052 // We're done. Return the completed type to the parser.
1053 return CreateParsedType(Result, ResultTInfo);
1056 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1059 ParsedType BaseType,
1060 SourceLocation TypeArgsLAngleLoc,
1061 ArrayRef<ParsedType> TypeArgs,
1062 SourceLocation TypeArgsRAngleLoc,
1063 SourceLocation ProtocolLAngleLoc,
1064 ArrayRef<Decl *> Protocols,
1065 ArrayRef<SourceLocation> ProtocolLocs,
1066 SourceLocation ProtocolRAngleLoc) {
1067 TypeSourceInfo *BaseTypeInfo = nullptr;
1068 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1072 // Handle missing type-source info.
1074 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1076 // Extract type arguments.
1077 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1078 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1079 TypeSourceInfo *TypeArgInfo = nullptr;
1080 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1081 if (TypeArg.isNull()) {
1082 ActualTypeArgInfos.clear();
1086 assert(TypeArgInfo && "No type source info?");
1087 ActualTypeArgInfos.push_back(TypeArgInfo);
1090 // Build the object type.
1091 QualType Result = BuildObjCObjectType(
1092 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1093 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1095 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1097 ProtocolLocs, ProtocolRAngleLoc,
1098 /*FailOnError=*/false);
1103 // Create source information for this type.
1104 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1105 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1107 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1108 // object pointer type. Fill in source information for it.
1109 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1110 // The '*' is implicit.
1111 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1112 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1115 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1116 // Protocol qualifier information.
1117 if (OTPTL.getNumProtocols() > 0) {
1118 assert(OTPTL.getNumProtocols() == Protocols.size());
1119 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1120 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1121 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1122 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1125 // We're done. Return the completed type to the parser.
1126 return CreateParsedType(Result, ResultTInfo);
1129 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1131 // Type argument information.
1132 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1133 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1134 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1135 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1136 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1137 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1139 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1140 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1143 // Protocol qualifier information.
1144 if (ObjCObjectTL.getNumProtocols() > 0) {
1145 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1146 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1147 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1148 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1149 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1151 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1152 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1156 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1157 if (ObjCObjectTL.getType() == T)
1158 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1160 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1162 // We're done. Return the completed type to the parser.
1163 return CreateParsedType(Result, ResultTInfo);
1166 static OpenCLAccessAttr::Spelling
1167 getImageAccess(const ParsedAttributesView &Attrs) {
1168 for (const ParsedAttr &AL : Attrs)
1169 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1170 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1171 return OpenCLAccessAttr::Keyword_read_only;
1174 /// Convert the specified declspec to the appropriate type
1176 /// \param state Specifies the declarator containing the declaration specifier
1177 /// to be converted, along with other associated processing state.
1178 /// \returns The type described by the declaration specifiers. This function
1179 /// never returns null.
1180 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1181 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1184 Sema &S = state.getSema();
1185 Declarator &declarator = state.getDeclarator();
1186 DeclSpec &DS = declarator.getMutableDeclSpec();
1187 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1188 if (DeclLoc.isInvalid())
1189 DeclLoc = DS.getLocStart();
1191 ASTContext &Context = S.Context;
1194 switch (DS.getTypeSpecType()) {
1195 case DeclSpec::TST_void:
1196 Result = Context.VoidTy;
1198 case DeclSpec::TST_char:
1199 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1200 Result = Context.CharTy;
1201 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1202 Result = Context.SignedCharTy;
1204 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1205 "Unknown TSS value");
1206 Result = Context.UnsignedCharTy;
1209 case DeclSpec::TST_wchar:
1210 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1211 Result = Context.WCharTy;
1212 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1213 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1214 << DS.getSpecifierName(DS.getTypeSpecType(),
1215 Context.getPrintingPolicy());
1216 Result = Context.getSignedWCharType();
1218 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1219 "Unknown TSS value");
1220 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1221 << DS.getSpecifierName(DS.getTypeSpecType(),
1222 Context.getPrintingPolicy());
1223 Result = Context.getUnsignedWCharType();
1226 case DeclSpec::TST_char8:
1227 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1228 "Unknown TSS value");
1229 Result = Context.Char8Ty;
1231 case DeclSpec::TST_char16:
1232 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1233 "Unknown TSS value");
1234 Result = Context.Char16Ty;
1236 case DeclSpec::TST_char32:
1237 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1238 "Unknown TSS value");
1239 Result = Context.Char32Ty;
1241 case DeclSpec::TST_unspecified:
1242 // If this is a missing declspec in a block literal return context, then it
1243 // is inferred from the return statements inside the block.
1244 // The declspec is always missing in a lambda expr context; it is either
1245 // specified with a trailing return type or inferred.
1246 if (S.getLangOpts().CPlusPlus14 &&
1247 declarator.getContext() == DeclaratorContext::LambdaExprContext) {
1248 // In C++1y, a lambda's implicit return type is 'auto'.
1249 Result = Context.getAutoDeductType();
1251 } else if (declarator.getContext() ==
1252 DeclaratorContext::LambdaExprContext ||
1253 checkOmittedBlockReturnType(S, declarator,
1254 Context.DependentTy)) {
1255 Result = Context.DependentTy;
1259 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1260 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1261 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1262 // Note that the one exception to this is function definitions, which are
1263 // allowed to be completely missing a declspec. This is handled in the
1264 // parser already though by it pretending to have seen an 'int' in this
1266 if (S.getLangOpts().ImplicitInt) {
1267 // In C89 mode, we only warn if there is a completely missing declspec
1268 // when one is not allowed.
1270 S.Diag(DeclLoc, diag::ext_missing_declspec)
1271 << DS.getSourceRange()
1272 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
1274 } else if (!DS.hasTypeSpecifier()) {
1275 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1276 // "At least one type specifier shall be given in the declaration
1277 // specifiers in each declaration, and in the specifier-qualifier list in
1278 // each struct declaration and type name."
1279 if (S.getLangOpts().CPlusPlus) {
1280 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1281 << DS.getSourceRange();
1283 // When this occurs in C++ code, often something is very broken with the
1284 // value being declared, poison it as invalid so we don't get chains of
1286 declarator.setInvalidType(true);
1287 } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1288 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1289 << DS.getSourceRange();
1290 declarator.setInvalidType(true);
1292 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1293 << DS.getSourceRange();
1298 case DeclSpec::TST_int: {
1299 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
1300 switch (DS.getTypeSpecWidth()) {
1301 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1302 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
1303 case DeclSpec::TSW_long: Result = Context.LongTy; break;
1304 case DeclSpec::TSW_longlong:
1305 Result = Context.LongLongTy;
1307 // 'long long' is a C99 or C++11 feature.
1308 if (!S.getLangOpts().C99) {
1309 if (S.getLangOpts().CPlusPlus)
1310 S.Diag(DS.getTypeSpecWidthLoc(),
1311 S.getLangOpts().CPlusPlus11 ?
1312 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1314 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1319 switch (DS.getTypeSpecWidth()) {
1320 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1321 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
1322 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
1323 case DeclSpec::TSW_longlong:
1324 Result = Context.UnsignedLongLongTy;
1326 // 'long long' is a C99 or C++11 feature.
1327 if (!S.getLangOpts().C99) {
1328 if (S.getLangOpts().CPlusPlus)
1329 S.Diag(DS.getTypeSpecWidthLoc(),
1330 S.getLangOpts().CPlusPlus11 ?
1331 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1333 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1340 case DeclSpec::TST_accum: {
1341 switch (DS.getTypeSpecWidth()) {
1342 case DeclSpec::TSW_short:
1343 Result = Context.ShortAccumTy;
1345 case DeclSpec::TSW_unspecified:
1346 Result = Context.AccumTy;
1348 case DeclSpec::TSW_long:
1349 Result = Context.LongAccumTy;
1351 case DeclSpec::TSW_longlong:
1352 llvm_unreachable("Unable to specify long long as _Accum width");
1355 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1356 Result = Context.getCorrespondingUnsignedType(Result);
1358 if (DS.isTypeSpecSat())
1359 Result = Context.getCorrespondingSaturatedType(Result);
1363 case DeclSpec::TST_fract: {
1364 switch (DS.getTypeSpecWidth()) {
1365 case DeclSpec::TSW_short:
1366 Result = Context.ShortFractTy;
1368 case DeclSpec::TSW_unspecified:
1369 Result = Context.FractTy;
1371 case DeclSpec::TSW_long:
1372 Result = Context.LongFractTy;
1374 case DeclSpec::TSW_longlong:
1375 llvm_unreachable("Unable to specify long long as _Fract width");
1378 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1379 Result = Context.getCorrespondingUnsignedType(Result);
1381 if (DS.isTypeSpecSat())
1382 Result = Context.getCorrespondingSaturatedType(Result);
1386 case DeclSpec::TST_int128:
1387 if (!S.Context.getTargetInfo().hasInt128Type())
1388 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1390 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1391 Result = Context.UnsignedInt128Ty;
1393 Result = Context.Int128Ty;
1395 case DeclSpec::TST_float16: Result = Context.Float16Ty; break;
1396 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1397 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1398 case DeclSpec::TST_double:
1399 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1400 Result = Context.LongDoubleTy;
1402 Result = Context.DoubleTy;
1404 case DeclSpec::TST_float128:
1405 if (!S.Context.getTargetInfo().hasFloat128Type())
1406 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1408 Result = Context.Float128Ty;
1410 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1412 case DeclSpec::TST_decimal32: // _Decimal32
1413 case DeclSpec::TST_decimal64: // _Decimal64
1414 case DeclSpec::TST_decimal128: // _Decimal128
1415 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1416 Result = Context.IntTy;
1417 declarator.setInvalidType(true);
1419 case DeclSpec::TST_class:
1420 case DeclSpec::TST_enum:
1421 case DeclSpec::TST_union:
1422 case DeclSpec::TST_struct:
1423 case DeclSpec::TST_interface: {
1424 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1426 // This can happen in C++ with ambiguous lookups.
1427 Result = Context.IntTy;
1428 declarator.setInvalidType(true);
1432 // If the type is deprecated or unavailable, diagnose it.
1433 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1435 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1436 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1438 // TypeQuals handled by caller.
1439 Result = Context.getTypeDeclType(D);
1441 // In both C and C++, make an ElaboratedType.
1442 ElaboratedTypeKeyword Keyword
1443 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1444 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1445 DS.isTypeSpecOwned() ? D : nullptr);
1448 case DeclSpec::TST_typename: {
1449 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1450 DS.getTypeSpecSign() == 0 &&
1451 "Can't handle qualifiers on typedef names yet!");
1452 Result = S.GetTypeFromParser(DS.getRepAsType());
1453 if (Result.isNull()) {
1454 declarator.setInvalidType(true);
1457 // TypeQuals handled by caller.
1460 case DeclSpec::TST_typeofType:
1461 // FIXME: Preserve type source info.
1462 Result = S.GetTypeFromParser(DS.getRepAsType());
1463 assert(!Result.isNull() && "Didn't get a type for typeof?");
1464 if (!Result->isDependentType())
1465 if (const TagType *TT = Result->getAs<TagType>())
1466 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1467 // TypeQuals handled by caller.
1468 Result = Context.getTypeOfType(Result);
1470 case DeclSpec::TST_typeofExpr: {
1471 Expr *E = DS.getRepAsExpr();
1472 assert(E && "Didn't get an expression for typeof?");
1473 // TypeQuals handled by caller.
1474 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1475 if (Result.isNull()) {
1476 Result = Context.IntTy;
1477 declarator.setInvalidType(true);
1481 case DeclSpec::TST_decltype: {
1482 Expr *E = DS.getRepAsExpr();
1483 assert(E && "Didn't get an expression for decltype?");
1484 // TypeQuals handled by caller.
1485 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1486 if (Result.isNull()) {
1487 Result = Context.IntTy;
1488 declarator.setInvalidType(true);
1492 case DeclSpec::TST_underlyingType:
1493 Result = S.GetTypeFromParser(DS.getRepAsType());
1494 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1495 Result = S.BuildUnaryTransformType(Result,
1496 UnaryTransformType::EnumUnderlyingType,
1497 DS.getTypeSpecTypeLoc());
1498 if (Result.isNull()) {
1499 Result = Context.IntTy;
1500 declarator.setInvalidType(true);
1504 case DeclSpec::TST_auto:
1505 Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1508 case DeclSpec::TST_auto_type:
1509 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1512 case DeclSpec::TST_decltype_auto:
1513 Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1514 /*IsDependent*/ false);
1517 case DeclSpec::TST_unknown_anytype:
1518 Result = Context.UnknownAnyTy;
1521 case DeclSpec::TST_atomic:
1522 Result = S.GetTypeFromParser(DS.getRepAsType());
1523 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1524 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1525 if (Result.isNull()) {
1526 Result = Context.IntTy;
1527 declarator.setInvalidType(true);
1531 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1532 case DeclSpec::TST_##ImgType##_t: \
1533 switch (getImageAccess(DS.getAttributes())) { \
1534 case OpenCLAccessAttr::Keyword_write_only: \
1535 Result = Context.Id##WOTy; \
1537 case OpenCLAccessAttr::Keyword_read_write: \
1538 Result = Context.Id##RWTy; \
1540 case OpenCLAccessAttr::Keyword_read_only: \
1541 Result = Context.Id##ROTy; \
1545 #include "clang/Basic/OpenCLImageTypes.def"
1547 case DeclSpec::TST_error:
1548 Result = Context.IntTy;
1549 declarator.setInvalidType(true);
1553 if (S.getLangOpts().OpenCL &&
1554 S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
1555 declarator.setInvalidType(true);
1557 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1558 DS.getTypeSpecType() == DeclSpec::TST_fract;
1560 // Only fixed point types can be saturated
1561 if (DS.isTypeSpecSat() && !IsFixedPointType)
1562 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1563 << DS.getSpecifierName(DS.getTypeSpecType(),
1564 Context.getPrintingPolicy());
1566 // Handle complex types.
1567 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1568 if (S.getLangOpts().Freestanding)
1569 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1570 Result = Context.getComplexType(Result);
1571 } else if (DS.isTypeAltiVecVector()) {
1572 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1573 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1574 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1575 if (DS.isTypeAltiVecPixel())
1576 VecKind = VectorType::AltiVecPixel;
1577 else if (DS.isTypeAltiVecBool())
1578 VecKind = VectorType::AltiVecBool;
1579 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1582 // FIXME: Imaginary.
1583 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1584 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1586 // Before we process any type attributes, synthesize a block literal
1587 // function declarator if necessary.
1588 if (declarator.getContext() == DeclaratorContext::BlockLiteralContext)
1589 maybeSynthesizeBlockSignature(state, Result);
1591 // Apply any type attributes from the decl spec. This may cause the
1592 // list of type attributes to be temporarily saved while the type
1593 // attributes are pushed around.
1594 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1595 if (!DS.isTypeSpecPipe())
1596 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1598 // Apply const/volatile/restrict qualifiers to T.
1599 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1600 // Warn about CV qualifiers on function types.
1602 // If the specification of a function type includes any type qualifiers,
1603 // the behavior is undefined.
1604 // C++11 [dcl.fct]p7:
1605 // The effect of a cv-qualifier-seq in a function declarator is not the
1606 // same as adding cv-qualification on top of the function type. In the
1607 // latter case, the cv-qualifiers are ignored.
1608 if (TypeQuals && Result->isFunctionType()) {
1609 diagnoseAndRemoveTypeQualifiers(
1610 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1611 S.getLangOpts().CPlusPlus
1612 ? diag::warn_typecheck_function_qualifiers_ignored
1613 : diag::warn_typecheck_function_qualifiers_unspecified);
1614 // No diagnostic for 'restrict' or '_Atomic' applied to a
1615 // function type; we'll diagnose those later, in BuildQualifiedType.
1618 // C++11 [dcl.ref]p1:
1619 // Cv-qualified references are ill-formed except when the
1620 // cv-qualifiers are introduced through the use of a typedef-name
1621 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1623 // There don't appear to be any other contexts in which a cv-qualified
1624 // reference type could be formed, so the 'ill-formed' clause here appears
1626 if (TypeQuals && Result->isReferenceType()) {
1627 diagnoseAndRemoveTypeQualifiers(
1628 S, DS, TypeQuals, Result,
1629 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1630 diag::warn_typecheck_reference_qualifiers);
1633 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1634 // than once in the same specifier-list or qualifier-list, either directly
1635 // or via one or more typedefs."
1636 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1637 && TypeQuals & Result.getCVRQualifiers()) {
1638 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1639 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1643 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1644 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1648 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1649 // produce a warning in this case.
1652 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1654 // If adding qualifiers fails, just use the unqualified type.
1655 if (Qualified.isNull())
1656 declarator.setInvalidType(true);
1661 assert(!Result.isNull() && "This function should not return a null type");
1665 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1667 return Entity.getAsString();
1672 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1673 Qualifiers Qs, const DeclSpec *DS) {
1677 // Ignore any attempt to form a cv-qualified reference.
1678 if (T->isReferenceType()) {
1680 Qs.removeVolatile();
1683 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1684 // object or incomplete types shall not be restrict-qualified."
1685 if (Qs.hasRestrict()) {
1686 unsigned DiagID = 0;
1689 if (T->isAnyPointerType() || T->isReferenceType() ||
1690 T->isMemberPointerType()) {
1692 if (T->isObjCObjectPointerType())
1694 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1695 EltTy = PTy->getPointeeType();
1697 EltTy = T->getPointeeType();
1699 // If we have a pointer or reference, the pointee must have an object
1701 if (!EltTy->isIncompleteOrObjectType()) {
1702 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1705 } else if (!T->isDependentType()) {
1706 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1711 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1712 Qs.removeRestrict();
1716 return Context.getQualifiedType(T, Qs);
1719 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1720 unsigned CVRAU, const DeclSpec *DS) {
1724 // Ignore any attempt to form a cv-qualified reference.
1725 if (T->isReferenceType())
1727 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1729 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1731 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1734 // If the same qualifier appears more than once in the same
1735 // specifier-qualifier-list, either directly or via one or more typedefs,
1736 // the behavior is the same as if it appeared only once.
1738 // It's not specified what happens when the _Atomic qualifier is applied to
1739 // a type specified with the _Atomic specifier, but we assume that this
1740 // should be treated as if the _Atomic qualifier appeared multiple times.
1741 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1743 // If other qualifiers appear along with the _Atomic qualifier in a
1744 // specifier-qualifier-list, the resulting type is the so-qualified
1747 // Don't need to worry about array types here, since _Atomic can't be
1748 // applied to such types.
1749 SplitQualType Split = T.getSplitUnqualifiedType();
1750 T = BuildAtomicType(QualType(Split.Ty, 0),
1751 DS ? DS->getAtomicSpecLoc() : Loc);
1754 Split.Quals.addCVRQualifiers(CVR);
1755 return BuildQualifiedType(T, Loc, Split.Quals);
1758 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1759 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1760 return BuildQualifiedType(T, Loc, Q, DS);
1763 /// Build a paren type including \p T.
1764 QualType Sema::BuildParenType(QualType T) {
1765 return Context.getParenType(T);
1768 /// Given that we're building a pointer or reference to the given
1769 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1772 // Bail out if retention is unrequired or already specified.
1773 if (!type->isObjCLifetimeType() ||
1774 type.getObjCLifetime() != Qualifiers::OCL_None)
1777 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1779 // If the object type is const-qualified, we can safely use
1780 // __unsafe_unretained. This is safe (because there are no read
1781 // barriers), and it'll be safe to coerce anything but __weak* to
1782 // the resulting type.
1783 if (type.isConstQualified()) {
1784 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1786 // Otherwise, check whether the static type does not require
1787 // retaining. This currently only triggers for Class (possibly
1788 // protocol-qualifed, and arrays thereof).
1789 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1790 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1792 // If we are in an unevaluated context, like sizeof, skip adding a
1794 } else if (S.isUnevaluatedContext()) {
1797 // If that failed, give an error and recover using __strong. __strong
1798 // is the option most likely to prevent spurious second-order diagnostics,
1799 // like when binding a reference to a field.
1801 // These types can show up in private ivars in system headers, so
1802 // we need this to not be an error in those cases. Instead we
1804 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1805 S.DelayedDiagnostics.add(
1806 sema::DelayedDiagnostic::makeForbiddenType(loc,
1807 diag::err_arc_indirect_no_ownership, type, isReference));
1809 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1811 implicitLifetime = Qualifiers::OCL_Strong;
1813 assert(implicitLifetime && "didn't infer any lifetime!");
1816 qs.addObjCLifetime(implicitLifetime);
1817 return S.Context.getQualifiedType(type, qs);
1820 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1822 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1824 switch (FnTy->getRefQualifier()) {
1845 /// Kinds of declarator that cannot contain a qualified function type.
1847 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1848 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1849 /// at the topmost level of a type.
1851 /// Parens and member pointers are permitted. We don't diagnose array and
1852 /// function declarators, because they don't allow function types at all.
1854 /// The values of this enum are used in diagnostics.
1855 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1856 } // end anonymous namespace
1858 /// Check whether the type T is a qualified function type, and if it is,
1859 /// diagnose that it cannot be contained within the given kind of declarator.
1860 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1861 QualifiedFunctionKind QFK) {
1862 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1863 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1864 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1867 S.Diag(Loc, diag::err_compound_qualified_function_type)
1868 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1869 << getFunctionQualifiersAsString(FPT);
1873 /// Build a pointer type.
1875 /// \param T The type to which we'll be building a pointer.
1877 /// \param Loc The location of the entity whose type involves this
1878 /// pointer type or, if there is no such entity, the location of the
1879 /// type that will have pointer type.
1881 /// \param Entity The name of the entity that involves the pointer
1884 /// \returns A suitable pointer type, if there are no
1885 /// errors. Otherwise, returns a NULL type.
1886 QualType Sema::BuildPointerType(QualType T,
1887 SourceLocation Loc, DeclarationName Entity) {
1888 if (T->isReferenceType()) {
1889 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1890 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1891 << getPrintableNameForEntity(Entity) << T;
1895 if (T->isFunctionType() && getLangOpts().OpenCL) {
1896 Diag(Loc, diag::err_opencl_function_pointer);
1900 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1903 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1905 // In ARC, it is forbidden to build pointers to unqualified pointers.
1906 if (getLangOpts().ObjCAutoRefCount)
1907 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1909 // Build the pointer type.
1910 return Context.getPointerType(T);
1913 /// Build a reference type.
1915 /// \param T The type to which we'll be building a reference.
1917 /// \param Loc The location of the entity whose type involves this
1918 /// reference type or, if there is no such entity, the location of the
1919 /// type that will have reference type.
1921 /// \param Entity The name of the entity that involves the reference
1924 /// \returns A suitable reference type, if there are no
1925 /// errors. Otherwise, returns a NULL type.
1926 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1928 DeclarationName Entity) {
1929 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1930 "Unresolved overloaded function type");
1932 // C++0x [dcl.ref]p6:
1933 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1934 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1935 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1936 // the type "lvalue reference to T", while an attempt to create the type
1937 // "rvalue reference to cv TR" creates the type TR.
1938 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1940 // C++ [dcl.ref]p4: There shall be no references to references.
1942 // According to C++ DR 106, references to references are only
1943 // diagnosed when they are written directly (e.g., "int & &"),
1944 // but not when they happen via a typedef:
1946 // typedef int& intref;
1947 // typedef intref& intref2;
1949 // Parser::ParseDeclaratorInternal diagnoses the case where
1950 // references are written directly; here, we handle the
1951 // collapsing of references-to-references as described in C++0x.
1952 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1955 // A declarator that specifies the type "reference to cv void"
1957 if (T->isVoidType()) {
1958 Diag(Loc, diag::err_reference_to_void);
1962 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1965 // In ARC, it is forbidden to build references to unqualified pointers.
1966 if (getLangOpts().ObjCAutoRefCount)
1967 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1969 // Handle restrict on references.
1971 return Context.getLValueReferenceType(T, SpelledAsLValue);
1972 return Context.getRValueReferenceType(T);
1975 /// Build a Read-only Pipe type.
1977 /// \param T The type to which we'll be building a Pipe.
1979 /// \param Loc We do not use it for now.
1981 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1983 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
1984 return Context.getReadPipeType(T);
1987 /// Build a Write-only Pipe type.
1989 /// \param T The type to which we'll be building a Pipe.
1991 /// \param Loc We do not use it for now.
1993 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1995 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
1996 return Context.getWritePipeType(T);
1999 /// Check whether the specified array size makes the array type a VLA. If so,
2000 /// return true, if not, return the size of the array in SizeVal.
2001 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
2002 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2003 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2004 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2006 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
2008 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
2011 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
2012 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2016 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2017 S.LangOpts.GNUMode ||
2018 S.LangOpts.OpenCL).isInvalid();
2021 /// Build an array type.
2023 /// \param T The type of each element in the array.
2025 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2027 /// \param ArraySize Expression describing the size of the array.
2029 /// \param Brackets The range from the opening '[' to the closing ']'.
2031 /// \param Entity The name of the entity that involves the array
2034 /// \returns A suitable array type, if there are no errors. Otherwise,
2035 /// returns a NULL type.
2036 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2037 Expr *ArraySize, unsigned Quals,
2038 SourceRange Brackets, DeclarationName Entity) {
2040 SourceLocation Loc = Brackets.getBegin();
2041 if (getLangOpts().CPlusPlus) {
2042 // C++ [dcl.array]p1:
2043 // T is called the array element type; this type shall not be a reference
2044 // type, the (possibly cv-qualified) type void, a function type or an
2045 // abstract class type.
2047 // C++ [dcl.array]p3:
2048 // When several "array of" specifications are adjacent, [...] only the
2049 // first of the constant expressions that specify the bounds of the arrays
2052 // Note: function types are handled in the common path with C.
2053 if (T->isReferenceType()) {
2054 Diag(Loc, diag::err_illegal_decl_array_of_references)
2055 << getPrintableNameForEntity(Entity) << T;
2059 if (T->isVoidType() || T->isIncompleteArrayType()) {
2060 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2064 if (RequireNonAbstractType(Brackets.getBegin(), T,
2065 diag::err_array_of_abstract_type))
2068 // Mentioning a member pointer type for an array type causes us to lock in
2069 // an inheritance model, even if it's inside an unused typedef.
2070 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2071 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2072 if (!MPTy->getClass()->isDependentType())
2073 (void)isCompleteType(Loc, T);
2076 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2077 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2078 if (RequireCompleteType(Loc, T,
2079 diag::err_illegal_decl_array_incomplete_type))
2083 if (T->isFunctionType()) {
2084 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2085 << getPrintableNameForEntity(Entity) << T;
2089 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2090 // If the element type is a struct or union that contains a variadic
2091 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2092 if (EltTy->getDecl()->hasFlexibleArrayMember())
2093 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2094 } else if (T->isObjCObjectType()) {
2095 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2099 // Do placeholder conversions on the array size expression.
2100 if (ArraySize && ArraySize->hasPlaceholderType()) {
2101 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2102 if (Result.isInvalid()) return QualType();
2103 ArraySize = Result.get();
2106 // Do lvalue-to-rvalue conversions on the array size expression.
2107 if (ArraySize && !ArraySize->isRValue()) {
2108 ExprResult Result = DefaultLvalueConversion(ArraySize);
2109 if (Result.isInvalid())
2112 ArraySize = Result.get();
2115 // C99 6.7.5.2p1: The size expression shall have integer type.
2116 // C++11 allows contextual conversions to such types.
2117 if (!getLangOpts().CPlusPlus11 &&
2118 ArraySize && !ArraySize->isTypeDependent() &&
2119 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2120 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2121 << ArraySize->getType() << ArraySize->getSourceRange();
2125 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2127 if (ASM == ArrayType::Star)
2128 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2130 T = Context.getIncompleteArrayType(T, ASM, Quals);
2131 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2132 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2133 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2134 !T->isConstantSizeType()) ||
2135 isArraySizeVLA(*this, ArraySize, ConstVal)) {
2136 // Even in C++11, don't allow contextual conversions in the array bound
2138 if (getLangOpts().CPlusPlus11 &&
2139 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2140 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2141 << ArraySize->getType() << ArraySize->getSourceRange();
2145 // C99: an array with an element type that has a non-constant-size is a VLA.
2146 // C99: an array with a non-ICE size is a VLA. We accept any expression
2147 // that we can fold to a non-zero positive value as an extension.
2148 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2150 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2151 // have a value greater than zero.
2152 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2154 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2155 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2157 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2158 << ArraySize->getSourceRange();
2161 if (ConstVal == 0) {
2162 // GCC accepts zero sized static arrays. We allow them when
2163 // we're not in a SFINAE context.
2164 Diag(ArraySize->getLocStart(),
2165 isSFINAEContext()? diag::err_typecheck_zero_array_size
2166 : diag::ext_typecheck_zero_array_size)
2167 << ArraySize->getSourceRange();
2169 if (ASM == ArrayType::Static) {
2170 Diag(ArraySize->getLocStart(),
2171 diag::warn_typecheck_zero_static_array_size)
2172 << ArraySize->getSourceRange();
2173 ASM = ArrayType::Normal;
2175 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2176 !T->isIncompleteType() && !T->isUndeducedType()) {
2177 // Is the array too large?
2178 unsigned ActiveSizeBits
2179 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2180 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2181 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2182 << ConstVal.toString(10)
2183 << ArraySize->getSourceRange();
2188 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2191 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2192 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2193 Diag(Loc, diag::err_opencl_vla);
2197 if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2198 if (getLangOpts().CUDA) {
2199 // CUDA device code doesn't support VLAs.
2200 CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget();
2201 } else if (!getLangOpts().OpenMP ||
2202 shouldDiagnoseTargetSupportFromOpenMP()) {
2203 // Some targets don't support VLAs.
2204 Diag(Loc, diag::err_vla_unsupported);
2209 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2210 if (!getLangOpts().C99) {
2211 if (T->isVariableArrayType()) {
2212 // Prohibit the use of VLAs during template argument deduction.
2213 if (isSFINAEContext()) {
2214 Diag(Loc, diag::err_vla_in_sfinae);
2217 // Just extwarn about VLAs.
2219 Diag(Loc, diag::ext_vla);
2220 } else if (ASM != ArrayType::Normal || Quals != 0)
2222 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2223 : diag::ext_c99_array_usage) << ASM;
2226 if (T->isVariableArrayType()) {
2227 // Warn about VLAs for -Wvla.
2228 Diag(Loc, diag::warn_vla_used);
2231 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2232 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2233 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2234 if (getLangOpts().OpenCL) {
2235 const QualType ArrType = Context.getBaseElementType(T);
2236 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2237 ArrType->isSamplerT() || ArrType->isImageType()) {
2238 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2246 QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2247 SourceLocation AttrLoc) {
2248 // The base type must be integer (not Boolean or enumeration) or float, and
2249 // can't already be a vector.
2250 if (!CurType->isDependentType() &&
2251 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2252 (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) {
2253 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2257 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2258 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2259 VectorType::GenericVector);
2261 llvm::APSInt VecSize(32);
2262 if (!SizeExpr->isIntegerConstantExpr(VecSize, Context)) {
2263 Diag(AttrLoc, diag::err_attribute_argument_type)
2264 << "vector_size" << AANT_ArgumentIntegerConstant
2265 << SizeExpr->getSourceRange();
2269 if (CurType->isDependentType())
2270 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2271 VectorType::GenericVector);
2273 unsigned VectorSize = static_cast<unsigned>(VecSize.getZExtValue() * 8);
2274 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2276 if (VectorSize == 0) {
2277 Diag(AttrLoc, diag::err_attribute_zero_size) << SizeExpr->getSourceRange();
2281 // vecSize is specified in bytes - convert to bits.
2282 if (VectorSize % TypeSize) {
2283 Diag(AttrLoc, diag::err_attribute_invalid_size)
2284 << SizeExpr->getSourceRange();
2288 if (VectorType::isVectorSizeTooLarge(VectorSize / TypeSize)) {
2289 Diag(AttrLoc, diag::err_attribute_size_too_large)
2290 << SizeExpr->getSourceRange();
2294 return Context.getVectorType(CurType, VectorSize / TypeSize,
2295 VectorType::GenericVector);
2298 /// Build an ext-vector type.
2300 /// Run the required checks for the extended vector type.
2301 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2302 SourceLocation AttrLoc) {
2303 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2304 // in conjunction with complex types (pointers, arrays, functions, etc.).
2306 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2307 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2308 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2309 // of bool aren't allowed.
2310 if ((!T->isDependentType() && !T->isIntegerType() &&
2311 !T->isRealFloatingType()) ||
2312 T->isBooleanType()) {
2313 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2317 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2318 llvm::APSInt vecSize(32);
2319 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2320 Diag(AttrLoc, diag::err_attribute_argument_type)
2321 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2322 << ArraySize->getSourceRange();
2326 // Unlike gcc's vector_size attribute, the size is specified as the
2327 // number of elements, not the number of bytes.
2328 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2330 if (vectorSize == 0) {
2331 Diag(AttrLoc, diag::err_attribute_zero_size)
2332 << ArraySize->getSourceRange();
2336 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2337 Diag(AttrLoc, diag::err_attribute_size_too_large)
2338 << ArraySize->getSourceRange();
2342 return Context.getExtVectorType(T, vectorSize);
2345 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2348 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2349 if (T->isArrayType() || T->isFunctionType()) {
2350 Diag(Loc, diag::err_func_returning_array_function)
2351 << T->isFunctionType() << T;
2355 // Functions cannot return half FP.
2356 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2357 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2358 FixItHint::CreateInsertion(Loc, "*");
2362 // Methods cannot return interface types. All ObjC objects are
2363 // passed by reference.
2364 if (T->isObjCObjectType()) {
2365 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2366 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2373 /// Check the extended parameter information. Most of the necessary
2374 /// checking should occur when applying the parameter attribute; the
2375 /// only other checks required are positional restrictions.
2376 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2377 const FunctionProtoType::ExtProtoInfo &EPI,
2378 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2379 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2381 bool hasCheckedSwiftCall = false;
2382 auto checkForSwiftCC = [&](unsigned paramIndex) {
2383 // Only do this once.
2384 if (hasCheckedSwiftCall) return;
2385 hasCheckedSwiftCall = true;
2386 if (EPI.ExtInfo.getCC() == CC_Swift) return;
2387 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2388 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2391 for (size_t paramIndex = 0, numParams = paramTypes.size();
2392 paramIndex != numParams; ++paramIndex) {
2393 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2394 // Nothing interesting to check for orindary-ABI parameters.
2395 case ParameterABI::Ordinary:
2398 // swift_indirect_result parameters must be a prefix of the function
2400 case ParameterABI::SwiftIndirectResult:
2401 checkForSwiftCC(paramIndex);
2402 if (paramIndex != 0 &&
2403 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2404 != ParameterABI::SwiftIndirectResult) {
2405 S.Diag(getParamLoc(paramIndex),
2406 diag::err_swift_indirect_result_not_first);
2410 case ParameterABI::SwiftContext:
2411 checkForSwiftCC(paramIndex);
2414 // swift_error parameters must be preceded by a swift_context parameter.
2415 case ParameterABI::SwiftErrorResult:
2416 checkForSwiftCC(paramIndex);
2417 if (paramIndex == 0 ||
2418 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2419 ParameterABI::SwiftContext) {
2420 S.Diag(getParamLoc(paramIndex),
2421 diag::err_swift_error_result_not_after_swift_context);
2425 llvm_unreachable("bad ABI kind");
2429 QualType Sema::BuildFunctionType(QualType T,
2430 MutableArrayRef<QualType> ParamTypes,
2431 SourceLocation Loc, DeclarationName Entity,
2432 const FunctionProtoType::ExtProtoInfo &EPI) {
2433 bool Invalid = false;
2435 Invalid |= CheckFunctionReturnType(T, Loc);
2437 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2438 // FIXME: Loc is too inprecise here, should use proper locations for args.
2439 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2440 if (ParamType->isVoidType()) {
2441 Diag(Loc, diag::err_param_with_void_type);
2443 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2444 // Disallow half FP arguments.
2445 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2446 FixItHint::CreateInsertion(Loc, "*");
2450 ParamTypes[Idx] = ParamType;
2453 if (EPI.ExtParameterInfos) {
2454 checkExtParameterInfos(*this, ParamTypes, EPI,
2455 [=](unsigned i) { return Loc; });
2458 if (EPI.ExtInfo.getProducesResult()) {
2459 // This is just a warning, so we can't fail to build if we see it.
2460 checkNSReturnsRetainedReturnType(Loc, T);
2466 return Context.getFunctionType(T, ParamTypes, EPI);
2469 /// Build a member pointer type \c T Class::*.
2471 /// \param T the type to which the member pointer refers.
2472 /// \param Class the class type into which the member pointer points.
2473 /// \param Loc the location where this type begins
2474 /// \param Entity the name of the entity that will have this member pointer type
2476 /// \returns a member pointer type, if successful, or a NULL type if there was
2478 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2480 DeclarationName Entity) {
2481 // Verify that we're not building a pointer to pointer to function with
2482 // exception specification.
2483 if (CheckDistantExceptionSpec(T)) {
2484 Diag(Loc, diag::err_distant_exception_spec);
2488 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2489 // with reference type, or "cv void."
2490 if (T->isReferenceType()) {
2491 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2492 << getPrintableNameForEntity(Entity) << T;
2496 if (T->isVoidType()) {
2497 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2498 << getPrintableNameForEntity(Entity);
2502 if (!Class->isDependentType() && !Class->isRecordType()) {
2503 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2507 // Adjust the default free function calling convention to the default method
2508 // calling convention.
2510 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2511 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2512 if (T->isFunctionType())
2513 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2515 return Context.getMemberPointerType(T, Class.getTypePtr());
2518 /// Build a block pointer type.
2520 /// \param T The type to which we'll be building a block pointer.
2522 /// \param Loc The source location, used for diagnostics.
2524 /// \param Entity The name of the entity that involves the block pointer
2527 /// \returns A suitable block pointer type, if there are no
2528 /// errors. Otherwise, returns a NULL type.
2529 QualType Sema::BuildBlockPointerType(QualType T,
2531 DeclarationName Entity) {
2532 if (!T->isFunctionType()) {
2533 Diag(Loc, diag::err_nonfunction_block_type);
2537 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2540 return Context.getBlockPointerType(T);
2543 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2544 QualType QT = Ty.get();
2546 if (TInfo) *TInfo = nullptr;
2550 TypeSourceInfo *DI = nullptr;
2551 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2552 QT = LIT->getType();
2553 DI = LIT->getTypeSourceInfo();
2556 if (TInfo) *TInfo = DI;
2560 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2561 Qualifiers::ObjCLifetime ownership,
2562 unsigned chunkIndex);
2564 /// Given that this is the declaration of a parameter under ARC,
2565 /// attempt to infer attributes and such for pointer-to-whatever
2567 static void inferARCWriteback(TypeProcessingState &state,
2568 QualType &declSpecType) {
2569 Sema &S = state.getSema();
2570 Declarator &declarator = state.getDeclarator();
2572 // TODO: should we care about decl qualifiers?
2574 // Check whether the declarator has the expected form. We walk
2575 // from the inside out in order to make the block logic work.
2576 unsigned outermostPointerIndex = 0;
2577 bool isBlockPointer = false;
2578 unsigned numPointers = 0;
2579 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2580 unsigned chunkIndex = i;
2581 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2582 switch (chunk.Kind) {
2583 case DeclaratorChunk::Paren:
2587 case DeclaratorChunk::Reference:
2588 case DeclaratorChunk::Pointer:
2589 // Count the number of pointers. Treat references
2590 // interchangeably as pointers; if they're mis-ordered, normal
2591 // type building will discover that.
2592 outermostPointerIndex = chunkIndex;
2596 case DeclaratorChunk::BlockPointer:
2597 // If we have a pointer to block pointer, that's an acceptable
2598 // indirect reference; anything else is not an application of
2600 if (numPointers != 1) return;
2602 outermostPointerIndex = chunkIndex;
2603 isBlockPointer = true;
2605 // We don't care about pointer structure in return values here.
2608 case DeclaratorChunk::Array: // suppress if written (id[])?
2609 case DeclaratorChunk::Function:
2610 case DeclaratorChunk::MemberPointer:
2611 case DeclaratorChunk::Pipe:
2617 // If we have *one* pointer, then we want to throw the qualifier on
2618 // the declaration-specifiers, which means that it needs to be a
2619 // retainable object type.
2620 if (numPointers == 1) {
2621 // If it's not a retainable object type, the rule doesn't apply.
2622 if (!declSpecType->isObjCRetainableType()) return;
2624 // If it already has lifetime, don't do anything.
2625 if (declSpecType.getObjCLifetime()) return;
2627 // Otherwise, modify the type in-place.
2630 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2631 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2633 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2634 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2636 // If we have *two* pointers, then we want to throw the qualifier on
2637 // the outermost pointer.
2638 } else if (numPointers == 2) {
2639 // If we don't have a block pointer, we need to check whether the
2640 // declaration-specifiers gave us something that will turn into a
2641 // retainable object pointer after we slap the first pointer on it.
2642 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2645 // Look for an explicit lifetime attribute there.
2646 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2647 if (chunk.Kind != DeclaratorChunk::Pointer &&
2648 chunk.Kind != DeclaratorChunk::BlockPointer)
2650 for (const ParsedAttr &AL : chunk.getAttrs())
2651 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2654 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2655 outermostPointerIndex);
2657 // Any other number of pointers/references does not trigger the rule.
2660 // TODO: mark whether we did this inference?
2663 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2664 SourceLocation FallbackLoc,
2665 SourceLocation ConstQualLoc,
2666 SourceLocation VolatileQualLoc,
2667 SourceLocation RestrictQualLoc,
2668 SourceLocation AtomicQualLoc,
2669 SourceLocation UnalignedQualLoc) {
2677 } const QualKinds[5] = {
2678 { "const", DeclSpec::TQ_const, ConstQualLoc },
2679 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2680 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2681 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2682 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2685 SmallString<32> QualStr;
2686 unsigned NumQuals = 0;
2688 FixItHint FixIts[5];
2690 // Build a string naming the redundant qualifiers.
2691 for (auto &E : QualKinds) {
2692 if (Quals & E.Mask) {
2693 if (!QualStr.empty()) QualStr += ' ';
2696 // If we have a location for the qualifier, offer a fixit.
2697 SourceLocation QualLoc = E.Loc;
2698 if (QualLoc.isValid()) {
2699 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2700 if (Loc.isInvalid() ||
2701 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2709 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2710 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2713 // Diagnose pointless type qualifiers on the return type of a function.
2714 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2716 unsigned FunctionChunkIndex) {
2717 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2718 // FIXME: TypeSourceInfo doesn't preserve location information for
2720 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2721 RetTy.getLocalCVRQualifiers(),
2722 D.getIdentifierLoc());
2726 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2727 End = D.getNumTypeObjects();
2728 OuterChunkIndex != End; ++OuterChunkIndex) {
2729 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2730 switch (OuterChunk.Kind) {
2731 case DeclaratorChunk::Paren:
2734 case DeclaratorChunk::Pointer: {
2735 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2736 S.diagnoseIgnoredQualifiers(
2737 diag::warn_qual_return_type,
2740 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2741 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2742 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2743 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
2744 SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
2748 case DeclaratorChunk::Function:
2749 case DeclaratorChunk::BlockPointer:
2750 case DeclaratorChunk::Reference:
2751 case DeclaratorChunk::Array:
2752 case DeclaratorChunk::MemberPointer:
2753 case DeclaratorChunk::Pipe:
2754 // FIXME: We can't currently provide an accurate source location and a
2755 // fix-it hint for these.
2756 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2757 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2758 RetTy.getCVRQualifiers() | AtomicQual,
2759 D.getIdentifierLoc());
2763 llvm_unreachable("unknown declarator chunk kind");
2766 // If the qualifiers come from a conversion function type, don't diagnose
2767 // them -- they're not necessarily redundant, since such a conversion
2768 // operator can be explicitly called as "x.operator const int()".
2769 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
2772 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2773 // which are present there.
2774 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2775 D.getDeclSpec().getTypeQualifiers(),
2776 D.getIdentifierLoc(),
2777 D.getDeclSpec().getConstSpecLoc(),
2778 D.getDeclSpec().getVolatileSpecLoc(),
2779 D.getDeclSpec().getRestrictSpecLoc(),
2780 D.getDeclSpec().getAtomicSpecLoc(),
2781 D.getDeclSpec().getUnalignedSpecLoc());
2784 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2785 TypeSourceInfo *&ReturnTypeInfo) {
2786 Sema &SemaRef = state.getSema();
2787 Declarator &D = state.getDeclarator();
2789 ReturnTypeInfo = nullptr;
2791 // The TagDecl owned by the DeclSpec.
2792 TagDecl *OwnedTagDecl = nullptr;
2794 switch (D.getName().getKind()) {
2795 case UnqualifiedIdKind::IK_ImplicitSelfParam:
2796 case UnqualifiedIdKind::IK_OperatorFunctionId:
2797 case UnqualifiedIdKind::IK_Identifier:
2798 case UnqualifiedIdKind::IK_LiteralOperatorId:
2799 case UnqualifiedIdKind::IK_TemplateId:
2800 T = ConvertDeclSpecToType(state);
2802 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2803 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2804 // Owned declaration is embedded in declarator.
2805 OwnedTagDecl->setEmbeddedInDeclarator(true);
2809 case UnqualifiedIdKind::IK_ConstructorName:
2810 case UnqualifiedIdKind::IK_ConstructorTemplateId:
2811 case UnqualifiedIdKind::IK_DestructorName:
2812 // Constructors and destructors don't have return types. Use
2814 T = SemaRef.Context.VoidTy;
2815 processTypeAttrs(state, T, TAL_DeclSpec,
2816 D.getMutableDeclSpec().getAttributes());
2819 case UnqualifiedIdKind::IK_DeductionGuideName:
2820 // Deduction guides have a trailing return type and no type in their
2821 // decl-specifier sequence. Use a placeholder return type for now.
2822 T = SemaRef.Context.DependentTy;
2825 case UnqualifiedIdKind::IK_ConversionFunctionId:
2826 // The result type of a conversion function is the type that it
2828 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2833 if (!D.getAttributes().empty())
2834 distributeTypeAttrsFromDeclarator(state, T);
2836 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2837 if (DeducedType *Deduced = T->getContainedDeducedType()) {
2838 AutoType *Auto = dyn_cast<AutoType>(Deduced);
2841 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
2842 // class template argument deduction)?
2843 bool IsCXXAutoType =
2844 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
2846 switch (D.getContext()) {
2847 case DeclaratorContext::LambdaExprContext:
2848 // Declared return type of a lambda-declarator is implicit and is always
2851 case DeclaratorContext::ObjCParameterContext:
2852 case DeclaratorContext::ObjCResultContext:
2853 case DeclaratorContext::PrototypeContext:
2856 case DeclaratorContext::LambdaExprParameterContext:
2857 // In C++14, generic lambdas allow 'auto' in their parameters.
2858 if (!SemaRef.getLangOpts().CPlusPlus14 ||
2859 !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto)
2862 // If auto is mentioned in a lambda parameter context, convert it to a
2863 // template parameter type.
2864 sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda();
2865 assert(LSI && "No LambdaScopeInfo on the stack!");
2866 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
2867 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
2868 const bool IsParameterPack = D.hasEllipsis();
2870 // Create the TemplateTypeParmDecl here to retrieve the corresponding
2871 // template parameter type. Template parameters are temporarily added
2872 // to the TU until the associated TemplateDecl is created.
2873 TemplateTypeParmDecl *CorrespondingTemplateParam =
2874 TemplateTypeParmDecl::Create(
2875 SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(),
2876 /*KeyLoc*/SourceLocation(), /*NameLoc*/D.getLocStart(),
2877 TemplateParameterDepth, AutoParameterPosition,
2878 /*Identifier*/nullptr, false, IsParameterPack);
2879 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
2880 // Replace the 'auto' in the function parameter with this invented
2881 // template type parameter.
2882 // FIXME: Retain some type sugar to indicate that this was written
2884 T = SemaRef.ReplaceAutoType(
2885 T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
2888 case DeclaratorContext::MemberContext: {
2889 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2890 D.isFunctionDeclarator())
2892 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2893 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2894 case TTK_Enum: llvm_unreachable("unhandled tag kind");
2895 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2896 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
2897 case TTK_Class: Error = 5; /* Class member */ break;
2898 case TTK_Interface: Error = 6; /* Interface member */ break;
2900 if (D.getDeclSpec().isFriendSpecified())
2901 Error = 20; // Friend type
2904 case DeclaratorContext::CXXCatchContext:
2905 case DeclaratorContext::ObjCCatchContext:
2906 Error = 7; // Exception declaration
2908 case DeclaratorContext::TemplateParamContext:
2909 if (isa<DeducedTemplateSpecializationType>(Deduced))
2910 Error = 19; // Template parameter
2911 else if (!SemaRef.getLangOpts().CPlusPlus17)
2912 Error = 8; // Template parameter (until C++17)
2914 case DeclaratorContext::BlockLiteralContext:
2915 Error = 9; // Block literal
2917 case DeclaratorContext::TemplateArgContext:
2918 // Within a template argument list, a deduced template specialization
2919 // type will be reinterpreted as a template template argument.
2920 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
2921 !D.getNumTypeObjects() &&
2922 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
2925 case DeclaratorContext::TemplateTypeArgContext:
2926 Error = 10; // Template type argument
2928 case DeclaratorContext::AliasDeclContext:
2929 case DeclaratorContext::AliasTemplateContext:
2930 Error = 12; // Type alias
2932 case DeclaratorContext::TrailingReturnContext:
2933 case DeclaratorContext::TrailingReturnVarContext:
2934 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2935 Error = 13; // Function return type
2937 case DeclaratorContext::ConversionIdContext:
2938 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2939 Error = 14; // conversion-type-id
2941 case DeclaratorContext::FunctionalCastContext:
2942 if (isa<DeducedTemplateSpecializationType>(Deduced))
2945 case DeclaratorContext::TypeNameContext:
2946 Error = 15; // Generic
2948 case DeclaratorContext::FileContext:
2949 case DeclaratorContext::BlockContext:
2950 case DeclaratorContext::ForContext:
2951 case DeclaratorContext::InitStmtContext:
2952 case DeclaratorContext::ConditionContext:
2953 // FIXME: P0091R3 (erroneously) does not permit class template argument
2954 // deduction in conditions, for-init-statements, and other declarations
2955 // that are not simple-declarations.
2957 case DeclaratorContext::CXXNewContext:
2958 // FIXME: P0091R3 does not permit class template argument deduction here,
2959 // but we follow GCC and allow it anyway.
2960 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
2961 Error = 17; // 'new' type
2963 case DeclaratorContext::KNRTypeListContext:
2964 Error = 18; // K&R function parameter
2968 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2971 // In Objective-C it is an error to use 'auto' on a function declarator
2972 // (and everywhere for '__auto_type').
2973 if (D.isFunctionDeclarator() &&
2974 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
2977 bool HaveTrailing = false;
2979 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2980 // contains a trailing return type. That is only legal at the outermost
2981 // level. Check all declarator chunks (outermost first) anyway, to give
2982 // better diagnostics.
2983 // We don't support '__auto_type' with trailing return types.
2984 // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
2985 if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
2986 D.hasTrailingReturnType()) {
2987 HaveTrailing = true;
2991 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2992 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
2993 AutoRange = D.getName().getSourceRange();
2998 switch (Auto->getKeyword()) {
2999 case AutoTypeKeyword::Auto: Kind = 0; break;
3000 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3001 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3004 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3005 "unknown auto type");
3009 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3010 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3012 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3013 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3014 << QualType(Deduced, 0) << AutoRange;
3015 if (auto *TD = TN.getAsTemplateDecl())
3016 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3018 T = SemaRef.Context.IntTy;
3019 D.setInvalidType(true);
3020 } else if (!HaveTrailing &&
3021 D.getContext() != DeclaratorContext::LambdaExprContext) {
3022 // If there was a trailing return type, we already got
3023 // warn_cxx98_compat_trailing_return_type in the parser.
3024 // If this was a lambda, we already warned on that too.
3025 SemaRef.Diag(AutoRange.getBegin(),
3026 diag::warn_cxx98_compat_auto_type_specifier)
3031 if (SemaRef.getLangOpts().CPlusPlus &&
3032 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3033 // Check the contexts where C++ forbids the declaration of a new class
3034 // or enumeration in a type-specifier-seq.
3035 unsigned DiagID = 0;
3036 switch (D.getContext()) {
3037 case DeclaratorContext::TrailingReturnContext:
3038 case DeclaratorContext::TrailingReturnVarContext:
3039 // Class and enumeration definitions are syntactically not allowed in
3040 // trailing return types.
3041 llvm_unreachable("parser should not have allowed this");
3043 case DeclaratorContext::FileContext:
3044 case DeclaratorContext::MemberContext:
3045 case DeclaratorContext::BlockContext:
3046 case DeclaratorContext::ForContext:
3047 case DeclaratorContext::InitStmtContext:
3048 case DeclaratorContext::BlockLiteralContext:
3049 case DeclaratorContext::LambdaExprContext:
3050 // C++11 [dcl.type]p3:
3051 // A type-specifier-seq shall not define a class or enumeration unless
3052 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3053 // the declaration of a template-declaration.
3054 case DeclaratorContext::AliasDeclContext:
3056 case DeclaratorContext::AliasTemplateContext:
3057 DiagID = diag::err_type_defined_in_alias_template;
3059 case DeclaratorContext::TypeNameContext:
3060 case DeclaratorContext::FunctionalCastContext:
3061 case DeclaratorContext::ConversionIdContext:
3062 case DeclaratorContext::TemplateParamContext:
3063 case DeclaratorContext::CXXNewContext:
3064 case DeclaratorContext::CXXCatchContext:
3065 case DeclaratorContext::ObjCCatchContext:
3066 case DeclaratorContext::TemplateArgContext:
3067 case DeclaratorContext::TemplateTypeArgContext:
3068 DiagID = diag::err_type_defined_in_type_specifier;
3070 case DeclaratorContext::PrototypeContext:
3071 case DeclaratorContext::LambdaExprParameterContext:
3072 case DeclaratorContext::ObjCParameterContext:
3073 case DeclaratorContext::ObjCResultContext:
3074 case DeclaratorContext::KNRTypeListContext:
3076 // Types shall not be defined in return or parameter types.
3077 DiagID = diag::err_type_defined_in_param_type;
3079 case DeclaratorContext::ConditionContext:
3081 // The type-specifier-seq shall not contain typedef and shall not declare
3082 // a new class or enumeration.
3083 DiagID = diag::err_type_defined_in_condition;
3088 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3089 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3090 D.setInvalidType(true);
3094 assert(!T.isNull() && "This function should not return a null type");
3098 /// Produce an appropriate diagnostic for an ambiguity between a function
3099 /// declarator and a C++ direct-initializer.
3100 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3101 DeclaratorChunk &DeclType, QualType RT) {
3102 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3103 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3105 // If the return type is void there is no ambiguity.
3106 if (RT->isVoidType())
3109 // An initializer for a non-class type can have at most one argument.
3110 if (!RT->isRecordType() && FTI.NumParams > 1)
3113 // An initializer for a reference must have exactly one argument.
3114 if (RT->isReferenceType() && FTI.NumParams != 1)
3117 // Only warn if this declarator is declaring a function at block scope, and
3118 // doesn't have a storage class (such as 'extern') specified.
3119 if (!D.isFunctionDeclarator() ||
3120 D.getFunctionDefinitionKind() != FDK_Declaration ||
3121 !S.CurContext->isFunctionOrMethod() ||
3122 D.getDeclSpec().getStorageClassSpec()
3123 != DeclSpec::SCS_unspecified)
3126 // Inside a condition, a direct initializer is not permitted. We allow one to
3127 // be parsed in order to give better diagnostics in condition parsing.
3128 if (D.getContext() == DeclaratorContext::ConditionContext)
3131 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3133 S.Diag(DeclType.Loc,
3134 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3135 : diag::warn_empty_parens_are_function_decl)
3138 // If the declaration looks like:
3141 // and name lookup finds a function named 'f', then the ',' was
3142 // probably intended to be a ';'.
3143 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3144 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3145 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3146 if (Comma.getFileID() != Name.getFileID() ||
3147 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3148 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3149 Sema::LookupOrdinaryName);
3150 if (S.LookupName(Result, S.getCurScope()))
3151 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3152 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3153 << D.getIdentifier();
3154 Result.suppressDiagnostics();
3158 if (FTI.NumParams > 0) {
3159 // For a declaration with parameters, eg. "T var(T());", suggest adding
3160 // parens around the first parameter to turn the declaration into a
3161 // variable declaration.
3162 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3163 SourceLocation B = Range.getBegin();
3164 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3165 // FIXME: Maybe we should suggest adding braces instead of parens
3166 // in C++11 for classes that don't have an initializer_list constructor.
3167 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3168 << FixItHint::CreateInsertion(B, "(")
3169 << FixItHint::CreateInsertion(E, ")");
3171 // For a declaration without parameters, eg. "T var();", suggest replacing
3172 // the parens with an initializer to turn the declaration into a variable
3174 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3176 // Empty parens mean value-initialization, and no parens mean
3177 // default initialization. These are equivalent if the default
3178 // constructor is user-provided or if zero-initialization is a
3180 if (RD && RD->hasDefinition() &&
3181 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3182 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3183 << FixItHint::CreateRemoval(ParenRange);
3186 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3187 if (Init.empty() && S.LangOpts.CPlusPlus11)
3190 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3191 << FixItHint::CreateReplacement(ParenRange, Init);
3196 /// Produce an appropriate diagnostic for a declarator with top-level
3198 static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3199 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3200 assert(Paren.Kind == DeclaratorChunk::Paren &&
3201 "do not have redundant top-level parentheses");
3203 // This is a syntactic check; we're not interested in cases that arise
3204 // during template instantiation.
3205 if (S.inTemplateInstantiation())
3208 // Check whether this could be intended to be a construction of a temporary
3209 // object in C++ via a function-style cast.
3210 bool CouldBeTemporaryObject =
3211 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3212 !D.isInvalidType() && D.getIdentifier() &&
3213 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3214 (T->isRecordType() || T->isDependentType()) &&
3215 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3217 bool StartsWithDeclaratorId = true;
3218 for (auto &C : D.type_objects()) {
3220 case DeclaratorChunk::Paren:
3224 case DeclaratorChunk::Pointer:
3225 StartsWithDeclaratorId = false;
3228 case DeclaratorChunk::Array:
3230 CouldBeTemporaryObject = false;
3233 case DeclaratorChunk::Reference:
3234 // FIXME: Suppress the warning here if there is no initializer; we're
3235 // going to give an error anyway.
3236 // We assume that something like 'T (&x) = y;' is highly likely to not
3237 // be intended to be a temporary object.
3238 CouldBeTemporaryObject = false;
3239 StartsWithDeclaratorId = false;
3242 case DeclaratorChunk::Function:
3243 // In a new-type-id, function chunks require parentheses.
3244 if (D.getContext() == DeclaratorContext::CXXNewContext)
3246 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3247 // redundant-parens warning, but we don't know whether the function
3248 // chunk was syntactically valid as an expression here.
3249 CouldBeTemporaryObject = false;
3252 case DeclaratorChunk::BlockPointer:
3253 case DeclaratorChunk::MemberPointer:
3254 case DeclaratorChunk::Pipe:
3255 // These cannot appear in expressions.
3256 CouldBeTemporaryObject = false;
3257 StartsWithDeclaratorId = false;
3262 // FIXME: If there is an initializer, assume that this is not intended to be
3263 // a construction of a temporary object.
3265 // Check whether the name has already been declared; if not, this is not a
3266 // function-style cast.
3267 if (CouldBeTemporaryObject) {
3268 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3269 Sema::LookupOrdinaryName);
3270 if (!S.LookupName(Result, S.getCurScope()))
3271 CouldBeTemporaryObject = false;
3272 Result.suppressDiagnostics();
3275 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3277 if (!CouldBeTemporaryObject) {
3278 // If we have A (::B), the parentheses affect the meaning of the program.
3279 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3280 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3281 // formally unambiguous.
3282 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3283 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3284 NNS = NNS->getPrefix()) {
3285 if (NNS->getKind() == NestedNameSpecifier::Global)
3290 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3291 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3292 << FixItHint::CreateRemoval(Paren.EndLoc);
3296 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3297 << ParenRange << D.getIdentifier();
3298 auto *RD = T->getAsCXXRecordDecl();
3299 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3300 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3301 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3302 << D.getIdentifier();
3303 // FIXME: A cast to void is probably a better suggestion in cases where it's
3304 // valid (when there is no initializer and we're not in a condition).
3305 S.Diag(D.getLocStart(), diag::note_function_style_cast_add_parentheses)
3306 << FixItHint::CreateInsertion(D.getLocStart(), "(")
3307 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getLocEnd()), ")");
3308 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3309 << FixItHint::CreateRemoval(Paren.Loc)
3310 << FixItHint::CreateRemoval(Paren.EndLoc);
3313 /// Helper for figuring out the default CC for a function declarator type. If
3314 /// this is the outermost chunk, then we can determine the CC from the
3315 /// declarator context. If not, then this could be either a member function
3316 /// type or normal function type.
3317 static CallingConv getCCForDeclaratorChunk(
3318 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3319 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3320 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3322 // Check for an explicit CC attribute.
3323 for (const ParsedAttr &AL : AttrList) {
3324 switch (AL.getKind()) {
3325 CALLING_CONV_ATTRS_CASELIST : {
3326 // Ignore attributes that don't validate or can't apply to the
3327 // function type. We'll diagnose the failure to apply them in
3328 // handleFunctionTypeAttr.
3330 if (!S.CheckCallingConvAttr(AL, CC) &&
3331 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3342 bool IsCXXInstanceMethod = false;
3344 if (S.getLangOpts().CPlusPlus) {
3345 // Look inwards through parentheses to see if this chunk will form a
3346 // member pointer type or if we're the declarator. Any type attributes
3347 // between here and there will override the CC we choose here.
3348 unsigned I = ChunkIndex;
3349 bool FoundNonParen = false;
3350 while (I && !FoundNonParen) {
3352 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3353 FoundNonParen = true;
3356 if (FoundNonParen) {
3357 // If we're not the declarator, we're a regular function type unless we're
3358 // in a member pointer.
3359 IsCXXInstanceMethod =
3360 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3361 } else if (D.getContext() == DeclaratorContext::LambdaExprContext) {
3362 // This can only be a call operator for a lambda, which is an instance
3364 IsCXXInstanceMethod = true;
3366 // We're the innermost decl chunk, so must be a function declarator.
3367 assert(D.isFunctionDeclarator());
3369 // If we're inside a record, we're declaring a method, but it could be
3370 // explicitly or implicitly static.
3371 IsCXXInstanceMethod =
3372 D.isFirstDeclarationOfMember() &&
3373 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3374 !D.isStaticMember();
3378 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3379 IsCXXInstanceMethod);
3381 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3382 // and AMDGPU targets, hence it cannot be treated as a calling
3383 // convention attribute. This is the simplest place to infer
3384 // calling convention for OpenCL kernels.
3385 if (S.getLangOpts().OpenCL) {
3386 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3387 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
3388 CC = CC_OpenCLKernel;
3398 /// A simple notion of pointer kinds, which matches up with the various
3399 /// pointer declarators.
3400 enum class SimplePointerKind {
3406 } // end anonymous namespace
3408 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3409 switch (nullability) {
3410 case NullabilityKind::NonNull:
3411 if (!Ident__Nonnull)
3412 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3413 return Ident__Nonnull;
3415 case NullabilityKind::Nullable:
3416 if (!Ident__Nullable)
3417 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3418 return Ident__Nullable;
3420 case NullabilityKind::Unspecified:
3421 if (!Ident__Null_unspecified)
3422 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3423 return Ident__Null_unspecified;
3425 llvm_unreachable("Unknown nullability kind.");
3428 /// Retrieve the identifier "NSError".
3429 IdentifierInfo *Sema::getNSErrorIdent() {
3431 Ident_NSError = PP.getIdentifierInfo("NSError");
3433 return Ident_NSError;
3436 /// Check whether there is a nullability attribute of any kind in the given
3438 static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3439 for (const ParsedAttr &AL : attrs) {
3440 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3441 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3442 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3450 /// Describes the kind of a pointer a declarator describes.
3451 enum class PointerDeclaratorKind {
3454 // Single-level pointer.
3456 // Multi-level pointer (of any pointer kind).
3459 MaybePointerToCFRef,
3463 NSErrorPointerPointer,
3466 /// Describes a declarator chunk wrapping a pointer that marks inference as
3468 // These values must be kept in sync with diagnostics.
3469 enum class PointerWrappingDeclaratorKind {
3470 /// Pointer is top-level.
3472 /// Pointer is an array element.
3474 /// Pointer is the referent type of a C++ reference.
3477 } // end anonymous namespace
3479 /// Classify the given declarator, whose type-specified is \c type, based on
3480 /// what kind of pointer it refers to.
3482 /// This is used to determine the default nullability.
3483 static PointerDeclaratorKind
3484 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
3485 PointerWrappingDeclaratorKind &wrappingKind) {
3486 unsigned numNormalPointers = 0;
3488 // For any dependent type, we consider it a non-pointer.
3489 if (type->isDependentType())
3490 return PointerDeclaratorKind::NonPointer;
3492 // Look through the declarator chunks to identify pointers.
3493 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3494 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3495 switch (chunk.Kind) {
3496 case DeclaratorChunk::Array:
3497 if (numNormalPointers == 0)
3498 wrappingKind = PointerWrappingDeclaratorKind::Array;
3501 case DeclaratorChunk::Function:
3502 case DeclaratorChunk::Pipe:
3505 case DeclaratorChunk::BlockPointer:
3506 case DeclaratorChunk::MemberPointer:
3507 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3508 : PointerDeclaratorKind::SingleLevelPointer;
3510 case DeclaratorChunk::Paren:
3513 case DeclaratorChunk::Reference:
3514 if (numNormalPointers == 0)
3515 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3518 case DeclaratorChunk::Pointer:
3519 ++numNormalPointers;
3520 if (numNormalPointers > 2)
3521 return PointerDeclaratorKind::MultiLevelPointer;
3526 // Then, dig into the type specifier itself.
3527 unsigned numTypeSpecifierPointers = 0;
3529 // Decompose normal pointers.
3530 if (auto ptrType = type->getAs<PointerType>()) {
3531 ++numNormalPointers;
3533 if (numNormalPointers > 2)
3534 return PointerDeclaratorKind::MultiLevelPointer;
3536 type = ptrType->getPointeeType();
3537 ++numTypeSpecifierPointers;
3541 // Decompose block pointers.
3542 if (type->getAs<BlockPointerType>()) {
3543 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3544 : PointerDeclaratorKind::SingleLevelPointer;
3547 // Decompose member pointers.
3548 if (type->getAs<MemberPointerType>()) {
3549 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3550 : PointerDeclaratorKind::SingleLevelPointer;
3553 // Look at Objective-C object pointers.
3554 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3555 ++numNormalPointers;
3556 ++numTypeSpecifierPointers;
3558 // If this is NSError**, report that.
3559 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3560 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3561 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3562 return PointerDeclaratorKind::NSErrorPointerPointer;
3569 // Look at Objective-C class types.
3570 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3571 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3572 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3573 return PointerDeclaratorKind::NSErrorPointerPointer;
3579 // If at this point we haven't seen a pointer, we won't see one.
3580 if (numNormalPointers == 0)
3581 return PointerDeclaratorKind::NonPointer;
3583 if (auto recordType = type->getAs<RecordType>()) {
3584 RecordDecl *recordDecl = recordType->getDecl();
3586 bool isCFError = false;
3588 // If we already know about CFError, test it directly.
3589 isCFError = (S.CFError == recordDecl);
3591 // Check whether this is CFError, which we identify based on its bridge
3592 // to NSError. CFErrorRef used to be declared with "objc_bridge" but is
3593 // now declared with "objc_bridge_mutable", so look for either one of
3594 // the two attributes.
3595 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3596 IdentifierInfo *bridgedType = nullptr;
3597 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>())
3598 bridgedType = bridgeAttr->getBridgedType();
3599 else if (auto bridgeAttr =
3600 recordDecl->getAttr<ObjCBridgeMutableAttr>())
3601 bridgedType = bridgeAttr->getBridgedType();
3603 if (bridgedType == S.getNSErrorIdent()) {
3604 S.CFError = recordDecl;
3610 // If this is CFErrorRef*, report it as such.
3611 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3612 return PointerDeclaratorKind::CFErrorRefPointer;
3620 switch (numNormalPointers) {
3622 return PointerDeclaratorKind::NonPointer;
3625 return PointerDeclaratorKind::SingleLevelPointer;
3628 return PointerDeclaratorKind::MaybePointerToCFRef;
3631 return PointerDeclaratorKind::MultiLevelPointer;
3635 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
3636 SourceLocation loc) {
3637 // If we're anywhere in a function, method, or closure context, don't perform
3638 // completeness checks.
3639 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3640 if (ctx->isFunctionOrMethod())
3643 if (ctx->isFileContext())
3647 // We only care about the expansion location.
3648 loc = S.SourceMgr.getExpansionLoc(loc);
3649 FileID file = S.SourceMgr.getFileID(loc);
3650 if (file.isInvalid())
3653 // Retrieve file information.
3654 bool invalid = false;
3655 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3656 if (invalid || !sloc.isFile())
3659 // We don't want to perform completeness checks on the main file or in
3661 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3662 if (fileInfo.getIncludeLoc().isInvalid())
3664 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3665 S.Diags.getSuppressSystemWarnings()) {
3672 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
3673 /// taking into account whitespace before and after.
3674 static void fixItNullability(Sema &S, DiagnosticBuilder &Diag,
3675 SourceLocation PointerLoc,
3676 NullabilityKind Nullability) {
3677 assert(PointerLoc.isValid());
3678 if (PointerLoc.isMacroID())
3681 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
3682 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
3685 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
3689 SmallString<32> InsertionTextBuf{" "};
3690 InsertionTextBuf += getNullabilitySpelling(Nullability);
3691 InsertionTextBuf += " ";
3692 StringRef InsertionText = InsertionTextBuf.str();
3694 if (isWhitespace(*NextChar)) {
3695 InsertionText = InsertionText.drop_back();
3696 } else if (NextChar[-1] == '[') {
3697 if (NextChar[0] == ']')
3698 InsertionText = InsertionText.drop_back().drop_front();
3700 InsertionText = InsertionText.drop_front();
3701 } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
3702 !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
3703 InsertionText = InsertionText.drop_back().drop_front();
3706 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
3709 static void emitNullabilityConsistencyWarning(Sema &S,
3710 SimplePointerKind PointerKind,
3711 SourceLocation PointerLoc,
3712 SourceLocation PointerEndLoc) {
3713 assert(PointerLoc.isValid());
3715 if (PointerKind == SimplePointerKind::Array) {
3716 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
3718 S.Diag(PointerLoc, diag::warn_nullability_missing)
3719 << static_cast<unsigned>(PointerKind);
3722 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
3723 if (FixItLoc.isMacroID())
3726 auto addFixIt = [&](NullabilityKind Nullability) {
3727 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
3728 Diag << static_cast<unsigned>(Nullability);
3729 Diag << static_cast<unsigned>(PointerKind);
3730 fixItNullability(S, Diag, FixItLoc, Nullability);
3732 addFixIt(NullabilityKind::Nullable);
3733 addFixIt(NullabilityKind::NonNull);
3736 /// Complains about missing nullability if the file containing \p pointerLoc
3737 /// has other uses of nullability (either the keywords or the \c assume_nonnull
3740 /// If the file has \e not seen other uses of nullability, this particular
3741 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
3743 checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
3744 SourceLocation pointerLoc,
3745 SourceLocation pointerEndLoc = SourceLocation()) {
3746 // Determine which file we're performing consistency checking for.
3747 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3748 if (file.isInvalid())
3751 // If we haven't seen any type nullability in this file, we won't warn now
3753 FileNullability &fileNullability = S.NullabilityMap[file];
3754 if (!fileNullability.SawTypeNullability) {
3755 // If this is the first pointer declarator in the file, and the appropriate
3756 // warning is on, record it in case we need to diagnose it retroactively.
3757 diag::kind diagKind;
3758 if (pointerKind == SimplePointerKind::Array)
3759 diagKind = diag::warn_nullability_missing_array;
3761 diagKind = diag::warn_nullability_missing;
3763 if (fileNullability.PointerLoc.isInvalid() &&
3764 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
3765 fileNullability.PointerLoc = pointerLoc;
3766 fileNullability.PointerEndLoc = pointerEndLoc;
3767 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3773 // Complain about missing nullability.
3774 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
3777 /// Marks that a nullability feature has been used in the file containing
3780 /// If this file already had pointer types in it that were missing nullability,
3781 /// the first such instance is retroactively diagnosed.
3783 /// \sa checkNullabilityConsistency
3784 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
3785 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
3786 if (file.isInvalid())
3789 FileNullability &fileNullability = S.NullabilityMap[file];
3790 if (fileNullability.SawTypeNullability)
3792 fileNullability.SawTypeNullability = true;
3794 // If we haven't seen any type nullability before, now we have. Retroactively
3795 // diagnose the first unannotated pointer, if there was one.
3796 if (fileNullability.PointerLoc.isInvalid())
3799 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
3800 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
3801 fileNullability.PointerEndLoc);
3804 /// Returns true if any of the declarator chunks before \p endIndex include a
3805 /// level of indirection: array, pointer, reference, or pointer-to-member.
3807 /// Because declarator chunks are stored in outer-to-inner order, testing
3808 /// every chunk before \p endIndex is testing all chunks that embed the current
3809 /// chunk as part of their type.
3811 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
3812 /// end index, in which case all chunks are tested.
3813 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
3814 unsigned i = endIndex;
3816 // Walk outwards along the declarator chunks.
3818 const DeclaratorChunk &DC = D.getTypeObject(i);
3820 case DeclaratorChunk::Paren:
3822 case DeclaratorChunk::Array:
3823 case DeclaratorChunk::Pointer:
3824 case DeclaratorChunk::Reference:
3825 case DeclaratorChunk::MemberPointer:
3827 case DeclaratorChunk::Function:
3828 case DeclaratorChunk::BlockPointer:
3829 case DeclaratorChunk::Pipe:
3830 // These are invalid anyway, so just ignore.
3837 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3838 QualType declSpecType,
3839 TypeSourceInfo *TInfo) {
3840 // The TypeSourceInfo that this function returns will not be a null type.
3841 // If there is an error, this function will fill in a dummy type as fallback.
3842 QualType T = declSpecType;
3843 Declarator &D = state.getDeclarator();
3844 Sema &S = state.getSema();
3845 ASTContext &Context = S.Context;
3846 const LangOptions &LangOpts = S.getLangOpts();
3848 // The name we're declaring, if any.
3849 DeclarationName Name;
3850 if (D.getIdentifier())
3851 Name = D.getIdentifier();
3853 // Does this declaration declare a typedef-name?
3854 bool IsTypedefName =
3855 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
3856 D.getContext() == DeclaratorContext::AliasDeclContext ||
3857 D.getContext() == DeclaratorContext::AliasTemplateContext;
3859 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3860 bool IsQualifiedFunction = T->isFunctionProtoType() &&
3861 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3862 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3864 // If T is 'decltype(auto)', the only declarators we can have are parens
3865 // and at most one function declarator if this is a function declaration.
3866 // If T is a deduced class template specialization type, we can have no
3867 // declarator chunks at all.
3868 if (auto *DT = T->getAs<DeducedType>()) {
3869 const AutoType *AT = T->getAs<AutoType>();
3870 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
3871 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
3872 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3873 unsigned Index = E - I - 1;
3874 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3875 unsigned DiagId = IsClassTemplateDeduction
3876 ? diag::err_deduced_class_template_compound_type
3877 : diag::err_decltype_auto_compound_type;
3878 unsigned DiagKind = 0;
3879 switch (DeclChunk.Kind) {
3880 case DeclaratorChunk::Paren:
3881 // FIXME: Rejecting this is a little silly.
3882 if (IsClassTemplateDeduction) {
3887 case DeclaratorChunk::Function: {
3888 if (IsClassTemplateDeduction) {
3893 if (D.isFunctionDeclarationContext() &&
3894 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3896 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3899 case DeclaratorChunk::Pointer:
3900 case DeclaratorChunk::BlockPointer:
3901 case DeclaratorChunk::MemberPointer:
3904 case DeclaratorChunk::Reference:
3907 case DeclaratorChunk::Array:
3910 case DeclaratorChunk::Pipe:
3914 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3915 D.setInvalidType(true);
3921 // Determine whether we should infer _Nonnull on pointer types.
3922 Optional<NullabilityKind> inferNullability;
3923 bool inferNullabilityCS = false;
3924 bool inferNullabilityInnerOnly = false;
3925 bool inferNullabilityInnerOnlyComplete = false;
3927 // Are we in an assume-nonnull region?
3928 bool inAssumeNonNullRegion = false;
3929 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
3930 if (assumeNonNullLoc.isValid()) {
3931 inAssumeNonNullRegion = true;
3932 recordNullabilitySeen(S, assumeNonNullLoc);
3935 // Whether to complain about missing nullability specifiers or not.
3939 /// Complain on the inner pointers (but not the outermost
3942 /// Complain about any pointers that don't have nullability
3943 /// specified or inferred.
3945 } complainAboutMissingNullability = CAMN_No;
3946 unsigned NumPointersRemaining = 0;
3947 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
3949 if (IsTypedefName) {
3950 // For typedefs, we do not infer any nullability (the default),
3951 // and we only complain about missing nullability specifiers on
3953 complainAboutMissingNullability = CAMN_InnerPointers;
3955 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
3956 !T->getNullability(S.Context)) {
3957 // Note that we allow but don't require nullability on dependent types.
3958 ++NumPointersRemaining;
3961 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3962 DeclaratorChunk &chunk = D.getTypeObject(i);
3963 switch (chunk.Kind) {
3964 case DeclaratorChunk::Array:
3965 case DeclaratorChunk::Function:
3966 case DeclaratorChunk::Pipe:
3969 case DeclaratorChunk::BlockPointer:
3970 case DeclaratorChunk::MemberPointer:
3971 ++NumPointersRemaining;
3974 case DeclaratorChunk::Paren:
3975 case DeclaratorChunk::Reference:
3978 case DeclaratorChunk::Pointer:
3979 ++NumPointersRemaining;
3984 bool isFunctionOrMethod = false;
3985 switch (auto context = state.getDeclarator().getContext()) {
3986 case DeclaratorContext::ObjCParameterContext:
3987 case DeclaratorContext::ObjCResultContext:
3988 case DeclaratorContext::PrototypeContext:
3989 case DeclaratorContext::TrailingReturnContext:
3990 case DeclaratorContext::TrailingReturnVarContext:
3991 isFunctionOrMethod = true;
3994 case DeclaratorContext::MemberContext:
3995 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3996 complainAboutMissingNullability = CAMN_No;
4000 // Weak properties are inferred to be nullable.
4001 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
4002 inferNullability = NullabilityKind::Nullable;
4008 case DeclaratorContext::FileContext:
4009 case DeclaratorContext::KNRTypeListContext: {
4010 complainAboutMissingNullability = CAMN_Yes;
4012 // Nullability inference depends on the type and declarator.
4013 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4014 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4015 case PointerDeclaratorKind::NonPointer:
4016 case PointerDeclaratorKind::MultiLevelPointer:
4017 // Cannot infer nullability.
4020 case PointerDeclaratorKind::SingleLevelPointer:
4021 // Infer _Nonnull if we are in an assumes-nonnull region.
4022 if (inAssumeNonNullRegion) {
4023 complainAboutInferringWithinChunk = wrappingKind;
4024 inferNullability = NullabilityKind::NonNull;
4025 inferNullabilityCS =
4026 (context == DeclaratorContext::ObjCParameterContext ||
4027 context == DeclaratorContext::ObjCResultContext);
4031 case PointerDeclaratorKind::CFErrorRefPointer:
4032 case PointerDeclaratorKind::NSErrorPointerPointer:
4033 // Within a function or method signature, infer _Nullable at both
4035 if (isFunctionOrMethod && inAssumeNonNullRegion)
4036 inferNullability = NullabilityKind::Nullable;
4039 case PointerDeclaratorKind::MaybePointerToCFRef:
4040 if (isFunctionOrMethod) {
4041 // On pointer-to-pointer parameters marked cf_returns_retained or
4042 // cf_returns_not_retained, if the outer pointer is explicit then
4043 // infer the inner pointer as _Nullable.
4044 auto hasCFReturnsAttr =
4045 [](const ParsedAttributesView &AttrList) -> bool {
4046 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4047 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4049 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4050 if (hasCFReturnsAttr(D.getAttributes()) ||
4051 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4052 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4053 inferNullability = NullabilityKind::Nullable;
4054 inferNullabilityInnerOnly = true;
4063 case DeclaratorContext::ConversionIdContext:
4064 complainAboutMissingNullability = CAMN_Yes;
4067 case DeclaratorContext::AliasDeclContext:
4068 case DeclaratorContext::AliasTemplateContext:
4069 case DeclaratorContext::BlockContext:
4070 case DeclaratorContext::BlockLiteralContext:
4071 case DeclaratorContext::ConditionContext:
4072 case DeclaratorContext::CXXCatchContext:
4073 case DeclaratorContext::CXXNewContext:
4074 case DeclaratorContext::ForContext:
4075 case DeclaratorContext::InitStmtContext:
4076 case DeclaratorContext::LambdaExprContext:
4077 case DeclaratorContext::LambdaExprParameterContext:
4078 case DeclaratorContext::ObjCCatchContext:
4079 case DeclaratorContext::TemplateParamContext:
4080 case DeclaratorContext::TemplateArgContext:
4081 case DeclaratorContext::TemplateTypeArgContext:
4082 case DeclaratorContext::TypeNameContext:
4083 case DeclaratorContext::FunctionalCastContext:
4084 // Don't infer in these contexts.
4089 // Local function that returns true if its argument looks like a va_list.
4090 auto isVaList = [&S](QualType T) -> bool {
4091 auto *typedefTy = T->getAs<TypedefType>();
4094 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4096 if (typedefTy->getDecl() == vaListTypedef)
4098 if (auto *name = typedefTy->getDecl()->getIdentifier())
4099 if (name->isStr("va_list"))
4101 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4102 } while (typedefTy);
4106 // Local function that checks the nullability for a given pointer declarator.
4107 // Returns true if _Nonnull was inferred.
4108 auto inferPointerNullability =
4109 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4110 SourceLocation pointerEndLoc,
4111 ParsedAttributesView &attrs) -> ParsedAttr * {
4112 // We've seen a pointer.
4113 if (NumPointersRemaining > 0)
4114 --NumPointersRemaining;
4116 // If a nullability attribute is present, there's nothing to do.
4117 if (hasNullabilityAttr(attrs))
4120 // If we're supposed to infer nullability, do so now.
4121 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4122 ParsedAttr::Syntax syntax = inferNullabilityCS
4123 ? ParsedAttr::AS_ContextSensitiveKeyword
4124 : ParsedAttr::AS_Keyword;
4125 ParsedAttr *nullabilityAttr =
4126 state.getDeclarator().getAttributePool().create(
4127 S.getNullabilityKeyword(*inferNullability),
4128 SourceRange(pointerLoc), nullptr, SourceLocation(), nullptr, 0,
4131 attrs.addAtStart(nullabilityAttr);
4133 if (inferNullabilityCS) {
4134 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4135 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4138 if (pointerLoc.isValid() &&
4139 complainAboutInferringWithinChunk !=
4140 PointerWrappingDeclaratorKind::None) {
4142 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4143 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4144 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4147 if (inferNullabilityInnerOnly)
4148 inferNullabilityInnerOnlyComplete = true;
4149 return nullabilityAttr;
4152 // If we're supposed to complain about missing nullability, do so
4153 // now if it's truly missing.
4154 switch (complainAboutMissingNullability) {
4158 case CAMN_InnerPointers:
4159 if (NumPointersRemaining == 0)
4164 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4169 // If the type itself could have nullability but does not, infer pointer
4170 // nullability and perform consistency checking.
4171 if (S.CodeSynthesisContexts.empty()) {
4172 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4173 !T->getNullability(S.Context)) {
4175 // Record that we've seen a pointer, but do nothing else.
4176 if (NumPointersRemaining > 0)
4177 --NumPointersRemaining;
4179 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4180 if (T->isBlockPointerType())
4181 pointerKind = SimplePointerKind::BlockPointer;
4182 else if (T->isMemberPointerType())
4183 pointerKind = SimplePointerKind::MemberPointer;
4185 if (auto *attr = inferPointerNullability(
4186 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4187 D.getDeclSpec().getLocEnd(),
4188 D.getMutableDeclSpec().getAttributes())) {
4189 T = Context.getAttributedType(
4190 AttributedType::getNullabilityAttrKind(*inferNullability),T,T);
4191 attr->setUsedAsTypeAttr();
4196 if (complainAboutMissingNullability == CAMN_Yes &&
4197 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4198 D.isPrototypeContext() &&
4199 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4200 checkNullabilityConsistency(S, SimplePointerKind::Array,
4201 D.getDeclSpec().getTypeSpecTypeLoc());
4205 // Walk the DeclTypeInfo, building the recursive type as we go.
4206 // DeclTypeInfos are ordered from the identifier out, which is
4207 // opposite of what we want :).
4208 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4209 unsigned chunkIndex = e - i - 1;
4210 state.setCurrentChunkIndex(chunkIndex);
4211 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4212 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4213 switch (DeclType.Kind) {
4214 case DeclaratorChunk::Paren:
4216 warnAboutRedundantParens(S, D, T);
4217 T = S.BuildParenType(T);
4219 case DeclaratorChunk::BlockPointer:
4220 // If blocks are disabled, emit an error.
4221 if (!LangOpts.Blocks)
4222 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4224 // Handle pointer nullability.
4225 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4226 DeclType.EndLoc, DeclType.getAttrs());
4228 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4229 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4230 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4231 // qualified with const.
4232 if (LangOpts.OpenCL)
4233 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4234 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4237 case DeclaratorChunk::Pointer:
4238 // Verify that we're not building a pointer to pointer to function with
4239 // exception specification.
4240 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4241 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4242 D.setInvalidType(true);
4243 // Build the type anyway.
4246 // Handle pointer nullability
4247 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4248 DeclType.EndLoc, DeclType.getAttrs());
4250 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
4251 T = Context.getObjCObjectPointerType(T);
4252 if (DeclType.Ptr.TypeQuals)
4253 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4257 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4258 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4259 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4260 if (LangOpts.OpenCL) {
4261 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4262 T->isBlockPointerType()) {
4263 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4264 D.setInvalidType(true);
4268 T = S.BuildPointerType(T, DeclType.Loc, Name);
4269 if (DeclType.Ptr.TypeQuals)
4270 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4272 case DeclaratorChunk::Reference: {
4273 // Verify that we're not building a reference to pointer to function with
4274 // exception specification.
4275 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4276 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4277 D.setInvalidType(true);
4278 // Build the type anyway.
4280 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4282 if (DeclType.Ref.HasRestrict)
4283 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4286 case DeclaratorChunk::Array: {
4287 // Verify that we're not building an array of pointers to function with
4288 // exception specification.
4289 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4290 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4291 D.setInvalidType(true);
4292 // Build the type anyway.
4294 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4295 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4296 ArrayType::ArraySizeModifier ASM;
4298 ASM = ArrayType::Star;
4299 else if (ATI.hasStatic)
4300 ASM = ArrayType::Static;
4302 ASM = ArrayType::Normal;
4303 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4304 // FIXME: This check isn't quite right: it allows star in prototypes
4305 // for function definitions, and disallows some edge cases detailed
4306 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4307 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4308 ASM = ArrayType::Normal;
4309 D.setInvalidType(true);
4312 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4313 // shall appear only in a declaration of a function parameter with an
4315 if (ASM == ArrayType::Static || ATI.TypeQuals) {
4316 if (!(D.isPrototypeContext() ||
4317 D.getContext() == DeclaratorContext::KNRTypeListContext)) {
4318 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4319 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4320 // Remove the 'static' and the type qualifiers.
4321 if (ASM == ArrayType::Static)
4322 ASM = ArrayType::Normal;
4324 D.setInvalidType(true);
4327 // C99 6.7.5.2p1: ... and then only in the outermost array type
4329 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4330 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4331 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4332 if (ASM == ArrayType::Static)
4333 ASM = ArrayType::Normal;
4335 D.setInvalidType(true);
4338 const AutoType *AT = T->getContainedAutoType();
4339 // Allow arrays of auto if we are a generic lambda parameter.
4340 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4342 D.getContext() != DeclaratorContext::LambdaExprParameterContext) {
4343 // We've already diagnosed this for decltype(auto).
4344 if (!AT->isDecltypeAuto())
4345 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4346 << getPrintableNameForEntity(Name) << T;
4351 // Array parameters can be marked nullable as well, although it's not
4352 // necessary if they're marked 'static'.
4353 if (complainAboutMissingNullability == CAMN_Yes &&
4354 !hasNullabilityAttr(DeclType.getAttrs()) &&
4355 ASM != ArrayType::Static &&
4356 D.isPrototypeContext() &&
4357 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4358 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4361 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4362 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4365 case DeclaratorChunk::Function: {
4366 // If the function declarator has a prototype (i.e. it is not () and
4367 // does not have a K&R-style identifier list), then the arguments are part
4368 // of the type, otherwise the argument list is ().
4369 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4370 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
4372 // Check for auto functions and trailing return type and adjust the
4373 // return type accordingly.
4374 if (!D.isInvalidType()) {
4375 // trailing-return-type is only required if we're declaring a function,
4376 // and not, for instance, a pointer to a function.
4377 if (D.getDeclSpec().hasAutoTypeSpec() &&
4378 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
4379 !S.getLangOpts().CPlusPlus14) {
4380 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4381 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4382 ? diag::err_auto_missing_trailing_return
4383 : diag::err_deduced_return_type);
4385 D.setInvalidType(true);
4386 } else if (FTI.hasTrailingReturnType()) {
4387 // T must be exactly 'auto' at this point. See CWG issue 681.
4388 if (isa<ParenType>(T)) {
4389 S.Diag(D.getLocStart(),
4390 diag::err_trailing_return_in_parens)
4391 << T << D.getSourceRange();
4392 D.setInvalidType(true);
4393 } else if (D.getName().getKind() ==
4394 UnqualifiedIdKind::IK_DeductionGuideName) {
4395 if (T != Context.DependentTy) {
4396 S.Diag(D.getDeclSpec().getLocStart(),
4397 diag::err_deduction_guide_with_complex_decl)
4398 << D.getSourceRange();
4399 D.setInvalidType(true);
4401 } else if (D.getContext() != DeclaratorContext::LambdaExprContext &&
4402 (T.hasQualifiers() || !isa<AutoType>(T) ||
4403 cast<AutoType>(T)->getKeyword() !=
4404 AutoTypeKeyword::Auto)) {
4405 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4406 diag::err_trailing_return_without_auto)
4407 << T << D.getDeclSpec().getSourceRange();
4408 D.setInvalidType(true);
4410 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4412 // An error occurred parsing the trailing return type.
4414 D.setInvalidType(true);
4419 // C99 6.7.5.3p1: The return type may not be a function or array type.
4420 // For conversion functions, we'll diagnose this particular error later.
4421 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4422 (D.getName().getKind() !=
4423 UnqualifiedIdKind::IK_ConversionFunctionId)) {
4424 unsigned diagID = diag::err_func_returning_array_function;
4425 // Last processing chunk in block context means this function chunk
4426 // represents the block.
4427 if (chunkIndex == 0 &&
4428 D.getContext() == DeclaratorContext::BlockLiteralContext)
4429 diagID = diag::err_block_returning_array_function;
4430 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4432 D.setInvalidType(true);
4435 // Do not allow returning half FP value.
4436 // FIXME: This really should be in BuildFunctionType.
4437 if (T->isHalfType()) {
4438 if (S.getLangOpts().OpenCL) {
4439 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4440 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4441 << T << 0 /*pointer hint*/;
4442 D.setInvalidType(true);
4444 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4445 S.Diag(D.getIdentifierLoc(),
4446 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4447 D.setInvalidType(true);
4451 if (LangOpts.OpenCL) {
4452 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4454 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4456 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4457 << T << 1 /*hint off*/;
4458 D.setInvalidType(true);
4460 // OpenCL doesn't support variadic functions and blocks
4461 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4462 // We also allow here any toolchain reserved identifiers.
4463 if (FTI.isVariadic &&
4464 !(D.getIdentifier() &&
4465 ((D.getIdentifier()->getName() == "printf" &&
4466 LangOpts.OpenCLVersion >= 120) ||
4467 D.getIdentifier()->getName().startswith("__")))) {
4468 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4469 D.setInvalidType(true);
4473 // Methods cannot return interface types. All ObjC objects are
4474 // passed by reference.
4475 if (T->isObjCObjectType()) {
4476 SourceLocation DiagLoc, FixitLoc;
4478 DiagLoc = TInfo->getTypeLoc().getLocStart();
4479 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
4481 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4482 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
4484 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4486 << FixItHint::CreateInsertion(FixitLoc, "*");
4488 T = Context.getObjCObjectPointerType(T);
4491 TLB.pushFullCopy(TInfo->getTypeLoc());
4492 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4493 TLoc.setStarLoc(FixitLoc);
4494 TInfo = TLB.getTypeSourceInfo(Context, T);
4497 D.setInvalidType(true);
4500 // cv-qualifiers on return types are pointless except when the type is a
4501 // class type in C++.
4502 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4503 !(S.getLangOpts().CPlusPlus &&
4504 (T->isDependentType() || T->isRecordType()))) {
4505 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4506 D.getFunctionDefinitionKind() == FDK_Definition) {
4507 // [6.9.1/3] qualified void return is invalid on a C
4508 // function definition. Apparently ok on declarations and
4509 // in C++ though (!)
4510 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4512 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4515 // Objective-C ARC ownership qualifiers are ignored on the function
4516 // return type (by type canonicalization). Complain if this attribute
4517 // was written here.
4518 if (T.getQualifiers().hasObjCLifetime()) {
4519 SourceLocation AttrLoc;
4520 if (chunkIndex + 1 < D.getNumTypeObjects()) {
4521 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4522 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
4523 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
4524 AttrLoc = AL.getLoc();
4529 if (AttrLoc.isInvalid()) {
4530 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4531 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
4532 AttrLoc = AL.getLoc();
4538 if (AttrLoc.isValid()) {
4539 // The ownership attributes are almost always written via
4541 // __strong/__weak/__autoreleasing/__unsafe_unretained.
4542 if (AttrLoc.isMacroID())
4544 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
4546 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4547 << T.getQualifiers().getObjCLifetime();
4551 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4553 // Types shall not be defined in return or parameter types.
4554 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4555 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4556 << Context.getTypeDeclType(Tag);
4559 // Exception specs are not allowed in typedefs. Complain, but add it
4561 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
4562 S.Diag(FTI.getExceptionSpecLocBeg(),
4563 diag::err_exception_spec_in_typedef)
4564 << (D.getContext() == DeclaratorContext::AliasDeclContext ||
4565 D.getContext() == DeclaratorContext::AliasTemplateContext);
4567 // If we see "T var();" or "T var(T());" at block scope, it is probably
4568 // an attempt to initialize a variable, not a function declaration.
4569 if (FTI.isAmbiguous)
4570 warnAboutAmbiguousFunction(S, D, DeclType, T);
4572 FunctionType::ExtInfo EI(
4573 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
4575 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
4576 && !LangOpts.OpenCL) {
4577 // Simple void foo(), where the incoming T is the result type.
4578 T = Context.getFunctionNoProtoType(T, EI);
4580 // We allow a zero-parameter variadic function in C if the
4581 // function is marked with the "overloadable" attribute. Scan
4582 // for this attribute now.
4583 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus)
4584 if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable))
4585 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4587 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4588 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4590 S.Diag(FTI.Params[0].IdentLoc,
4591 diag::err_ident_list_in_fn_declaration);
4592 D.setInvalidType(true);
4593 // Recover by creating a K&R-style function type.
4594 T = Context.getFunctionNoProtoType(T, EI);
4598 FunctionProtoType::ExtProtoInfo EPI;
4600 EPI.Variadic = FTI.isVariadic;
4601 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
4602 EPI.TypeQuals = FTI.TypeQuals;
4603 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4604 : FTI.RefQualifierIsLValueRef? RQ_LValue
4607 // Otherwise, we have a function with a parameter list that is
4608 // potentially variadic.
4609 SmallVector<QualType, 16> ParamTys;
4610 ParamTys.reserve(FTI.NumParams);
4612 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
4613 ExtParameterInfos(FTI.NumParams);
4614 bool HasAnyInterestingExtParameterInfos = false;
4616 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4617 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4618 QualType ParamTy = Param->getType();
4619 assert(!ParamTy.isNull() && "Couldn't parse type?");
4621 // Look for 'void'. void is allowed only as a single parameter to a
4622 // function with no other parameters (C99 6.7.5.3p10). We record
4623 // int(void) as a FunctionProtoType with an empty parameter list.
4624 if (ParamTy->isVoidType()) {
4625 // If this is something like 'float(int, void)', reject it. 'void'
4626 // is an incomplete type (C99 6.2.5p19) and function decls cannot
4627 // have parameters of incomplete type.
4628 if (FTI.NumParams != 1 || FTI.isVariadic) {
4629 S.Diag(DeclType.Loc, diag::err_void_only_param);
4630 ParamTy = Context.IntTy;
4631 Param->setType(ParamTy);
4632 } else if (FTI.Params[i].Ident) {
4633 // Reject, but continue to parse 'int(void abc)'.
4634 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4635 ParamTy = Context.IntTy;
4636 Param->setType(ParamTy);
4638 // Reject, but continue to parse 'float(const void)'.
4639 if (ParamTy.hasQualifiers())
4640 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4642 // Do not add 'void' to the list.
4645 } else if (ParamTy->isHalfType()) {
4646 // Disallow half FP parameters.
4647 // FIXME: This really should be in BuildFunctionType.
4648 if (S.getLangOpts().OpenCL) {
4649 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4650 S.Diag(Param->getLocation(),
4651 diag::err_opencl_half_param) << ParamTy;
4653 Param->setInvalidDecl();
4655 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4656 S.Diag(Param->getLocation(),
4657 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4660 } else if (!FTI.hasPrototype) {
4661 if (ParamTy->isPromotableIntegerType()) {
4662 ParamTy = Context.getPromotedIntegerType(ParamTy);
4663 Param->setKNRPromoted(true);
4664 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4665 if (BTy->getKind() == BuiltinType::Float) {
4666 ParamTy = Context.DoubleTy;
4667 Param->setKNRPromoted(true);
4672 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4673 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4674 HasAnyInterestingExtParameterInfos = true;
4677 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4678 ExtParameterInfos[i] =
4679 ExtParameterInfos[i].withABI(attr->getABI());
4680 HasAnyInterestingExtParameterInfos = true;
4683 if (Param->hasAttr<PassObjectSizeAttr>()) {
4684 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
4685 HasAnyInterestingExtParameterInfos = true;
4688 if (Param->hasAttr<NoEscapeAttr>()) {
4689 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
4690 HasAnyInterestingExtParameterInfos = true;
4693 ParamTys.push_back(ParamTy);
4696 if (HasAnyInterestingExtParameterInfos) {
4697 EPI.ExtParameterInfos = ExtParameterInfos.data();
4698 checkExtParameterInfos(S, ParamTys, EPI,
4699 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4702 SmallVector<QualType, 4> Exceptions;
4703 SmallVector<ParsedType, 2> DynamicExceptions;
4704 SmallVector<SourceRange, 2> DynamicExceptionRanges;
4705 Expr *NoexceptExpr = nullptr;
4707 if (FTI.getExceptionSpecType() == EST_Dynamic) {
4708 // FIXME: It's rather inefficient to have to split into two vectors
4710 unsigned N = FTI.getNumExceptions();
4711 DynamicExceptions.reserve(N);
4712 DynamicExceptionRanges.reserve(N);
4713 for (unsigned I = 0; I != N; ++I) {
4714 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4715 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4717 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
4718 NoexceptExpr = FTI.NoexceptExpr;
4721 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4722 FTI.getExceptionSpecType(),
4724 DynamicExceptionRanges,
4729 T = Context.getFunctionType(T, ParamTys, EPI);
4733 case DeclaratorChunk::MemberPointer: {
4734 // The scope spec must refer to a class, or be dependent.
4735 CXXScopeSpec &SS = DeclType.Mem.Scope();
4738 // Handle pointer nullability.
4739 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
4740 DeclType.EndLoc, DeclType.getAttrs());
4742 if (SS.isInvalid()) {
4743 // Avoid emitting extra errors if we already errored on the scope.
4744 D.setInvalidType(true);
4745 } else if (S.isDependentScopeSpecifier(SS) ||
4746 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4747 NestedNameSpecifier *NNS = SS.getScopeRep();
4748 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4749 switch (NNS->getKind()) {
4750 case NestedNameSpecifier::Identifier:
4751 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4752 NNS->getAsIdentifier());
4755 case NestedNameSpecifier::Namespace:
4756 case NestedNameSpecifier::NamespaceAlias:
4757 case NestedNameSpecifier::Global:
4758 case NestedNameSpecifier::Super:
4759 llvm_unreachable("Nested-name-specifier must name a type");
4761 case NestedNameSpecifier::TypeSpec:
4762 case NestedNameSpecifier::TypeSpecWithTemplate:
4763 ClsType = QualType(NNS->getAsType(), 0);
4764 // Note: if the NNS has a prefix and ClsType is a nondependent
4765 // TemplateSpecializationType, then the NNS prefix is NOT included
4766 // in ClsType; hence we wrap ClsType into an ElaboratedType.
4767 // NOTE: in particular, no wrap occurs if ClsType already is an
4768 // Elaborated, DependentName, or DependentTemplateSpecialization.
4769 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4770 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4774 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4775 diag::err_illegal_decl_mempointer_in_nonclass)
4776 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4777 << DeclType.Mem.Scope().getRange();
4778 D.setInvalidType(true);
4781 if (!ClsType.isNull())
4782 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4786 D.setInvalidType(true);
4787 } else if (DeclType.Mem.TypeQuals) {
4788 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4793 case DeclaratorChunk::Pipe: {
4794 T = S.BuildReadPipeType(T, DeclType.Loc);
4795 processTypeAttrs(state, T, TAL_DeclSpec,
4796 D.getMutableDeclSpec().getAttributes());
4802 D.setInvalidType(true);
4806 // See if there are any attributes on this declarator chunk.
4807 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
4810 // GNU warning -Wstrict-prototypes
4811 // Warn if a function declaration is without a prototype.
4812 // This warning is issued for all kinds of unprototyped function
4813 // declarations (i.e. function type typedef, function pointer etc.)
4815 // The empty list in a function declarator that is not part of a definition
4816 // of that function specifies that no information about the number or types
4817 // of the parameters is supplied.
4818 if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) {
4819 bool IsBlock = false;
4820 for (const DeclaratorChunk &DeclType : D.type_objects()) {
4821 switch (DeclType.Kind) {
4822 case DeclaratorChunk::BlockPointer:
4825 case DeclaratorChunk::Function: {
4826 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4827 if (FTI.NumParams == 0 && !FTI.isVariadic)
4828 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
4830 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
4840 assert(!T.isNull() && "T must not be null after this point");
4842 if (LangOpts.CPlusPlus && T->isFunctionType()) {
4843 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4844 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4847 // A cv-qualifier-seq shall only be part of the function type
4848 // for a nonstatic member function, the function type to which a pointer
4849 // to member refers, or the top-level function type of a function typedef
4852 // Core issue 547 also allows cv-qualifiers on function types that are
4853 // top-level template type arguments.
4854 enum { NonMember, Member, DeductionGuide } Kind = NonMember;
4855 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
4856 Kind = DeductionGuide;
4857 else if (!D.getCXXScopeSpec().isSet()) {
4858 if ((D.getContext() == DeclaratorContext::MemberContext ||
4859 D.getContext() == DeclaratorContext::LambdaExprContext) &&
4860 !D.getDeclSpec().isFriendSpecified())
4863 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4864 if (!DC || DC->isRecord())
4868 // C++11 [dcl.fct]p6 (w/DR1417):
4869 // An attempt to specify a function type with a cv-qualifier-seq or a
4870 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4871 // - the function type for a non-static member function,
4872 // - the function type to which a pointer to member refers,
4873 // - the top-level function type of a function typedef declaration or
4874 // alias-declaration,
4875 // - the type-id in the default argument of a type-parameter, or
4876 // - the type-id of a template-argument for a type-parameter
4878 // FIXME: Checking this here is insufficient. We accept-invalid on:
4880 // template<typename T> struct S { void f(T); };
4881 // S<int() const> s;
4883 // ... for instance.
4884 if (IsQualifiedFunction &&
4886 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4888 D.getContext() != DeclaratorContext::TemplateArgContext &&
4889 D.getContext() != DeclaratorContext::TemplateTypeArgContext) {
4890 SourceLocation Loc = D.getLocStart();
4891 SourceRange RemovalRange;
4893 if (D.isFunctionDeclarator(I)) {
4894 SmallVector<SourceLocation, 4> RemovalLocs;
4895 const DeclaratorChunk &Chunk = D.getTypeObject(I);
4896 assert(Chunk.Kind == DeclaratorChunk::Function);
4897 if (Chunk.Fun.hasRefQualifier())
4898 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4899 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4900 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4901 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4902 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4903 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4904 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4905 if (!RemovalLocs.empty()) {
4906 llvm::sort(RemovalLocs.begin(), RemovalLocs.end(),
4907 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4908 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4909 Loc = RemovalLocs.front();
4913 S.Diag(Loc, diag::err_invalid_qualified_function_type)
4914 << Kind << D.isFunctionDeclarator() << T
4915 << getFunctionQualifiersAsString(FnTy)
4916 << FixItHint::CreateRemoval(RemovalRange);
4918 // Strip the cv-qualifiers and ref-qualifiers from the type.
4919 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4921 EPI.RefQualifier = RQ_None;
4923 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4925 // Rebuild any parens around the identifier in the function type.
4926 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4927 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4929 T = S.BuildParenType(T);
4934 // Apply any undistributed attributes from the declarator.
4935 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
4937 // Diagnose any ignored type attributes.
4938 state.diagnoseIgnoredTypeAttrs(T);
4940 // C++0x [dcl.constexpr]p9:
4941 // A constexpr specifier used in an object declaration declares the object
4943 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4947 // If there was an ellipsis in the declarator, the declaration declares a
4948 // parameter pack whose type may be a pack expansion type.
4949 if (D.hasEllipsis()) {
4950 // C++0x [dcl.fct]p13:
4951 // A declarator-id or abstract-declarator containing an ellipsis shall
4952 // only be used in a parameter-declaration. Such a parameter-declaration
4953 // is a parameter pack (14.5.3). [...]
4954 switch (D.getContext()) {
4955 case DeclaratorContext::PrototypeContext:
4956 case DeclaratorContext::LambdaExprParameterContext:
4957 // C++0x [dcl.fct]p13:
4958 // [...] When it is part of a parameter-declaration-clause, the
4959 // parameter pack is a function parameter pack (14.5.3). The type T
4960 // of the declarator-id of the function parameter pack shall contain
4961 // a template parameter pack; each template parameter pack in T is
4962 // expanded by the function parameter pack.
4964 // We represent function parameter packs as function parameters whose
4965 // type is a pack expansion.
4966 if (!T->containsUnexpandedParameterPack()) {
4967 S.Diag(D.getEllipsisLoc(),
4968 diag::err_function_parameter_pack_without_parameter_packs)
4969 << T << D.getSourceRange();
4970 D.setEllipsisLoc(SourceLocation());
4972 T = Context.getPackExpansionType(T, None);
4975 case DeclaratorContext::TemplateParamContext:
4976 // C++0x [temp.param]p15:
4977 // If a template-parameter is a [...] is a parameter-declaration that
4978 // declares a parameter pack (8.3.5), then the template-parameter is a
4979 // template parameter pack (14.5.3).
4981 // Note: core issue 778 clarifies that, if there are any unexpanded
4982 // parameter packs in the type of the non-type template parameter, then
4983 // it expands those parameter packs.
4984 if (T->containsUnexpandedParameterPack())
4985 T = Context.getPackExpansionType(T, None);
4987 S.Diag(D.getEllipsisLoc(),
4988 LangOpts.CPlusPlus11
4989 ? diag::warn_cxx98_compat_variadic_templates
4990 : diag::ext_variadic_templates);
4993 case DeclaratorContext::FileContext:
4994 case DeclaratorContext::KNRTypeListContext:
4995 case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic
4997 case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic
4999 case DeclaratorContext::TypeNameContext:
5000 case DeclaratorContext::FunctionalCastContext:
5001 case DeclaratorContext::CXXNewContext:
5002 case DeclaratorContext::AliasDeclContext:
5003 case DeclaratorContext::AliasTemplateContext:
5004 case DeclaratorContext::MemberContext:
5005 case DeclaratorContext::BlockContext:
5006 case DeclaratorContext::ForContext:
5007 case DeclaratorContext::InitStmtContext:
5008 case DeclaratorContext::ConditionContext:
5009 case DeclaratorContext::CXXCatchContext:
5010 case DeclaratorContext::ObjCCatchContext:
5011 case DeclaratorContext::BlockLiteralContext:
5012 case DeclaratorContext::LambdaExprContext:
5013 case DeclaratorContext::ConversionIdContext:
5014 case DeclaratorContext::TrailingReturnContext:
5015 case DeclaratorContext::TrailingReturnVarContext:
5016 case DeclaratorContext::TemplateArgContext:
5017 case DeclaratorContext::TemplateTypeArgContext:
5018 // FIXME: We may want to allow parameter packs in block-literal contexts
5020 S.Diag(D.getEllipsisLoc(),
5021 diag::err_ellipsis_in_declarator_not_parameter);
5022 D.setEllipsisLoc(SourceLocation());
5027 assert(!T.isNull() && "T must not be null at the end of this function");
5028 if (D.isInvalidType())
5029 return Context.getTrivialTypeSourceInfo(T);
5031 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
5034 /// GetTypeForDeclarator - Convert the type for the specified
5035 /// declarator to Type instances.
5037 /// The result of this call will never be null, but the associated
5038 /// type may be a null type if there's an unrecoverable error.
5039 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
5040 // Determine the type of the declarator. Not all forms of declarator
5043 TypeProcessingState state(*this, D);
5045 TypeSourceInfo *ReturnTypeInfo = nullptr;
5046 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5047 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5048 inferARCWriteback(state, T);
5050 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5053 static void transferARCOwnershipToDeclSpec(Sema &S,
5054 QualType &declSpecTy,
5055 Qualifiers::ObjCLifetime ownership) {
5056 if (declSpecTy->isObjCRetainableType() &&
5057 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5059 qs.addObjCLifetime(ownership);
5060 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5064 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5065 Qualifiers::ObjCLifetime ownership,
5066 unsigned chunkIndex) {
5067 Sema &S = state.getSema();
5068 Declarator &D = state.getDeclarator();
5070 // Look for an explicit lifetime attribute.
5071 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5072 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5075 const char *attrStr = nullptr;
5076 switch (ownership) {
5077 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5078 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5079 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5080 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5081 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5084 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5085 Arg->Ident = &S.Context.Idents.get(attrStr);
5086 Arg->Loc = SourceLocation();
5088 ArgsUnion Args(Arg);
5090 // If there wasn't one, add one (with an invalid source location
5091 // so that we don't make an AttributedType for it).
5092 ParsedAttr *attr = D.getAttributePool().create(
5093 &S.Context.Idents.get("objc_ownership"), SourceLocation(),
5094 /*scope*/ nullptr, SourceLocation(),
5095 /*args*/ &Args, 1, ParsedAttr::AS_GNU);
5096 chunk.getAttrs().addAtStart(attr);
5097 // TODO: mark whether we did this inference?
5100 /// Used for transferring ownership in casts resulting in l-values.
5101 static void transferARCOwnership(TypeProcessingState &state,
5102 QualType &declSpecTy,
5103 Qualifiers::ObjCLifetime ownership) {
5104 Sema &S = state.getSema();
5105 Declarator &D = state.getDeclarator();
5108 bool hasIndirection = false;
5109 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5110 DeclaratorChunk &chunk = D.getTypeObject(i);
5111 switch (chunk.Kind) {
5112 case DeclaratorChunk::Paren:
5116 case DeclaratorChunk::Array:
5117 case DeclaratorChunk::Reference:
5118 case DeclaratorChunk::Pointer:
5120 hasIndirection = true;
5124 case DeclaratorChunk::BlockPointer:
5126 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5129 case DeclaratorChunk::Function:
5130 case DeclaratorChunk::MemberPointer:
5131 case DeclaratorChunk::Pipe:
5139 DeclaratorChunk &chunk = D.getTypeObject(inner);
5140 if (chunk.Kind == DeclaratorChunk::Pointer) {
5141 if (declSpecTy->isObjCRetainableType())
5142 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5143 if (declSpecTy->isObjCObjectType() && hasIndirection)
5144 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5146 assert(chunk.Kind == DeclaratorChunk::Array ||
5147 chunk.Kind == DeclaratorChunk::Reference);
5148 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5152 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
5153 TypeProcessingState state(*this, D);
5155 TypeSourceInfo *ReturnTypeInfo = nullptr;
5156 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5158 if (getLangOpts().ObjC1) {
5159 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5160 if (ownership != Qualifiers::OCL_None)
5161 transferARCOwnership(state, declSpecTy, ownership);
5164 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5167 /// Map an AttributedType::Kind to an ParsedAttr::Kind.
5168 static ParsedAttr::Kind getAttrListKind(AttributedType::Kind kind) {
5170 case AttributedType::attr_address_space:
5171 return ParsedAttr::AT_AddressSpace;
5172 case AttributedType::attr_regparm:
5173 return ParsedAttr::AT_Regparm;
5174 case AttributedType::attr_vector_size:
5175 return ParsedAttr::AT_VectorSize;
5176 case AttributedType::attr_neon_vector_type:
5177 return ParsedAttr::AT_NeonVectorType;
5178 case AttributedType::attr_neon_polyvector_type:
5179 return ParsedAttr::AT_NeonPolyVectorType;
5180 case AttributedType::attr_objc_gc:
5181 return ParsedAttr::AT_ObjCGC;
5182 case AttributedType::attr_objc_ownership:
5183 case AttributedType::attr_objc_inert_unsafe_unretained:
5184 return ParsedAttr::AT_ObjCOwnership;
5185 case AttributedType::attr_noreturn:
5186 return ParsedAttr::AT_NoReturn;
5187 case AttributedType::attr_nocf_check:
5188 return ParsedAttr::AT_AnyX86NoCfCheck;
5189 case AttributedType::attr_cdecl:
5190 return ParsedAttr::AT_CDecl;
5191 case AttributedType::attr_fastcall:
5192 return ParsedAttr::AT_FastCall;
5193 case AttributedType::attr_stdcall:
5194 return ParsedAttr::AT_StdCall;
5195 case AttributedType::attr_thiscall:
5196 return ParsedAttr::AT_ThisCall;
5197 case AttributedType::attr_regcall:
5198 return ParsedAttr::AT_RegCall;
5199 case AttributedType::attr_pascal:
5200 return ParsedAttr::AT_Pascal;
5201 case AttributedType::attr_swiftcall:
5202 return ParsedAttr::AT_SwiftCall;
5203 case AttributedType::attr_vectorcall:
5204 return ParsedAttr::AT_VectorCall;
5205 case AttributedType::attr_pcs:
5206 case AttributedType::attr_pcs_vfp:
5207 return ParsedAttr::AT_Pcs;
5208 case AttributedType::attr_inteloclbicc:
5209 return ParsedAttr::AT_IntelOclBicc;
5210 case AttributedType::attr_ms_abi:
5211 return ParsedAttr::AT_MSABI;
5212 case AttributedType::attr_sysv_abi:
5213 return ParsedAttr::AT_SysVABI;
5214 case AttributedType::attr_preserve_most:
5215 return ParsedAttr::AT_PreserveMost;
5216 case AttributedType::attr_preserve_all:
5217 return ParsedAttr::AT_PreserveAll;
5218 case AttributedType::attr_ptr32:
5219 return ParsedAttr::AT_Ptr32;
5220 case AttributedType::attr_ptr64:
5221 return ParsedAttr::AT_Ptr64;
5222 case AttributedType::attr_sptr:
5223 return ParsedAttr::AT_SPtr;
5224 case AttributedType::attr_uptr:
5225 return ParsedAttr::AT_UPtr;
5226 case AttributedType::attr_nonnull:
5227 return ParsedAttr::AT_TypeNonNull;
5228 case AttributedType::attr_nullable:
5229 return ParsedAttr::AT_TypeNullable;
5230 case AttributedType::attr_null_unspecified:
5231 return ParsedAttr::AT_TypeNullUnspecified;
5232 case AttributedType::attr_objc_kindof:
5233 return ParsedAttr::AT_ObjCKindOf;
5234 case AttributedType::attr_ns_returns_retained:
5235 return ParsedAttr::AT_NSReturnsRetained;
5236 case AttributedType::attr_lifetimebound:
5237 return ParsedAttr::AT_LifetimeBound;
5239 llvm_unreachable("unexpected attribute kind!");
5242 static void setAttributedTypeLoc(AttributedTypeLoc TL, const ParsedAttr &attr) {
5243 TL.setAttrNameLoc(attr.getLoc());
5244 if (TL.hasAttrExprOperand()) {
5245 assert(attr.isArgExpr(0) && "mismatched attribute operand kind");
5246 TL.setAttrExprOperand(attr.getArgAsExpr(0));
5247 } else if (TL.hasAttrEnumOperand()) {
5248 assert((attr.isArgIdent(0) || attr.isArgExpr(0)) &&
5249 "unexpected attribute operand kind");
5250 if (attr.isArgIdent(0))
5251 TL.setAttrEnumOperandLoc(attr.getArgAsIdent(0)->Loc);
5253 TL.setAttrEnumOperandLoc(attr.getArgAsExpr(0)->getExprLoc());
5256 // FIXME: preserve this information to here.
5257 if (TL.hasAttrOperand())
5258 TL.setAttrOperandParensRange(SourceRange());
5261 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5262 const ParsedAttributesView &Attrs,
5263 const ParsedAttributesView &DeclAttrs) {
5264 // DeclAttrs and Attrs cannot be both empty.
5265 assert((!Attrs.empty() || !DeclAttrs.empty()) &&
5266 "no type attributes in the expected location!");
5268 ParsedAttr::Kind parsedKind = getAttrListKind(TL.getAttrKind());
5269 // Try to search for an attribute of matching kind in Attrs list.
5270 for (const ParsedAttr &AL : Attrs)
5271 if (AL.getKind() == parsedKind)
5272 return setAttributedTypeLoc(TL, AL);
5274 for (const ParsedAttr &AL : DeclAttrs)
5275 if (AL.isCXX11Attribute() || AL.getKind() == parsedKind)
5276 return setAttributedTypeLoc(TL, AL);
5277 llvm_unreachable("no matching type attribute in expected location!");
5281 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5282 ASTContext &Context;
5286 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
5287 : Context(Context), DS(DS) {}
5289 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5290 fillAttributedTypeLoc(TL, DS.getAttributes(), ParsedAttributesView{});
5291 Visit(TL.getModifiedLoc());
5293 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5294 Visit(TL.getUnqualifiedLoc());
5296 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5297 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5299 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5300 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5301 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5302 // addition field. What we have is good enough for dispay of location
5303 // of 'fixit' on interface name.
5304 TL.setNameEndLoc(DS.getLocEnd());
5306 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5307 TypeSourceInfo *RepTInfo = nullptr;
5308 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5309 TL.copy(RepTInfo->getTypeLoc());
5311 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5312 TypeSourceInfo *RepTInfo = nullptr;
5313 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5314 TL.copy(RepTInfo->getTypeLoc());
5316 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5317 TypeSourceInfo *TInfo = nullptr;
5318 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5320 // If we got no declarator info from previous Sema routines,
5321 // just fill with the typespec loc.
5323 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5327 TypeLoc OldTL = TInfo->getTypeLoc();
5328 if (TInfo->getType()->getAs<ElaboratedType>()) {
5329 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5330 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5331 .castAs<TemplateSpecializationTypeLoc>();
5334 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5335 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
5339 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5340 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
5341 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5342 TL.setParensRange(DS.getTypeofParensRange());
5344 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5345 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
5346 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5347 TL.setParensRange(DS.getTypeofParensRange());
5348 assert(DS.getRepAsType());
5349 TypeSourceInfo *TInfo = nullptr;
5350 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5351 TL.setUnderlyingTInfo(TInfo);
5353 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5354 // FIXME: This holds only because we only have one unary transform.
5355 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
5356 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5357 TL.setParensRange(DS.getTypeofParensRange());
5358 assert(DS.getRepAsType());
5359 TypeSourceInfo *TInfo = nullptr;
5360 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5361 TL.setUnderlyingTInfo(TInfo);
5363 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5364 // By default, use the source location of the type specifier.
5365 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5366 if (TL.needsExtraLocalData()) {
5367 // Set info for the written builtin specifiers.
5368 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5369 // Try to have a meaningful source location.
5370 if (TL.getWrittenSignSpec() != TSS_unspecified)
5371 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5372 if (TL.getWrittenWidthSpec() != TSW_unspecified)
5373 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5376 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5377 ElaboratedTypeKeyword Keyword
5378 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5379 if (DS.getTypeSpecType() == TST_typename) {
5380 TypeSourceInfo *TInfo = nullptr;
5381 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5383 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5387 TL.setElaboratedKeywordLoc(Keyword != ETK_None
5388 ? DS.getTypeSpecTypeLoc()
5389 : SourceLocation());
5390 const CXXScopeSpec& SS = DS.getTypeSpecScope();
5391 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5392 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5394 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5395 assert(DS.getTypeSpecType() == TST_typename);
5396 TypeSourceInfo *TInfo = nullptr;
5397 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5399 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
5401 void VisitDependentTemplateSpecializationTypeLoc(
5402 DependentTemplateSpecializationTypeLoc TL) {
5403 assert(DS.getTypeSpecType() == TST_typename);
5404 TypeSourceInfo *TInfo = nullptr;
5405 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5408 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
5410 void VisitTagTypeLoc(TagTypeLoc TL) {
5411 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
5413 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5414 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
5415 // or an _Atomic qualifier.
5416 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
5417 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5418 TL.setParensRange(DS.getTypeofParensRange());
5420 TypeSourceInfo *TInfo = nullptr;
5421 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5423 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5425 TL.setKWLoc(DS.getAtomicSpecLoc());
5426 // No parens, to indicate this was spelled as an _Atomic qualifier.
5427 TL.setParensRange(SourceRange());
5428 Visit(TL.getValueLoc());
5432 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5433 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5435 TypeSourceInfo *TInfo = nullptr;
5436 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5437 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5440 void VisitTypeLoc(TypeLoc TL) {
5441 // FIXME: add other typespec types and change this to an assert.
5442 TL.initialize(Context, DS.getTypeSpecTypeLoc());
5446 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
5447 ASTContext &Context;
5448 const DeclaratorChunk &Chunk;
5451 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
5452 : Context(Context), Chunk(Chunk) {}
5454 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5455 llvm_unreachable("qualified type locs not expected here!");
5457 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5458 llvm_unreachable("decayed type locs not expected here!");
5461 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5462 fillAttributedTypeLoc(TL, Chunk.getAttrs(), ParsedAttributesView{});
5464 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5467 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5468 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
5469 TL.setCaretLoc(Chunk.Loc);
5471 void VisitPointerTypeLoc(PointerTypeLoc TL) {
5472 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5473 TL.setStarLoc(Chunk.Loc);
5475 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5476 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5477 TL.setStarLoc(Chunk.Loc);
5479 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5480 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
5481 const CXXScopeSpec& SS = Chunk.Mem.Scope();
5482 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
5484 const Type* ClsTy = TL.getClass();
5485 QualType ClsQT = QualType(ClsTy, 0);
5486 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5487 // Now copy source location info into the type loc component.
5488 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5489 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5490 case NestedNameSpecifier::Identifier:
5491 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
5493 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
5494 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
5495 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5496 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5500 case NestedNameSpecifier::TypeSpec:
5501 case NestedNameSpecifier::TypeSpecWithTemplate:
5502 if (isa<ElaboratedType>(ClsTy)) {
5503 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5504 ETLoc.setElaboratedKeywordLoc(SourceLocation());
5505 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5506 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5507 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5509 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
5513 case NestedNameSpecifier::Namespace:
5514 case NestedNameSpecifier::NamespaceAlias:
5515 case NestedNameSpecifier::Global:
5516 case NestedNameSpecifier::Super:
5517 llvm_unreachable("Nested-name-specifier must name a type");
5520 // Finally fill in MemberPointerLocInfo fields.
5521 TL.setStarLoc(Chunk.Loc);
5522 TL.setClassTInfo(ClsTInfo);
5524 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5525 assert(Chunk.Kind == DeclaratorChunk::Reference);
5526 // 'Amp' is misleading: this might have been originally
5527 /// spelled with AmpAmp.
5528 TL.setAmpLoc(Chunk.Loc);
5530 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5531 assert(Chunk.Kind == DeclaratorChunk::Reference);
5532 assert(!Chunk.Ref.LValueRef);
5533 TL.setAmpAmpLoc(Chunk.Loc);
5535 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
5536 assert(Chunk.Kind == DeclaratorChunk::Array);
5537 TL.setLBracketLoc(Chunk.Loc);
5538 TL.setRBracketLoc(Chunk.EndLoc);
5539 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
5541 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5542 assert(Chunk.Kind == DeclaratorChunk::Function);
5543 TL.setLocalRangeBegin(Chunk.Loc);
5544 TL.setLocalRangeEnd(Chunk.EndLoc);
5546 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
5547 TL.setLParenLoc(FTI.getLParenLoc());
5548 TL.setRParenLoc(FTI.getRParenLoc());
5549 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
5550 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5551 TL.setParam(tpi++, Param);
5553 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
5555 void VisitParenTypeLoc(ParenTypeLoc TL) {
5556 assert(Chunk.Kind == DeclaratorChunk::Paren);
5557 TL.setLParenLoc(Chunk.Loc);
5558 TL.setRParenLoc(Chunk.EndLoc);
5560 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5561 assert(Chunk.Kind == DeclaratorChunk::Pipe);
5562 TL.setKWLoc(Chunk.Loc);
5565 void VisitTypeLoc(TypeLoc TL) {
5566 llvm_unreachable("unsupported TypeLoc kind in declarator!");
5569 } // end anonymous namespace
5571 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5573 switch (Chunk.Kind) {
5574 case DeclaratorChunk::Function:
5575 case DeclaratorChunk::Array:
5576 case DeclaratorChunk::Paren:
5577 case DeclaratorChunk::Pipe:
5578 llvm_unreachable("cannot be _Atomic qualified");
5580 case DeclaratorChunk::Pointer:
5581 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
5584 case DeclaratorChunk::BlockPointer:
5585 case DeclaratorChunk::Reference:
5586 case DeclaratorChunk::MemberPointer:
5587 // FIXME: Provide a source location for the _Atomic keyword.
5592 ATL.setParensRange(SourceRange());
5596 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
5597 const ParsedAttributesView &Attrs) {
5598 for (const ParsedAttr &AL : Attrs) {
5599 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
5600 DASTL.setAttrNameLoc(AL.getLoc());
5601 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
5602 DASTL.setAttrOperandParensRange(SourceRange());
5608 "no address_space attribute found at the expected location!");
5611 /// Create and instantiate a TypeSourceInfo with type source information.
5613 /// \param T QualType referring to the type as written in source code.
5615 /// \param ReturnTypeInfo For declarators whose return type does not show
5616 /// up in the normal place in the declaration specifiers (such as a C++
5617 /// conversion function), this pointer will refer to a type source information
5618 /// for that return type.
5620 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
5621 TypeSourceInfo *ReturnTypeInfo) {
5622 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
5623 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
5625 // Handle parameter packs whose type is a pack expansion.
5626 if (isa<PackExpansionType>(T)) {
5627 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
5628 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5631 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5633 if (DependentAddressSpaceTypeLoc DASTL =
5634 CurrTL.getAs<DependentAddressSpaceTypeLoc>()) {
5635 fillDependentAddressSpaceTypeLoc(DASTL, D.getTypeObject(i).getAttrs());
5636 CurrTL = DASTL.getPointeeTypeLoc().getUnqualifiedLoc();
5639 // An AtomicTypeLoc might be produced by an atomic qualifier in this
5640 // declarator chunk.
5641 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
5642 fillAtomicQualLoc(ATL, D.getTypeObject(i));
5643 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
5646 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
5647 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(),
5649 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5652 // FIXME: Ordering here?
5653 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
5654 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5656 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
5657 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5660 // If we have different source information for the return type, use
5661 // that. This really only applies to C++ conversion functions.
5662 if (ReturnTypeInfo) {
5663 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
5664 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
5665 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
5667 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
5673 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
5674 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
5675 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
5676 // and Sema during declaration parsing. Try deallocating/caching them when
5677 // it's appropriate, instead of allocating them and keeping them around.
5678 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
5680 new (LocT) LocInfoType(T, TInfo);
5681 assert(LocT->getTypeClass() != T->getTypeClass() &&
5682 "LocInfoType's TypeClass conflicts with an existing Type class");
5683 return ParsedType::make(QualType(LocT, 0));
5686 void LocInfoType::getAsStringInternal(std::string &Str,
5687 const PrintingPolicy &Policy) const {
5688 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
5689 " was used directly instead of getting the QualType through"
5690 " GetTypeFromParser");
5693 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
5694 // C99 6.7.6: Type names have no identifier. This is already validated by
5696 assert(D.getIdentifier() == nullptr &&
5697 "Type name should have no identifier!");
5699 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5700 QualType T = TInfo->getType();
5701 if (D.isInvalidType())
5704 // Make sure there are no unused decl attributes on the declarator.
5705 // We don't want to do this for ObjC parameters because we're going
5706 // to apply them to the actual parameter declaration.
5707 // Likewise, we don't want to do this for alias declarations, because
5708 // we are actually going to build a declaration from this eventually.
5709 if (D.getContext() != DeclaratorContext::ObjCParameterContext &&
5710 D.getContext() != DeclaratorContext::AliasDeclContext &&
5711 D.getContext() != DeclaratorContext::AliasTemplateContext)
5712 checkUnusedDeclAttributes(D);
5714 if (getLangOpts().CPlusPlus) {
5715 // Check that there are no default arguments (C++ only).
5716 CheckExtraCXXDefaultArguments(D);
5719 return CreateParsedType(T, TInfo);
5722 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
5723 QualType T = Context.getObjCInstanceType();
5724 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
5725 return CreateParsedType(T, TInfo);
5728 //===----------------------------------------------------------------------===//
5729 // Type Attribute Processing
5730 //===----------------------------------------------------------------------===//
5732 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
5733 /// is uninstantiated. If instantiated it will apply the appropriate address space
5734 /// to the type. This function allows dependent template variables to be used in
5735 /// conjunction with the address_space attribute
5736 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
5737 SourceLocation AttrLoc) {
5738 if (!AddrSpace->isValueDependent()) {
5740 llvm::APSInt addrSpace(32);
5741 if (!AddrSpace->isIntegerConstantExpr(addrSpace, Context)) {
5742 Diag(AttrLoc, diag::err_attribute_argument_type)
5743 << "'address_space'" << AANT_ArgumentIntegerConstant
5744 << AddrSpace->getSourceRange();
5749 if (addrSpace.isSigned()) {
5750 if (addrSpace.isNegative()) {
5751 Diag(AttrLoc, diag::err_attribute_address_space_negative)
5752 << AddrSpace->getSourceRange();
5755 addrSpace.setIsSigned(false);
5758 llvm::APSInt max(addrSpace.getBitWidth());
5760 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
5761 if (addrSpace > max) {
5762 Diag(AttrLoc, diag::err_attribute_address_space_too_high)
5763 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
5768 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
5770 // If this type is already address space qualified with a different
5771 // address space, reject it.
5772 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
5773 // by qualifiers for two or more different address spaces."
5774 if (T.getAddressSpace() != LangAS::Default) {
5775 if (T.getAddressSpace() != ASIdx) {
5776 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
5779 // Emit a warning if they are identical; it's likely unintended.
5781 diag::warn_attribute_address_multiple_identical_qualifiers);
5784 return Context.getAddrSpaceQualType(T, ASIdx);
5787 // A check with similar intentions as checking if a type already has an
5788 // address space except for on a dependent types, basically if the
5789 // current type is already a DependentAddressSpaceType then its already
5790 // lined up to have another address space on it and we can't have
5791 // multiple address spaces on the one pointer indirection
5792 if (T->getAs<DependentAddressSpaceType>()) {
5793 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
5797 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
5800 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5801 /// specified type. The attribute contains 1 argument, the id of the address
5802 /// space for the type.
5803 static void HandleAddressSpaceTypeAttribute(QualType &Type,
5804 const ParsedAttr &Attr, Sema &S) {
5805 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5806 // qualified by an address-space qualifier."
5807 if (Type->isFunctionType()) {
5808 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5814 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
5816 // Check the attribute arguments.
5817 if (Attr.getNumArgs() != 1) {
5818 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5819 << Attr.getName() << 1;
5825 if (Attr.isArgIdent(0)) {
5826 // Special case where the argument is a template id.
5828 SourceLocation TemplateKWLoc;
5830 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
5832 ExprResult AddrSpace = S.ActOnIdExpression(
5833 S.getCurScope(), SS, TemplateKWLoc, id, false, false);
5834 if (AddrSpace.isInvalid())
5837 ASArgExpr = static_cast<Expr *>(AddrSpace.get());
5839 ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5842 // Create the DependentAddressSpaceType or append an address space onto
5844 QualType T = S.BuildAddressSpaceAttr(Type, ASArgExpr, Attr.getLoc());
5851 // The keyword-based type attributes imply which address space to use.
5852 switch (Attr.getKind()) {
5853 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
5854 ASIdx = LangAS::opencl_global; break;
5855 case ParsedAttr::AT_OpenCLLocalAddressSpace:
5856 ASIdx = LangAS::opencl_local; break;
5857 case ParsedAttr::AT_OpenCLConstantAddressSpace:
5858 ASIdx = LangAS::opencl_constant; break;
5859 case ParsedAttr::AT_OpenCLGenericAddressSpace:
5860 ASIdx = LangAS::opencl_generic; break;
5861 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
5862 ASIdx = LangAS::opencl_private; break;
5864 llvm_unreachable("Invalid address space");
5867 // If this type is already address space qualified with a different
5868 // address space, reject it.
5869 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5870 // qualifiers for two or more different address spaces."
5871 if (Type.getAddressSpace() != LangAS::Default) {
5872 if (Type.getAddressSpace() != ASIdx) {
5873 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5877 // Emit a warning if they are identical; it's likely unintended.
5878 S.Diag(Attr.getLoc(),
5879 diag::warn_attribute_address_multiple_identical_qualifiers);
5882 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5886 /// Does this type have a "direct" ownership qualifier? That is,
5887 /// is it written like "__strong id", as opposed to something like
5888 /// "typeof(foo)", where that happens to be strong?
5889 static bool hasDirectOwnershipQualifier(QualType type) {
5890 // Fast path: no qualifier at all.
5891 assert(type.getQualifiers().hasObjCLifetime());
5895 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5896 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5899 type = attr->getModifiedType();
5901 // X *__strong (...)
5902 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5903 type = paren->getInnerType();
5905 // That's it for things we want to complain about. In particular,
5906 // we do not want to look through typedefs, typeof(expr),
5907 // typeof(type), or any other way that the type is somehow
5916 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5917 /// attribute on the specified type.
5919 /// Returns 'true' if the attribute was handled.
5920 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5921 ParsedAttr &attr, QualType &type) {
5922 bool NonObjCPointer = false;
5924 if (!type->isDependentType() && !type->isUndeducedType()) {
5925 if (const PointerType *ptr = type->getAs<PointerType>()) {
5926 QualType pointee = ptr->getPointeeType();
5927 if (pointee->isObjCRetainableType() || pointee->isPointerType())
5929 // It is important not to lose the source info that there was an attribute
5930 // applied to non-objc pointer. We will create an attributed type but
5931 // its type will be the same as the original type.
5932 NonObjCPointer = true;
5933 } else if (!type->isObjCRetainableType()) {
5937 // Don't accept an ownership attribute in the declspec if it would
5938 // just be the return type of a block pointer.
5939 if (state.isProcessingDeclSpec()) {
5940 Declarator &D = state.getDeclarator();
5941 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5942 /*onlyBlockPointers=*/true))
5947 Sema &S = state.getSema();
5948 SourceLocation AttrLoc = attr.getLoc();
5949 if (AttrLoc.isMacroID())
5951 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
5953 if (!attr.isArgIdent(0)) {
5954 S.Diag(AttrLoc, diag::err_attribute_argument_type)
5955 << attr.getName() << AANT_ArgumentString;
5960 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5961 Qualifiers::ObjCLifetime lifetime;
5962 if (II->isStr("none"))
5963 lifetime = Qualifiers::OCL_ExplicitNone;
5964 else if (II->isStr("strong"))
5965 lifetime = Qualifiers::OCL_Strong;
5966 else if (II->isStr("weak"))
5967 lifetime = Qualifiers::OCL_Weak;
5968 else if (II->isStr("autoreleasing"))
5969 lifetime = Qualifiers::OCL_Autoreleasing;
5971 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5972 << attr.getName() << II;
5977 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
5978 // outside of ARC mode.
5979 if (!S.getLangOpts().ObjCAutoRefCount &&
5980 lifetime != Qualifiers::OCL_Weak &&
5981 lifetime != Qualifiers::OCL_ExplicitNone) {
5985 SplitQualType underlyingType = type.split();
5987 // Check for redundant/conflicting ownership qualifiers.
5988 if (Qualifiers::ObjCLifetime previousLifetime
5989 = type.getQualifiers().getObjCLifetime()) {
5990 // If it's written directly, that's an error.
5991 if (hasDirectOwnershipQualifier(type)) {
5992 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5997 // Otherwise, if the qualifiers actually conflict, pull sugar off
5998 // and remove the ObjCLifetime qualifiers.
5999 if (previousLifetime != lifetime) {
6000 // It's possible to have multiple local ObjCLifetime qualifiers. We
6001 // can't stop after we reach a type that is directly qualified.
6002 const Type *prevTy = nullptr;
6003 while (!prevTy || prevTy != underlyingType.Ty) {
6004 prevTy = underlyingType.Ty;
6005 underlyingType = underlyingType.getSingleStepDesugaredType();
6007 underlyingType.Quals.removeObjCLifetime();
6011 underlyingType.Quals.addObjCLifetime(lifetime);
6013 if (NonObjCPointer) {
6014 StringRef name = attr.getName()->getName();
6016 case Qualifiers::OCL_None:
6017 case Qualifiers::OCL_ExplicitNone:
6019 case Qualifiers::OCL_Strong: name = "__strong"; break;
6020 case Qualifiers::OCL_Weak: name = "__weak"; break;
6021 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6023 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6024 << TDS_ObjCObjOrBlock << type;
6027 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6028 // because having both 'T' and '__unsafe_unretained T' exist in the type
6029 // system causes unfortunate widespread consistency problems. (For example,
6030 // they're not considered compatible types, and we mangle them identicially
6031 // as template arguments.) These problems are all individually fixable,
6032 // but it's easier to just not add the qualifier and instead sniff it out
6033 // in specific places using isObjCInertUnsafeUnretainedType().
6035 // Doing this does means we miss some trivial consistency checks that
6036 // would've triggered in ARC, but that's better than trying to solve all
6037 // the coexistence problems with __unsafe_unretained.
6038 if (!S.getLangOpts().ObjCAutoRefCount &&
6039 lifetime == Qualifiers::OCL_ExplicitNone) {
6040 type = S.Context.getAttributedType(
6041 AttributedType::attr_objc_inert_unsafe_unretained,
6046 QualType origType = type;
6047 if (!NonObjCPointer)
6048 type = S.Context.getQualifiedType(underlyingType);
6050 // If we have a valid source location for the attribute, use an
6051 // AttributedType instead.
6052 if (AttrLoc.isValid())
6053 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
6056 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6057 unsigned diagnostic, QualType type) {
6058 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
6059 S.DelayedDiagnostics.add(
6060 sema::DelayedDiagnostic::makeForbiddenType(
6061 S.getSourceManager().getExpansionLoc(loc),
6062 diagnostic, type, /*ignored*/ 0));
6064 S.Diag(loc, diagnostic);
6068 // Sometimes, __weak isn't allowed.
6069 if (lifetime == Qualifiers::OCL_Weak &&
6070 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6072 // Use a specialized diagnostic if the runtime just doesn't support them.
6073 unsigned diagnostic =
6074 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6075 : diag::err_arc_weak_no_runtime);
6077 // In any case, delay the diagnostic until we know what we're parsing.
6078 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6084 // Forbid __weak for class objects marked as
6085 // objc_arc_weak_reference_unavailable
6086 if (lifetime == Qualifiers::OCL_Weak) {
6087 if (const ObjCObjectPointerType *ObjT =
6088 type->getAs<ObjCObjectPointerType>()) {
6089 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6090 if (Class->isArcWeakrefUnavailable()) {
6091 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6092 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6093 diag::note_class_declared);
6102 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6103 /// attribute on the specified type. Returns true to indicate that
6104 /// the attribute was handled, false to indicate that the type does
6105 /// not permit the attribute.
6106 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6108 Sema &S = state.getSema();
6110 // Delay if this isn't some kind of pointer.
6111 if (!type->isPointerType() &&
6112 !type->isObjCObjectPointerType() &&
6113 !type->isBlockPointerType())
6116 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
6117 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
6122 // Check the attribute arguments.
6123 if (!attr.isArgIdent(0)) {
6124 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
6125 << attr.getName() << AANT_ArgumentString;
6129 Qualifiers::GC GCAttr;
6130 if (attr.getNumArgs() > 1) {
6131 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6132 << attr.getName() << 1;
6137 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6138 if (II->isStr("weak"))
6139 GCAttr = Qualifiers::Weak;
6140 else if (II->isStr("strong"))
6141 GCAttr = Qualifiers::Strong;
6143 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
6144 << attr.getName() << II;
6149 QualType origType = type;
6150 type = S.Context.getObjCGCQualType(origType, GCAttr);
6152 // Make an attributed type to preserve the source information.
6153 if (attr.getLoc().isValid())
6154 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
6161 /// A helper class to unwrap a type down to a function for the
6162 /// purposes of applying attributes there.
6165 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
6166 /// if (unwrapped.isFunctionType()) {
6167 /// const FunctionType *fn = unwrapped.get();
6168 /// // change fn somehow
6169 /// T = unwrapped.wrap(fn);
6171 struct FunctionTypeUnwrapper {
6183 const FunctionType *Fn;
6184 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
6186 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
6188 const Type *Ty = T.getTypePtr();
6189 if (isa<FunctionType>(Ty)) {
6190 Fn = cast<FunctionType>(Ty);
6192 } else if (isa<ParenType>(Ty)) {
6193 T = cast<ParenType>(Ty)->getInnerType();
6194 Stack.push_back(Parens);
6195 } else if (isa<PointerType>(Ty)) {
6196 T = cast<PointerType>(Ty)->getPointeeType();
6197 Stack.push_back(Pointer);
6198 } else if (isa<BlockPointerType>(Ty)) {
6199 T = cast<BlockPointerType>(Ty)->getPointeeType();
6200 Stack.push_back(BlockPointer);
6201 } else if (isa<MemberPointerType>(Ty)) {
6202 T = cast<MemberPointerType>(Ty)->getPointeeType();
6203 Stack.push_back(MemberPointer);
6204 } else if (isa<ReferenceType>(Ty)) {
6205 T = cast<ReferenceType>(Ty)->getPointeeType();
6206 Stack.push_back(Reference);
6207 } else if (isa<AttributedType>(Ty)) {
6208 T = cast<AttributedType>(Ty)->getEquivalentType();
6209 Stack.push_back(Attributed);
6211 const Type *DTy = Ty->getUnqualifiedDesugaredType();
6217 T = QualType(DTy, 0);
6218 Stack.push_back(Desugar);
6223 bool isFunctionType() const { return (Fn != nullptr); }
6224 const FunctionType *get() const { return Fn; }
6226 QualType wrap(Sema &S, const FunctionType *New) {
6227 // If T wasn't modified from the unwrapped type, do nothing.
6228 if (New == get()) return Original;
6231 return wrap(S.Context, Original, 0);
6235 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
6236 if (I == Stack.size())
6237 return C.getQualifiedType(Fn, Old.getQualifiers());
6239 // Build up the inner type, applying the qualifiers from the old
6240 // type to the new type.
6241 SplitQualType SplitOld = Old.split();
6243 // As a special case, tail-recurse if there are no qualifiers.
6244 if (SplitOld.Quals.empty())
6245 return wrap(C, SplitOld.Ty, I);
6246 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
6249 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
6250 if (I == Stack.size()) return QualType(Fn, 0);
6252 switch (static_cast<WrapKind>(Stack[I++])) {
6254 // This is the point at which we potentially lose source
6256 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
6259 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
6262 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
6263 return C.getParenType(New);
6267 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
6268 return C.getPointerType(New);
6271 case BlockPointer: {
6272 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
6273 return C.getBlockPointerType(New);
6276 case MemberPointer: {
6277 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
6278 QualType New = wrap(C, OldMPT->getPointeeType(), I);
6279 return C.getMemberPointerType(New, OldMPT->getClass());
6283 const ReferenceType *OldRef = cast<ReferenceType>(Old);
6284 QualType New = wrap(C, OldRef->getPointeeType(), I);
6285 if (isa<LValueReferenceType>(OldRef))
6286 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
6288 return C.getRValueReferenceType(New);
6292 llvm_unreachable("unknown wrapping kind");
6295 } // end anonymous namespace
6297 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
6298 ParsedAttr &Attr, QualType &Type) {
6299 Sema &S = State.getSema();
6301 ParsedAttr::Kind Kind = Attr.getKind();
6302 QualType Desugared = Type;
6303 const AttributedType *AT = dyn_cast<AttributedType>(Type);
6305 AttributedType::Kind CurAttrKind = AT->getAttrKind();
6307 // You cannot specify duplicate type attributes, so if the attribute has
6308 // already been applied, flag it.
6309 if (getAttrListKind(CurAttrKind) == Kind) {
6310 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
6315 // You cannot have both __sptr and __uptr on the same type, nor can you
6316 // have __ptr32 and __ptr64.
6317 if ((CurAttrKind == AttributedType::attr_ptr32 &&
6318 Kind == ParsedAttr::AT_Ptr64) ||
6319 (CurAttrKind == AttributedType::attr_ptr64 &&
6320 Kind == ParsedAttr::AT_Ptr32)) {
6321 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
6322 << "'__ptr32'" << "'__ptr64'";
6324 } else if ((CurAttrKind == AttributedType::attr_sptr &&
6325 Kind == ParsedAttr::AT_UPtr) ||
6326 (CurAttrKind == AttributedType::attr_uptr &&
6327 Kind == ParsedAttr::AT_SPtr)) {
6328 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
6329 << "'__sptr'" << "'__uptr'";
6333 Desugared = AT->getEquivalentType();
6334 AT = dyn_cast<AttributedType>(Desugared);
6337 // Pointer type qualifiers can only operate on pointer types, but not
6338 // pointer-to-member types.
6339 if (!isa<PointerType>(Desugared)) {
6340 if (Type->isMemberPointerType())
6341 S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers)
6344 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
6345 << Attr.getName() << 0;
6349 AttributedType::Kind TAK;
6351 default: llvm_unreachable("Unknown attribute kind");
6352 case ParsedAttr::AT_Ptr32:
6353 TAK = AttributedType::attr_ptr32;
6355 case ParsedAttr::AT_Ptr64:
6356 TAK = AttributedType::attr_ptr64;
6358 case ParsedAttr::AT_SPtr:
6359 TAK = AttributedType::attr_sptr;
6361 case ParsedAttr::AT_UPtr:
6362 TAK = AttributedType::attr_uptr;
6366 Type = S.Context.getAttributedType(TAK, Type, Type);
6370 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
6371 NullabilityKind nullability,
6372 SourceLocation nullabilityLoc,
6373 bool isContextSensitive,
6374 bool allowOnArrayType) {
6375 recordNullabilitySeen(*this, nullabilityLoc);
6377 // Check for existing nullability attributes on the type.
6378 QualType desugared = type;
6379 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
6380 // Check whether there is already a null
6381 if (auto existingNullability = attributed->getImmediateNullability()) {
6382 // Duplicated nullability.
6383 if (nullability == *existingNullability) {
6384 Diag(nullabilityLoc, diag::warn_nullability_duplicate)
6385 << DiagNullabilityKind(nullability, isContextSensitive)
6386 << FixItHint::CreateRemoval(nullabilityLoc);
6391 // Conflicting nullability.
6392 Diag(nullabilityLoc, diag::err_nullability_conflicting)
6393 << DiagNullabilityKind(nullability, isContextSensitive)
6394 << DiagNullabilityKind(*existingNullability, false);
6398 desugared = attributed->getModifiedType();
6401 // If there is already a different nullability specifier, complain.
6402 // This (unlike the code above) looks through typedefs that might
6403 // have nullability specifiers on them, which means we cannot
6404 // provide a useful Fix-It.
6405 if (auto existingNullability = desugared->getNullability(Context)) {
6406 if (nullability != *existingNullability) {
6407 Diag(nullabilityLoc, diag::err_nullability_conflicting)
6408 << DiagNullabilityKind(nullability, isContextSensitive)
6409 << DiagNullabilityKind(*existingNullability, false);
6411 // Try to find the typedef with the existing nullability specifier.
6412 if (auto typedefType = desugared->getAs<TypedefType>()) {
6413 TypedefNameDecl *typedefDecl = typedefType->getDecl();
6414 QualType underlyingType = typedefDecl->getUnderlyingType();
6415 if (auto typedefNullability
6416 = AttributedType::stripOuterNullability(underlyingType)) {
6417 if (*typedefNullability == *existingNullability) {
6418 Diag(typedefDecl->getLocation(), diag::note_nullability_here)
6419 << DiagNullabilityKind(*existingNullability, false);
6428 // If this definitely isn't a pointer type, reject the specifier.
6429 if (!desugared->canHaveNullability() &&
6430 !(allowOnArrayType && desugared->isArrayType())) {
6431 Diag(nullabilityLoc, diag::err_nullability_nonpointer)
6432 << DiagNullabilityKind(nullability, isContextSensitive) << type;
6436 // For the context-sensitive keywords/Objective-C property
6437 // attributes, require that the type be a single-level pointer.
6438 if (isContextSensitive) {
6439 // Make sure that the pointee isn't itself a pointer type.
6440 const Type *pointeeType;
6441 if (desugared->isArrayType())
6442 pointeeType = desugared->getArrayElementTypeNoTypeQual();
6444 pointeeType = desugared->getPointeeType().getTypePtr();
6446 if (pointeeType->isAnyPointerType() ||
6447 pointeeType->isObjCObjectPointerType() ||
6448 pointeeType->isMemberPointerType()) {
6449 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
6450 << DiagNullabilityKind(nullability, true)
6452 Diag(nullabilityLoc, diag::note_nullability_type_specifier)
6453 << DiagNullabilityKind(nullability, false)
6455 << FixItHint::CreateReplacement(nullabilityLoc,
6456 getNullabilitySpelling(nullability));
6461 // Form the attributed type.
6462 type = Context.getAttributedType(
6463 AttributedType::getNullabilityAttrKind(nullability), type, type);
6467 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
6468 if (isa<ObjCTypeParamType>(type)) {
6469 // Build the attributed type to record where __kindof occurred.
6470 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6475 // Find out if it's an Objective-C object or object pointer type;
6476 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
6477 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
6478 : type->getAs<ObjCObjectType>();
6480 // If not, we can't apply __kindof.
6482 // FIXME: Handle dependent types that aren't yet object types.
6483 Diag(loc, diag::err_objc_kindof_nonobject)
6488 // Rebuild the "equivalent" type, which pushes __kindof down into
6490 // There is no need to apply kindof on an unqualified id type.
6491 QualType equivType = Context.getObjCObjectType(
6492 objType->getBaseType(), objType->getTypeArgsAsWritten(),
6493 objType->getProtocols(),
6494 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
6496 // If we started with an object pointer type, rebuild it.
6498 equivType = Context.getObjCObjectPointerType(equivType);
6499 if (auto nullability = type->getNullability(Context)) {
6500 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
6501 equivType = Context.getAttributedType(attrKind, equivType, equivType);
6505 // Build the attributed type to record where __kindof occurred.
6506 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6513 /// Map a nullability attribute kind to a nullability kind.
6514 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
6516 case ParsedAttr::AT_TypeNonNull:
6517 return NullabilityKind::NonNull;
6519 case ParsedAttr::AT_TypeNullable:
6520 return NullabilityKind::Nullable;
6522 case ParsedAttr::AT_TypeNullUnspecified:
6523 return NullabilityKind::Unspecified;
6526 llvm_unreachable("not a nullability attribute kind");
6530 /// Distribute a nullability type attribute that cannot be applied to
6531 /// the type specifier to a pointer, block pointer, or member pointer
6532 /// declarator, complaining if necessary.
6534 /// \returns true if the nullability annotation was distributed, false
6536 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
6537 QualType type, ParsedAttr &attr) {
6538 Declarator &declarator = state.getDeclarator();
6540 /// Attempt to move the attribute to the specified chunk.
6541 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
6542 // If there is already a nullability attribute there, don't add
6544 if (hasNullabilityAttr(chunk.getAttrs()))
6547 // Complain about the nullability qualifier being in the wrong
6554 PK_MemberFunctionPointer,
6556 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
6558 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
6559 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
6561 auto diag = state.getSema().Diag(attr.getLoc(),
6562 diag::warn_nullability_declspec)
6563 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
6564 attr.isContextSensitiveKeywordAttribute())
6566 << static_cast<unsigned>(pointerKind);
6568 // FIXME: MemberPointer chunks don't carry the location of the *.
6569 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
6570 diag << FixItHint::CreateRemoval(attr.getLoc())
6571 << FixItHint::CreateInsertion(
6572 state.getSema().getPreprocessor()
6573 .getLocForEndOfToken(chunk.Loc),
6574 " " + attr.getName()->getName().str() + " ");
6577 moveAttrFromListToList(attr, state.getCurrentAttributes(),
6582 // Move it to the outermost pointer, member pointer, or block
6583 // pointer declarator.
6584 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
6585 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6586 switch (chunk.Kind) {
6587 case DeclaratorChunk::Pointer:
6588 case DeclaratorChunk::BlockPointer:
6589 case DeclaratorChunk::MemberPointer:
6590 return moveToChunk(chunk, false);
6592 case DeclaratorChunk::Paren:
6593 case DeclaratorChunk::Array:
6596 case DeclaratorChunk::Function:
6597 // Try to move past the return type to a function/block/member
6598 // function pointer.
6599 if (DeclaratorChunk *dest = maybeMovePastReturnType(
6601 /*onlyBlockPointers=*/false)) {
6602 return moveToChunk(*dest, true);
6607 // Don't walk through these.
6608 case DeclaratorChunk::Reference:
6609 case DeclaratorChunk::Pipe:
6617 static AttributedType::Kind getCCTypeAttrKind(ParsedAttr &Attr) {
6618 assert(!Attr.isInvalid());
6619 switch (Attr.getKind()) {
6621 llvm_unreachable("not a calling convention attribute");
6622 case ParsedAttr::AT_CDecl:
6623 return AttributedType::attr_cdecl;
6624 case ParsedAttr::AT_FastCall:
6625 return AttributedType::attr_fastcall;
6626 case ParsedAttr::AT_StdCall:
6627 return AttributedType::attr_stdcall;
6628 case ParsedAttr::AT_ThisCall:
6629 return AttributedType::attr_thiscall;
6630 case ParsedAttr::AT_RegCall:
6631 return AttributedType::attr_regcall;
6632 case ParsedAttr::AT_Pascal:
6633 return AttributedType::attr_pascal;
6634 case ParsedAttr::AT_SwiftCall:
6635 return AttributedType::attr_swiftcall;
6636 case ParsedAttr::AT_VectorCall:
6637 return AttributedType::attr_vectorcall;
6638 case ParsedAttr::AT_Pcs: {
6639 // The attribute may have had a fixit applied where we treated an
6640 // identifier as a string literal. The contents of the string are valid,
6641 // but the form may not be.
6643 if (Attr.isArgExpr(0))
6644 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6646 Str = Attr.getArgAsIdent(0)->Ident->getName();
6647 return llvm::StringSwitch<AttributedType::Kind>(Str)
6648 .Case("aapcs", AttributedType::attr_pcs)
6649 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
6651 case ParsedAttr::AT_IntelOclBicc:
6652 return AttributedType::attr_inteloclbicc;
6653 case ParsedAttr::AT_MSABI:
6654 return AttributedType::attr_ms_abi;
6655 case ParsedAttr::AT_SysVABI:
6656 return AttributedType::attr_sysv_abi;
6657 case ParsedAttr::AT_PreserveMost:
6658 return AttributedType::attr_preserve_most;
6659 case ParsedAttr::AT_PreserveAll:
6660 return AttributedType::attr_preserve_all;
6662 llvm_unreachable("unexpected attribute kind!");
6665 /// Process an individual function attribute. Returns true to
6666 /// indicate that the attribute was handled, false if it wasn't.
6667 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6669 Sema &S = state.getSema();
6671 FunctionTypeUnwrapper unwrapped(S, type);
6673 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
6674 if (S.CheckAttrNoArgs(attr))
6677 // Delay if this is not a function type.
6678 if (!unwrapped.isFunctionType())
6681 // Otherwise we can process right away.
6682 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6683 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6687 // ns_returns_retained is not always a type attribute, but if we got
6688 // here, we're treating it as one right now.
6689 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
6690 if (attr.getNumArgs()) return true;
6692 // Delay if this is not a function type.
6693 if (!unwrapped.isFunctionType())
6696 // Check whether the return type is reasonable.
6697 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
6698 unwrapped.get()->getReturnType()))
6701 // Only actually change the underlying type in ARC builds.
6702 QualType origType = type;
6703 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
6704 FunctionType::ExtInfo EI
6705 = unwrapped.get()->getExtInfo().withProducesResult(true);
6706 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6708 type = S.Context.getAttributedType(AttributedType::attr_ns_returns_retained,
6713 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
6714 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
6717 // Delay if this is not a function type.
6718 if (!unwrapped.isFunctionType())
6721 FunctionType::ExtInfo EI =
6722 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
6723 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6727 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
6728 if (!S.getLangOpts().CFProtectionBranch) {
6729 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
6734 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
6737 // If this is not a function type, warning will be asserted by subject
6739 if (!unwrapped.isFunctionType())
6742 FunctionType::ExtInfo EI =
6743 unwrapped.get()->getExtInfo().withNoCfCheck(true);
6744 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6748 if (attr.getKind() == ParsedAttr::AT_Regparm) {
6750 if (S.CheckRegparmAttr(attr, value))
6753 // Delay if this is not a function type.
6754 if (!unwrapped.isFunctionType())
6757 // Diagnose regparm with fastcall.
6758 const FunctionType *fn = unwrapped.get();
6759 CallingConv CC = fn->getCallConv();
6760 if (CC == CC_X86FastCall) {
6761 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6762 << FunctionType::getNameForCallConv(CC)
6768 FunctionType::ExtInfo EI =
6769 unwrapped.get()->getExtInfo().withRegParm(value);
6770 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6774 // Delay if the type didn't work out to a function.
6775 if (!unwrapped.isFunctionType()) return false;
6777 // Otherwise, a calling convention.
6779 if (S.CheckCallingConvAttr(attr, CC))
6782 const FunctionType *fn = unwrapped.get();
6783 CallingConv CCOld = fn->getCallConv();
6784 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
6787 // Error out on when there's already an attribute on the type
6788 // and the CCs don't match.
6789 const AttributedType *AT = S.getCallingConvAttributedType(type);
6790 if (AT && AT->getAttrKind() != CCAttrKind) {
6791 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6792 << FunctionType::getNameForCallConv(CC)
6793 << FunctionType::getNameForCallConv(CCOld);
6799 // Diagnose use of variadic functions with calling conventions that
6800 // don't support them (e.g. because they're callee-cleanup).
6801 // We delay warning about this on unprototyped function declarations
6802 // until after redeclaration checking, just in case we pick up a
6803 // prototype that way. And apparently we also "delay" warning about
6804 // unprototyped function types in general, despite not necessarily having
6805 // much ability to diagnose it later.
6806 if (!supportsVariadicCall(CC)) {
6807 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6808 if (FnP && FnP->isVariadic()) {
6809 unsigned DiagID = diag::err_cconv_varargs;
6811 // stdcall and fastcall are ignored with a warning for GCC and MS
6813 bool IsInvalid = true;
6814 if (CC == CC_X86StdCall || CC == CC_X86FastCall) {
6815 DiagID = diag::warn_cconv_varargs;
6819 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
6820 if (IsInvalid) attr.setInvalid();
6825 // Also diagnose fastcall with regparm.
6826 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
6827 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6828 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
6833 // Modify the CC from the wrapped function type, wrap it all back, and then
6834 // wrap the whole thing in an AttributedType as written. The modified type
6835 // might have a different CC if we ignored the attribute.
6836 QualType Equivalent;
6840 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
6842 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6844 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
6848 bool Sema::hasExplicitCallingConv(QualType &T) {
6849 QualType R = T.IgnoreParens();
6850 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
6851 if (AT->isCallingConv())
6853 R = AT->getModifiedType().IgnoreParens();
6858 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
6859 SourceLocation Loc) {
6860 FunctionTypeUnwrapper Unwrapped(*this, T);
6861 const FunctionType *FT = Unwrapped.get();
6862 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
6863 cast<FunctionProtoType>(FT)->isVariadic());
6864 CallingConv CurCC = FT->getCallConv();
6865 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
6870 // MS compiler ignores explicit calling convention attributes on structors. We
6871 // should do the same.
6872 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
6873 // Issue a warning on ignored calling convention -- except of __stdcall.
6874 // Again, this is what MS compiler does.
6875 if (CurCC != CC_X86StdCall)
6876 Diag(Loc, diag::warn_cconv_structors)
6877 << FunctionType::getNameForCallConv(CurCC);
6878 // Default adjustment.
6880 // Only adjust types with the default convention. For example, on Windows
6881 // we should adjust a __cdecl type to __thiscall for instance methods, and a
6882 // __thiscall type to __cdecl for static methods.
6883 CallingConv DefaultCC =
6884 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6886 if (CurCC != DefaultCC || DefaultCC == ToCC)
6889 if (hasExplicitCallingConv(T))
6893 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6894 QualType Wrapped = Unwrapped.wrap(*this, FT);
6895 T = Context.getAdjustedType(T, Wrapped);
6898 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6899 /// and float scalars, although arrays, pointers, and function return values are
6900 /// allowed in conjunction with this construct. Aggregates with this attribute
6901 /// are invalid, even if they are of the same size as a corresponding scalar.
6902 /// The raw attribute should contain precisely 1 argument, the vector size for
6903 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6904 /// this routine will return a new vector type.
6905 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
6907 // Check the attribute arguments.
6908 if (Attr.getNumArgs() != 1) {
6909 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6910 << Attr.getName() << 1;
6916 // Special case where the argument is a template id.
6917 if (Attr.isArgIdent(0)) {
6919 SourceLocation TemplateKWLoc;
6921 Id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6923 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6926 if (Size.isInvalid())
6928 SizeExpr = Size.get();
6930 SizeExpr = Attr.getArgAsExpr(0);
6933 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
6940 /// Process the OpenCL-like ext_vector_type attribute when it occurs on
6942 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
6944 // check the attribute arguments.
6945 if (Attr.getNumArgs() != 1) {
6946 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6947 << Attr.getName() << 1;
6953 // Special case where the argument is a template id.
6954 if (Attr.isArgIdent(0)) {
6956 SourceLocation TemplateKWLoc;
6958 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6960 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6962 if (Size.isInvalid())
6965 sizeExpr = Size.get();
6967 sizeExpr = Attr.getArgAsExpr(0);
6970 // Create the vector type.
6971 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6976 static bool isPermittedNeonBaseType(QualType &Ty,
6977 VectorType::VectorKind VecKind, Sema &S) {
6978 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6982 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6984 // Signed poly is mathematically wrong, but has been baked into some ABIs by
6986 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6987 Triple.getArch() == llvm::Triple::aarch64_be;
6988 if (VecKind == VectorType::NeonPolyVector) {
6989 if (IsPolyUnsigned) {
6990 // AArch64 polynomial vectors are unsigned and support poly64.
6991 return BTy->getKind() == BuiltinType::UChar ||
6992 BTy->getKind() == BuiltinType::UShort ||
6993 BTy->getKind() == BuiltinType::ULong ||
6994 BTy->getKind() == BuiltinType::ULongLong;
6996 // AArch32 polynomial vector are signed.
6997 return BTy->getKind() == BuiltinType::SChar ||
6998 BTy->getKind() == BuiltinType::Short;
7002 // Non-polynomial vector types: the usual suspects are allowed, as well as
7003 // float64_t on AArch64.
7004 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
7005 Triple.getArch() == llvm::Triple::aarch64_be;
7007 if (Is64Bit && BTy->getKind() == BuiltinType::Double)
7010 return BTy->getKind() == BuiltinType::SChar ||
7011 BTy->getKind() == BuiltinType::UChar ||
7012 BTy->getKind() == BuiltinType::Short ||
7013 BTy->getKind() == BuiltinType::UShort ||
7014 BTy->getKind() == BuiltinType::Int ||
7015 BTy->getKind() == BuiltinType::UInt ||
7016 BTy->getKind() == BuiltinType::Long ||
7017 BTy->getKind() == BuiltinType::ULong ||
7018 BTy->getKind() == BuiltinType::LongLong ||
7019 BTy->getKind() == BuiltinType::ULongLong ||
7020 BTy->getKind() == BuiltinType::Float ||
7021 BTy->getKind() == BuiltinType::Half;
7024 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
7025 /// "neon_polyvector_type" attributes are used to create vector types that
7026 /// are mangled according to ARM's ABI. Otherwise, these types are identical
7027 /// to those created with the "vector_size" attribute. Unlike "vector_size"
7028 /// the argument to these Neon attributes is the number of vector elements,
7029 /// not the vector size in bytes. The vector width and element type must
7030 /// match one of the standard Neon vector types.
7031 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7032 Sema &S, VectorType::VectorKind VecKind) {
7033 // Target must have NEON
7034 if (!S.Context.getTargetInfo().hasFeature("neon")) {
7035 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
7039 // Check the attribute arguments.
7040 if (Attr.getNumArgs() != 1) {
7041 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
7042 << Attr.getName() << 1;
7046 // The number of elements must be an ICE.
7047 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
7048 llvm::APSInt numEltsInt(32);
7049 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
7050 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
7051 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
7052 << Attr.getName() << AANT_ArgumentIntegerConstant
7053 << numEltsExpr->getSourceRange();
7057 // Only certain element types are supported for Neon vectors.
7058 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
7059 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
7064 // The total size of the vector must be 64 or 128 bits.
7065 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
7066 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
7067 unsigned vecSize = typeSize * numElts;
7068 if (vecSize != 64 && vecSize != 128) {
7069 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
7074 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
7077 /// Handle OpenCL Access Qualifier Attribute.
7078 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
7080 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
7081 if (!(CurType->isImageType() || CurType->isPipeType())) {
7082 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
7087 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
7088 QualType PointeeTy = TypedefTy->desugar();
7089 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
7091 std::string PrevAccessQual;
7092 switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) {
7093 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7094 case BuiltinType::Id: \
7095 PrevAccessQual = #Access; \
7097 #include "clang/Basic/OpenCLImageTypes.def"
7099 assert(0 && "Unable to find corresponding image type.");
7102 S.Diag(TypedefTy->getDecl()->getLocStart(),
7103 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
7104 } else if (CurType->isPipeType()) {
7105 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
7106 QualType ElemType = CurType->getAs<PipeType>()->getElementType();
7107 CurType = S.Context.getWritePipeType(ElemType);
7112 static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State,
7113 QualType &T, TypeAttrLocation TAL) {
7114 Declarator &D = State.getDeclarator();
7116 // Handle the cases where address space should not be deduced.
7118 // The pointee type of a pointer type is always deduced since a pointer always
7119 // points to some memory location which should has an address space.
7121 // There are situations that at the point of certain declarations, the address
7122 // space may be unknown and better to be left as default. For example, when
7123 // defining a typedef or struct type, they are not associated with any
7124 // specific address space. Later on, they may be used with any address space
7125 // to declare a variable.
7127 // The return value of a function is r-value, therefore should not have
7130 // The void type does not occupy memory, therefore should not have address
7131 // space, except when it is used as a pointee type.
7133 // Since LLVM assumes function type is in default address space, it should not
7134 // have address space.
7135 auto ChunkIndex = State.getCurrentChunkIndex();
7138 (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer ||
7139 D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer);
7140 bool IsFuncReturnType =
7142 D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function;
7144 ChunkIndex < D.getNumTypeObjects() &&
7145 D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function;
7146 if ( // Do not deduce addr space for function return type and function type,
7147 // otherwise it will fail some sema check.
7148 IsFuncReturnType || IsFuncType ||
7149 // Do not deduce addr space for member types of struct, except the pointee
7150 // type of a pointer member type.
7151 (D.getContext() == DeclaratorContext::MemberContext && !IsPointee) ||
7152 // Do not deduce addr space for types used to define a typedef and the
7153 // typedef itself, except the pointee type of a pointer type which is used
7154 // to define the typedef.
7155 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef &&
7157 // Do not deduce addr space of the void type, e.g. in f(void), otherwise
7158 // it will fail some sema check.
7159 (T->isVoidType() && !IsPointee))
7163 // Put OpenCL automatic variable in private address space.
7164 // OpenCL v1.2 s6.5:
7165 // The default address space name for arguments to a function in a
7166 // program, or local variables of a function is __private. All function
7167 // arguments shall be in the __private address space.
7168 if (State.getSema().getLangOpts().OpenCLVersion <= 120 &&
7169 !State.getSema().getLangOpts().OpenCLCPlusPlus) {
7170 ImpAddr = LangAS::opencl_private;
7172 // If address space is not set, OpenCL 2.0 defines non private default
7173 // address spaces for some cases:
7174 // OpenCL 2.0, section 6.5:
7175 // The address space for a variable at program scope or a static variable
7176 // inside a function can either be __global or __constant, but defaults to
7177 // __global if not specified.
7179 // Pointers that are declared without pointing to a named address space
7180 // point to the generic address space.
7182 ImpAddr = LangAS::opencl_generic;
7184 if (D.getContext() == DeclaratorContext::FileContext) {
7185 ImpAddr = LangAS::opencl_global;
7187 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
7188 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) {
7189 ImpAddr = LangAS::opencl_global;
7191 ImpAddr = LangAS::opencl_private;
7196 T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr);
7199 static void HandleLifetimeBoundAttr(QualType &CurType,
7200 const ParsedAttr &Attr,
7201 Sema &S, Declarator &D) {
7202 if (D.isDeclarationOfFunction()) {
7203 CurType = S.Context.getAttributedType(AttributedType::attr_lifetimebound,
7206 Attr.diagnoseAppertainsTo(S, nullptr);
7211 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
7212 TypeAttrLocation TAL,
7213 ParsedAttributesView &attrs) {
7214 // Scan through and apply attributes to this type where it makes sense. Some
7215 // attributes (such as __address_space__, __vector_size__, etc) apply to the
7216 // type, but others can be present in the type specifiers even though they
7217 // apply to the decl. Here we apply type attributes and ignore the rest.
7219 // This loop modifies the list pretty frequently, but we still need to make
7220 // sure we visit every element once. Copy the attributes list, and iterate
7222 ParsedAttributesView AttrsCopy{attrs};
7223 for (ParsedAttr &attr : AttrsCopy) {
7225 // Skip attributes that were marked to be invalid.
7226 if (attr.isInvalid())
7229 if (attr.isCXX11Attribute()) {
7230 // [[gnu::...]] attributes are treated as declaration attributes, so may
7231 // not appertain to a DeclaratorChunk. If we handle them as type
7232 // attributes, accept them in that position and diagnose the GCC
7234 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
7235 bool IsTypeAttr = attr.isTypeAttr();
7236 if (TAL == TAL_DeclChunk) {
7237 state.getSema().Diag(attr.getLoc(),
7239 ? diag::warn_gcc_ignores_type_attr
7240 : diag::warn_cxx11_gnu_attribute_on_type)
7245 } else if (TAL != TAL_DeclChunk) {
7246 // Otherwise, only consider type processing for a C++11 attribute if
7247 // it's actually been applied to a type.
7252 // If this is an attribute we can handle, do so now,
7253 // otherwise, add it to the FnAttrs list for rechaining.
7254 switch (attr.getKind()) {
7256 // A C++11 attribute on a declarator chunk must appertain to a type.
7257 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
7258 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
7260 attr.setUsedAsTypeAttr();
7264 case ParsedAttr::UnknownAttribute:
7265 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
7266 state.getSema().Diag(attr.getLoc(),
7267 diag::warn_unknown_attribute_ignored)
7271 case ParsedAttr::IgnoredAttribute:
7274 case ParsedAttr::AT_MayAlias:
7275 // FIXME: This attribute needs to actually be handled, but if we ignore
7276 // it it breaks large amounts of Linux software.
7277 attr.setUsedAsTypeAttr();
7279 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
7280 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
7281 case ParsedAttr::AT_OpenCLLocalAddressSpace:
7282 case ParsedAttr::AT_OpenCLConstantAddressSpace:
7283 case ParsedAttr::AT_OpenCLGenericAddressSpace:
7284 case ParsedAttr::AT_AddressSpace:
7285 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
7286 attr.setUsedAsTypeAttr();
7288 OBJC_POINTER_TYPE_ATTRS_CASELIST:
7289 if (!handleObjCPointerTypeAttr(state, attr, type))
7290 distributeObjCPointerTypeAttr(state, attr, type);
7291 attr.setUsedAsTypeAttr();
7293 case ParsedAttr::AT_VectorSize:
7294 HandleVectorSizeAttr(type, attr, state.getSema());
7295 attr.setUsedAsTypeAttr();
7297 case ParsedAttr::AT_ExtVectorType:
7298 HandleExtVectorTypeAttr(type, attr, state.getSema());
7299 attr.setUsedAsTypeAttr();
7301 case ParsedAttr::AT_NeonVectorType:
7302 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
7303 VectorType::NeonVector);
7304 attr.setUsedAsTypeAttr();
7306 case ParsedAttr::AT_NeonPolyVectorType:
7307 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
7308 VectorType::NeonPolyVector);
7309 attr.setUsedAsTypeAttr();
7311 case ParsedAttr::AT_OpenCLAccess:
7312 HandleOpenCLAccessAttr(type, attr, state.getSema());
7313 attr.setUsedAsTypeAttr();
7315 case ParsedAttr::AT_LifetimeBound:
7316 if (TAL == TAL_DeclChunk) {
7317 HandleLifetimeBoundAttr(type, attr, state.getSema(),
7318 state.getDeclarator());
7319 attr.setUsedAsTypeAttr();
7323 MS_TYPE_ATTRS_CASELIST:
7324 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
7325 attr.setUsedAsTypeAttr();
7329 NULLABILITY_TYPE_ATTRS_CASELIST:
7330 // Either add nullability here or try to distribute it. We
7331 // don't want to distribute the nullability specifier past any
7332 // dependent type, because that complicates the user model.
7333 if (type->canHaveNullability() || type->isDependentType() ||
7334 type->isArrayType() ||
7335 !distributeNullabilityTypeAttr(state, type, attr)) {
7337 if (TAL == TAL_DeclChunk)
7338 endIndex = state.getCurrentChunkIndex();
7340 endIndex = state.getDeclarator().getNumTypeObjects();
7341 bool allowOnArrayType =
7342 state.getDeclarator().isPrototypeContext() &&
7343 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
7344 if (state.getSema().checkNullabilityTypeSpecifier(
7346 mapNullabilityAttrKind(attr.getKind()),
7348 attr.isContextSensitiveKeywordAttribute(),
7349 allowOnArrayType)) {
7353 attr.setUsedAsTypeAttr();
7357 case ParsedAttr::AT_ObjCKindOf:
7358 // '__kindof' must be part of the decl-specifiers.
7365 state.getSema().Diag(attr.getLoc(),
7366 diag::err_objc_kindof_wrong_position)
7367 << FixItHint::CreateRemoval(attr.getLoc())
7368 << FixItHint::CreateInsertion(
7369 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
7373 // Apply it regardless.
7374 if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
7376 attr.setUsedAsTypeAttr();
7379 FUNCTION_TYPE_ATTRS_CASELIST:
7380 attr.setUsedAsTypeAttr();
7382 // Never process function type attributes as part of the
7383 // declaration-specifiers.
7384 if (TAL == TAL_DeclSpec)
7385 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
7387 // Otherwise, handle the possible delays.
7388 else if (!handleFunctionTypeAttr(state, attr, type))
7389 distributeFunctionTypeAttr(state, attr, type);
7394 if (!state.getSema().getLangOpts().OpenCL ||
7395 type.getAddressSpace() != LangAS::Default)
7398 deduceOpenCLImplicitAddrSpace(state, type, TAL);
7401 void Sema::completeExprArrayBound(Expr *E) {
7402 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7403 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7404 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
7405 auto *Def = Var->getDefinition();
7407 SourceLocation PointOfInstantiation = E->getExprLoc();
7408 InstantiateVariableDefinition(PointOfInstantiation, Var);
7409 Def = Var->getDefinition();
7411 // If we don't already have a point of instantiation, and we managed
7412 // to instantiate a definition, this is the point of instantiation.
7413 // Otherwise, we don't request an end-of-TU instantiation, so this is
7414 // not a point of instantiation.
7415 // FIXME: Is this really the right behavior?
7416 if (Var->getPointOfInstantiation().isInvalid() && Def) {
7417 assert(Var->getTemplateSpecializationKind() ==
7418 TSK_ImplicitInstantiation &&
7419 "explicit instantiation with no point of instantiation");
7420 Var->setTemplateSpecializationKind(
7421 Var->getTemplateSpecializationKind(), PointOfInstantiation);
7425 // Update the type to the definition's type both here and within the
7429 QualType T = Def->getType();
7431 // FIXME: Update the type on all intervening expressions.
7435 // We still go on to try to complete the type independently, as it
7436 // may also require instantiations or diagnostics if it remains
7443 /// Ensure that the type of the given expression is complete.
7445 /// This routine checks whether the expression \p E has a complete type. If the
7446 /// expression refers to an instantiable construct, that instantiation is
7447 /// performed as needed to complete its type. Furthermore
7448 /// Sema::RequireCompleteType is called for the expression's type (or in the
7449 /// case of a reference type, the referred-to type).
7451 /// \param E The expression whose type is required to be complete.
7452 /// \param Diagnoser The object that will emit a diagnostic if the type is
7455 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
7457 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
7458 QualType T = E->getType();
7460 // Incomplete array types may be completed by the initializer attached to
7461 // their definitions. For static data members of class templates and for
7462 // variable templates, we need to instantiate the definition to get this
7463 // initializer and complete the type.
7464 if (T->isIncompleteArrayType()) {
7465 completeExprArrayBound(E);
7469 // FIXME: Are there other cases which require instantiating something other
7470 // than the type to complete the type of an expression?
7472 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
7475 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
7476 BoundTypeDiagnoser<> Diagnoser(DiagID);
7477 return RequireCompleteExprType(E, Diagnoser);
7480 /// Ensure that the type T is a complete type.
7482 /// This routine checks whether the type @p T is complete in any
7483 /// context where a complete type is required. If @p T is a complete
7484 /// type, returns false. If @p T is a class template specialization,
7485 /// this routine then attempts to perform class template
7486 /// instantiation. If instantiation fails, or if @p T is incomplete
7487 /// and cannot be completed, issues the diagnostic @p diag (giving it
7488 /// the type @p T) and returns true.
7490 /// @param Loc The location in the source that the incomplete type
7491 /// diagnostic should refer to.
7493 /// @param T The type that this routine is examining for completeness.
7495 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
7496 /// @c false otherwise.
7497 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7498 TypeDiagnoser &Diagnoser) {
7499 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
7501 if (const TagType *Tag = T->getAs<TagType>()) {
7502 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
7503 Tag->getDecl()->setCompleteDefinitionRequired();
7504 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
7510 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
7511 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
7515 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
7516 // and isolate from other C++ specific checks.
7517 StructuralEquivalenceContext Ctx(
7518 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
7519 StructuralEquivalenceKind::Default,
7520 false /*StrictTypeSpelling*/, true /*Complain*/,
7521 true /*ErrorOnTagTypeMismatch*/);
7522 return Ctx.IsEquivalent(D, Suggested);
7525 /// Determine whether there is any declaration of \p D that was ever a
7526 /// definition (perhaps before module merging) and is currently visible.
7527 /// \param D The definition of the entity.
7528 /// \param Suggested Filled in with the declaration that should be made visible
7529 /// in order to provide a definition of this entity.
7530 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
7531 /// not defined. This only matters for enums with a fixed underlying
7532 /// type, since in all other cases, a type is complete if and only if it
7534 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
7535 bool OnlyNeedComplete) {
7536 // Easy case: if we don't have modules, all declarations are visible.
7537 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
7540 // If this definition was instantiated from a template, map back to the
7541 // pattern from which it was instantiated.
7542 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
7543 // We're in the middle of defining it; this definition should be treated
7546 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
7547 if (auto *Pattern = RD->getTemplateInstantiationPattern())
7549 D = RD->getDefinition();
7550 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
7551 if (auto *Pattern = ED->getTemplateInstantiationPattern())
7553 if (OnlyNeedComplete && ED->isFixed()) {
7554 // If the enum has a fixed underlying type, and we're only looking for a
7555 // complete type (not a definition), any visible declaration of it will
7557 *Suggested = nullptr;
7558 for (auto *Redecl : ED->redecls()) {
7559 if (isVisible(Redecl))
7561 if (Redecl->isThisDeclarationADefinition() ||
7562 (Redecl->isCanonicalDecl() && !*Suggested))
7563 *Suggested = Redecl;
7567 D = ED->getDefinition();
7568 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7569 if (auto *Pattern = FD->getTemplateInstantiationPattern())
7571 D = FD->getDefinition();
7572 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
7573 if (auto *Pattern = VD->getTemplateInstantiationPattern())
7575 D = VD->getDefinition();
7577 assert(D && "missing definition for pattern of instantiated definition");
7583 // The external source may have additional definitions of this entity that are
7584 // visible, so complete the redeclaration chain now and ask again.
7585 if (auto *Source = Context.getExternalSource()) {
7586 Source->CompleteRedeclChain(D);
7587 return isVisible(D);
7593 /// Locks in the inheritance model for the given class and all of its bases.
7594 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
7595 RD = RD->getMostRecentNonInjectedDecl();
7596 if (!RD->hasAttr<MSInheritanceAttr>()) {
7597 MSInheritanceAttr::Spelling IM;
7599 switch (S.MSPointerToMemberRepresentationMethod) {
7600 case LangOptions::PPTMK_BestCase:
7601 IM = RD->calculateInheritanceModel();
7603 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
7604 IM = MSInheritanceAttr::Keyword_single_inheritance;
7606 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
7607 IM = MSInheritanceAttr::Keyword_multiple_inheritance;
7609 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
7610 IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
7614 RD->addAttr(MSInheritanceAttr::CreateImplicit(
7615 S.getASTContext(), IM,
7616 /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
7617 LangOptions::PPTMK_BestCase,
7618 S.ImplicitMSInheritanceAttrLoc.isValid()
7619 ? S.ImplicitMSInheritanceAttrLoc
7620 : RD->getSourceRange()));
7621 S.Consumer.AssignInheritanceModel(RD);
7625 /// The implementation of RequireCompleteType
7626 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
7627 TypeDiagnoser *Diagnoser) {
7628 // FIXME: Add this assertion to make sure we always get instantiation points.
7629 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
7630 // FIXME: Add this assertion to help us flush out problems with
7631 // checking for dependent types and type-dependent expressions.
7633 // assert(!T->isDependentType() &&
7634 // "Can't ask whether a dependent type is complete");
7636 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
7637 if (!MPTy->getClass()->isDependentType()) {
7638 if (getLangOpts().CompleteMemberPointers &&
7639 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
7640 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0),
7641 diag::err_memptr_incomplete))
7644 // We lock in the inheritance model once somebody has asked us to ensure
7645 // that a pointer-to-member type is complete.
7646 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7647 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
7648 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
7653 NamedDecl *Def = nullptr;
7654 bool Incomplete = T->isIncompleteType(&Def);
7656 // Check that any necessary explicit specializations are visible. For an
7657 // enum, we just need the declaration, so don't check this.
7658 if (Def && !isa<EnumDecl>(Def))
7659 checkSpecializationVisibility(Loc, Def);
7661 // If we have a complete type, we're done.
7663 // If we know about the definition but it is not visible, complain.
7664 NamedDecl *SuggestedDef = nullptr;
7666 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
7667 // If the user is going to see an error here, recover by making the
7668 // definition visible.
7669 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
7670 if (Diagnoser && SuggestedDef)
7671 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
7672 /*Recover*/TreatAsComplete);
7673 return !TreatAsComplete;
7674 } else if (Def && !TemplateInstCallbacks.empty()) {
7675 CodeSynthesisContext TempInst;
7676 TempInst.Kind = CodeSynthesisContext::Memoization;
7677 TempInst.Template = Def;
7678 TempInst.Entity = Def;
7679 TempInst.PointOfInstantiation = Loc;
7680 atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
7681 atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
7687 const TagType *Tag = T->getAs<TagType>();
7688 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
7690 // If there's an unimported definition of this type in a module (for
7691 // instance, because we forward declared it, then imported the definition),
7692 // import that definition now.
7694 // FIXME: What about other cases where an import extends a redeclaration
7695 // chain for a declaration that can be accessed through a mechanism other
7696 // than name lookup (eg, referenced in a template, or a variable whose type
7697 // could be completed by the module)?
7699 // FIXME: Should we map through to the base array element type before
7700 // checking for a tag type?
7703 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
7705 // Avoid diagnosing invalid decls as incomplete.
7706 if (D->isInvalidDecl())
7709 // Give the external AST source a chance to complete the type.
7710 if (auto *Source = Context.getExternalSource()) {
7712 TagDecl *TagD = Tag->getDecl();
7713 if (TagD->hasExternalLexicalStorage())
7714 Source->CompleteType(TagD);
7716 ObjCInterfaceDecl *IFaceD = IFace->getDecl();
7717 if (IFaceD->hasExternalLexicalStorage())
7718 Source->CompleteType(IFace->getDecl());
7720 // If the external source completed the type, go through the motions
7721 // again to ensure we're allowed to use the completed type.
7722 if (!T->isIncompleteType())
7723 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7727 // If we have a class template specialization or a class member of a
7728 // class template specialization, or an array with known size of such,
7729 // try to instantiate it.
7730 QualType MaybeTemplate = T;
7731 while (const ConstantArrayType *Array
7732 = Context.getAsConstantArrayType(MaybeTemplate))
7733 MaybeTemplate = Array->getElementType();
7734 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
7735 bool Instantiated = false;
7736 bool Diagnosed = false;
7737 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
7738 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
7739 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
7740 Diagnosed = InstantiateClassTemplateSpecialization(
7741 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
7742 /*Complain=*/Diagnoser);
7743 Instantiated = true;
7745 } else if (CXXRecordDecl *Rec
7746 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
7747 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
7748 if (!Rec->isBeingDefined() && Pattern) {
7749 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
7750 assert(MSI && "Missing member specialization information?");
7751 // This record was instantiated from a class within a template.
7752 if (MSI->getTemplateSpecializationKind() !=
7753 TSK_ExplicitSpecialization) {
7754 Diagnosed = InstantiateClass(Loc, Rec, Pattern,
7755 getTemplateInstantiationArgs(Rec),
7756 TSK_ImplicitInstantiation,
7757 /*Complain=*/Diagnoser);
7758 Instantiated = true;
7764 // Instantiate* might have already complained that the template is not
7765 // defined, if we asked it to.
7766 if (Diagnoser && Diagnosed)
7768 // If we instantiated a definition, check that it's usable, even if
7769 // instantiation produced an error, so that repeated calls to this
7770 // function give consistent answers.
7771 if (!T->isIncompleteType())
7772 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7776 // FIXME: If we didn't instantiate a definition because of an explicit
7777 // specialization declaration, check that it's visible.
7782 Diagnoser->diagnose(*this, Loc, T);
7784 // If the type was a forward declaration of a class/struct/union
7785 // type, produce a note.
7786 if (Tag && !Tag->getDecl()->isInvalidDecl())
7787 Diag(Tag->getDecl()->getLocation(),
7788 Tag->isBeingDefined() ? diag::note_type_being_defined
7789 : diag::note_forward_declaration)
7790 << QualType(Tag, 0);
7792 // If the Objective-C class was a forward declaration, produce a note.
7793 if (IFace && !IFace->getDecl()->isInvalidDecl())
7794 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
7796 // If we have external information that we can use to suggest a fix,
7799 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
7804 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7806 BoundTypeDiagnoser<> Diagnoser(DiagID);
7807 return RequireCompleteType(Loc, T, Diagnoser);
7810 /// Get diagnostic %select index for tag kind for
7811 /// literal type diagnostic message.
7812 /// WARNING: Indexes apply to particular diagnostics only!
7814 /// \returns diagnostic %select index.
7815 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
7817 case TTK_Struct: return 0;
7818 case TTK_Interface: return 1;
7819 case TTK_Class: return 2;
7820 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
7824 /// Ensure that the type T is a literal type.
7826 /// This routine checks whether the type @p T is a literal type. If @p T is an
7827 /// incomplete type, an attempt is made to complete it. If @p T is a literal
7828 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
7829 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
7830 /// it the type @p T), along with notes explaining why the type is not a
7831 /// literal type, and returns true.
7833 /// @param Loc The location in the source that the non-literal type
7834 /// diagnostic should refer to.
7836 /// @param T The type that this routine is examining for literalness.
7838 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
7840 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
7841 /// @c false otherwise.
7842 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
7843 TypeDiagnoser &Diagnoser) {
7844 assert(!T->isDependentType() && "type should not be dependent");
7846 QualType ElemType = Context.getBaseElementType(T);
7847 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
7848 T->isLiteralType(Context))
7851 Diagnoser.diagnose(*this, Loc, T);
7853 if (T->isVariableArrayType())
7856 const RecordType *RT = ElemType->getAs<RecordType>();
7860 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7862 // A partially-defined class type can't be a literal type, because a literal
7863 // class type must have a trivial destructor (which can't be checked until
7864 // the class definition is complete).
7865 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
7868 // [expr.prim.lambda]p3:
7869 // This class type is [not] a literal type.
7870 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
7871 Diag(RD->getLocation(), diag::note_non_literal_lambda);
7875 // If the class has virtual base classes, then it's not an aggregate, and
7876 // cannot have any constexpr constructors or a trivial default constructor,
7877 // so is non-literal. This is better to diagnose than the resulting absence
7878 // of constexpr constructors.
7879 if (RD->getNumVBases()) {
7880 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
7881 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
7882 for (const auto &I : RD->vbases())
7883 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
7884 << I.getSourceRange();
7885 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
7886 !RD->hasTrivialDefaultConstructor()) {
7887 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
7888 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
7889 for (const auto &I : RD->bases()) {
7890 if (!I.getType()->isLiteralType(Context)) {
7891 Diag(I.getLocStart(),
7892 diag::note_non_literal_base_class)
7893 << RD << I.getType() << I.getSourceRange();
7897 for (const auto *I : RD->fields()) {
7898 if (!I->getType()->isLiteralType(Context) ||
7899 I->getType().isVolatileQualified()) {
7900 Diag(I->getLocation(), diag::note_non_literal_field)
7901 << RD << I << I->getType()
7902 << I->getType().isVolatileQualified();
7906 } else if (!RD->hasTrivialDestructor()) {
7907 // All fields and bases are of literal types, so have trivial destructors.
7908 // If this class's destructor is non-trivial it must be user-declared.
7909 CXXDestructorDecl *Dtor = RD->getDestructor();
7910 assert(Dtor && "class has literal fields and bases but no dtor?");
7914 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
7915 diag::note_non_literal_user_provided_dtor :
7916 diag::note_non_literal_nontrivial_dtor) << RD;
7917 if (!Dtor->isUserProvided())
7918 SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
7925 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
7926 BoundTypeDiagnoser<> Diagnoser(DiagID);
7927 return RequireLiteralType(Loc, T, Diagnoser);
7930 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
7931 /// by the nested-name-specifier contained in SS, and that is (re)declared by
7932 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
7933 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
7934 const CXXScopeSpec &SS, QualType T,
7935 TagDecl *OwnedTagDecl) {
7938 NestedNameSpecifier *NNS;
7940 NNS = SS.getScopeRep();
7942 if (Keyword == ETK_None)
7946 return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl);
7949 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
7950 ExprResult ER = CheckPlaceholderExpr(E);
7951 if (ER.isInvalid()) return QualType();
7954 if (!getLangOpts().CPlusPlus && E->refersToBitField())
7955 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
7957 if (!E->isTypeDependent()) {
7958 QualType T = E->getType();
7959 if (const TagType *TT = T->getAs<TagType>())
7960 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
7962 return Context.getTypeOfExprType(E);
7965 /// getDecltypeForExpr - Given an expr, will return the decltype for
7966 /// that expression, according to the rules in C++11
7967 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
7968 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
7969 if (E->isTypeDependent())
7970 return S.Context.DependentTy;
7972 // C++11 [dcl.type.simple]p4:
7973 // The type denoted by decltype(e) is defined as follows:
7975 // - if e is an unparenthesized id-expression or an unparenthesized class
7976 // member access (5.2.5), decltype(e) is the type of the entity named
7977 // by e. If there is no such entity, or if e names a set of overloaded
7978 // functions, the program is ill-formed;
7980 // We apply the same rules for Objective-C ivar and property references.
7981 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7982 const ValueDecl *VD = DRE->getDecl();
7983 return VD->getType();
7984 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7985 if (const ValueDecl *VD = ME->getMemberDecl())
7986 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
7987 return VD->getType();
7988 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
7989 return IR->getDecl()->getType();
7990 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
7991 if (PR->isExplicitProperty())
7992 return PR->getExplicitProperty()->getType();
7993 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
7994 return PE->getType();
7997 // C++11 [expr.lambda.prim]p18:
7998 // Every occurrence of decltype((x)) where x is a possibly
7999 // parenthesized id-expression that names an entity of automatic
8000 // storage duration is treated as if x were transformed into an
8001 // access to a corresponding data member of the closure type that
8002 // would have been declared if x were an odr-use of the denoted
8004 using namespace sema;
8005 if (S.getCurLambda()) {
8006 if (isa<ParenExpr>(E)) {
8007 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8008 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8009 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
8011 return S.Context.getLValueReferenceType(T);
8018 // C++11 [dcl.type.simple]p4:
8020 QualType T = E->getType();
8021 switch (E->getValueKind()) {
8022 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
8024 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
8025 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
8027 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
8028 // - otherwise, decltype(e) is the type of e.
8029 case VK_RValue: break;
8035 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
8036 bool AsUnevaluated) {
8037 ExprResult ER = CheckPlaceholderExpr(E);
8038 if (ER.isInvalid()) return QualType();
8041 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
8042 E->HasSideEffects(Context, false)) {
8043 // The expression operand for decltype is in an unevaluated expression
8044 // context, so side effects could result in unintended consequences.
8045 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8048 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
8051 QualType Sema::BuildUnaryTransformType(QualType BaseType,
8052 UnaryTransformType::UTTKind UKind,
8053 SourceLocation Loc) {
8055 case UnaryTransformType::EnumUnderlyingType:
8056 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
8057 Diag(Loc, diag::err_only_enums_have_underlying_types);
8060 QualType Underlying = BaseType;
8061 if (!BaseType->isDependentType()) {
8062 // The enum could be incomplete if we're parsing its definition or
8063 // recovering from an error.
8064 NamedDecl *FwdDecl = nullptr;
8065 if (BaseType->isIncompleteType(&FwdDecl)) {
8066 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
8067 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
8071 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
8072 assert(ED && "EnumType has no EnumDecl");
8074 DiagnoseUseOfDecl(ED, Loc);
8076 Underlying = ED->getIntegerType();
8077 assert(!Underlying.isNull());
8079 return Context.getUnaryTransformType(BaseType, Underlying,
8080 UnaryTransformType::EnumUnderlyingType);
8083 llvm_unreachable("unknown unary transform type");
8086 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
8087 if (!T->isDependentType()) {
8088 // FIXME: It isn't entirely clear whether incomplete atomic types
8089 // are allowed or not; for simplicity, ban them for the moment.
8090 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
8093 int DisallowedKind = -1;
8094 if (T->isArrayType())
8096 else if (T->isFunctionType())
8098 else if (T->isReferenceType())
8100 else if (T->isAtomicType())
8102 else if (T.hasQualifiers())
8104 else if (!T.isTriviallyCopyableType(Context))
8105 // Some other non-trivially-copyable type (probably a C++ class)
8108 if (DisallowedKind != -1) {
8109 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
8113 // FIXME: Do we need any handling for ARC here?
8116 // Build the pointer type.
8117 return Context.getAtomicType(T);