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