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