clang  9.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.getName()->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  /*NumArgs=*/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.getName();
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_invalid_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_invalid_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  } \
1637  break;
1638 #include "clang/Basic/OpenCLImageTypes.def"
1639 
1640  case DeclSpec::TST_error:
1641  Result = Context.IntTy;
1642  declarator.setInvalidType(true);
1643  break;
1644  }
1645 
1646  if (S.getLangOpts().OpenCL &&
1648  declarator.setInvalidType(true);
1649 
1650  bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1651  DS.getTypeSpecType() == DeclSpec::TST_fract;
1652 
1653  // Only fixed point types can be saturated
1654  if (DS.isTypeSpecSat() && !IsFixedPointType)
1655  S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1656  << DS.getSpecifierName(DS.getTypeSpecType(),
1657  Context.getPrintingPolicy());
1658 
1659  // Handle complex types.
1660  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1661  if (S.getLangOpts().Freestanding)
1662  S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1663  Result = Context.getComplexType(Result);
1664  } else if (DS.isTypeAltiVecVector()) {
1665  unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1666  assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1668  if (DS.isTypeAltiVecPixel())
1669  VecKind = VectorType::AltiVecPixel;
1670  else if (DS.isTypeAltiVecBool())
1671  VecKind = VectorType::AltiVecBool;
1672  Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1673  }
1674 
1675  // FIXME: Imaginary.
1676  if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1677  S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1678 
1679  // Before we process any type attributes, synthesize a block literal
1680  // function declarator if necessary.
1681  if (declarator.getContext() == DeclaratorContext::BlockLiteralContext)
1683 
1684  // Apply any type attributes from the decl spec. This may cause the
1685  // list of type attributes to be temporarily saved while the type
1686  // attributes are pushed around.
1687  // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1688  if (!DS.isTypeSpecPipe())
1689  processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1690 
1691  // Apply const/volatile/restrict qualifiers to T.
1692  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1693  // Warn about CV qualifiers on function types.
1694  // C99 6.7.3p8:
1695  // If the specification of a function type includes any type qualifiers,
1696  // the behavior is undefined.
1697  // C++11 [dcl.fct]p7:
1698  // The effect of a cv-qualifier-seq in a function declarator is not the
1699  // same as adding cv-qualification on top of the function type. In the
1700  // latter case, the cv-qualifiers are ignored.
1701  if (TypeQuals && Result->isFunctionType()) {
1703  S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1704  S.getLangOpts().CPlusPlus
1705  ? diag::warn_typecheck_function_qualifiers_ignored
1706  : diag::warn_typecheck_function_qualifiers_unspecified);
1707  // No diagnostic for 'restrict' or '_Atomic' applied to a
1708  // function type; we'll diagnose those later, in BuildQualifiedType.
1709  }
1710 
1711  // C++11 [dcl.ref]p1:
1712  // Cv-qualified references are ill-formed except when the
1713  // cv-qualifiers are introduced through the use of a typedef-name
1714  // or decltype-specifier, in which case the cv-qualifiers are ignored.
1715  //
1716  // There don't appear to be any other contexts in which a cv-qualified
1717  // reference type could be formed, so the 'ill-formed' clause here appears
1718  // to never happen.
1719  if (TypeQuals && Result->isReferenceType()) {
1721  S, DS, TypeQuals, Result,
1723  diag::warn_typecheck_reference_qualifiers);
1724  }
1725 
1726  // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1727  // than once in the same specifier-list or qualifier-list, either directly
1728  // or via one or more typedefs."
1729  if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1730  && TypeQuals & Result.getCVRQualifiers()) {
1731  if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1732  S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1733  << "const";
1734  }
1735 
1736  if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1737  S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1738  << "volatile";
1739  }
1740 
1741  // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1742  // produce a warning in this case.
1743  }
1744 
1745  QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1746 
1747  // If adding qualifiers fails, just use the unqualified type.
1748  if (Qualified.isNull())
1749  declarator.setInvalidType(true);
1750  else
1751  Result = Qualified;
1752  }
1753 
1754  assert(!Result.isNull() && "This function should not return a null type");
1755  return Result;
1756 }
1757 
1758 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1759  if (Entity)
1760  return Entity.getAsString();
1761 
1762  return "type name";
1763 }
1764 
1766  Qualifiers Qs, const DeclSpec *DS) {
1767  if (T.isNull())
1768  return QualType();
1769 
1770  // Ignore any attempt to form a cv-qualified reference.
1771  if (T->isReferenceType()) {
1772  Qs.removeConst();
1773  Qs.removeVolatile();
1774  }
1775 
1776  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1777  // object or incomplete types shall not be restrict-qualified."
1778  if (Qs.hasRestrict()) {
1779  unsigned DiagID = 0;
1780  QualType ProblemTy;
1781 
1782  if (T->isAnyPointerType() || T->isReferenceType() ||
1783  T->isMemberPointerType()) {
1784  QualType EltTy;
1785  if (T->isObjCObjectPointerType())
1786  EltTy = T;
1787  else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1788  EltTy = PTy->getPointeeType();
1789  else
1790  EltTy = T->getPointeeType();
1791 
1792  // If we have a pointer or reference, the pointee must have an object
1793  // incomplete type.
1794  if (!EltTy->isIncompleteOrObjectType()) {
1795  DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1796  ProblemTy = EltTy;
1797  }
1798  } else if (!T->isDependentType()) {
1799  DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1800  ProblemTy = T;
1801  }
1802 
1803  if (DiagID) {
1804  Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1805  Qs.removeRestrict();
1806  }
1807  }
1808 
1809  return Context.getQualifiedType(T, Qs);
1810 }
1811 
1813  unsigned CVRAU, const DeclSpec *DS) {
1814  if (T.isNull())
1815  return QualType();
1816 
1817  // Ignore any attempt to form a cv-qualified reference.
1818  if (T->isReferenceType())
1819  CVRAU &=
1821 
1822  // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1823  // TQ_unaligned;
1824  unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1825 
1826  // C11 6.7.3/5:
1827  // If the same qualifier appears more than once in the same
1828  // specifier-qualifier-list, either directly or via one or more typedefs,
1829  // the behavior is the same as if it appeared only once.
1830  //
1831  // It's not specified what happens when the _Atomic qualifier is applied to
1832  // a type specified with the _Atomic specifier, but we assume that this
1833  // should be treated as if the _Atomic qualifier appeared multiple times.
1834  if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1835  // C11 6.7.3/5:
1836  // If other qualifiers appear along with the _Atomic qualifier in a
1837  // specifier-qualifier-list, the resulting type is the so-qualified
1838  // atomic type.
1839  //
1840  // Don't need to worry about array types here, since _Atomic can't be
1841  // applied to such types.
1843  T = BuildAtomicType(QualType(Split.Ty, 0),
1844  DS ? DS->getAtomicSpecLoc() : Loc);
1845  if (T.isNull())
1846  return T;
1847  Split.Quals.addCVRQualifiers(CVR);
1848  return BuildQualifiedType(T, Loc, Split.Quals);
1849  }
1850 
1853  return BuildQualifiedType(T, Loc, Q, DS);
1854 }
1855 
1856 /// Build a paren type including \p T.
1858  return Context.getParenType(T);
1859 }
1860 
1861 /// Given that we're building a pointer or reference to the given
1863  SourceLocation loc,
1864  bool isReference) {
1865  // Bail out if retention is unrequired or already specified.
1866  if (!type->isObjCLifetimeType() ||
1868  return type;
1869 
1871 
1872  // If the object type is const-qualified, we can safely use
1873  // __unsafe_unretained. This is safe (because there are no read
1874  // barriers), and it'll be safe to coerce anything but __weak* to
1875  // the resulting type.
1876  if (type.isConstQualified()) {
1877  implicitLifetime = Qualifiers::OCL_ExplicitNone;
1878 
1879  // Otherwise, check whether the static type does not require
1880  // retaining. This currently only triggers for Class (possibly
1881  // protocol-qualifed, and arrays thereof).
1882  } else if (type->isObjCARCImplicitlyUnretainedType()) {
1883  implicitLifetime = Qualifiers::OCL_ExplicitNone;
1884 
1885  // If we are in an unevaluated context, like sizeof, skip adding a
1886  // qualification.
1887  } else if (S.isUnevaluatedContext()) {
1888  return type;
1889 
1890  // If that failed, give an error and recover using __strong. __strong
1891  // is the option most likely to prevent spurious second-order diagnostics,
1892  // like when binding a reference to a field.
1893  } else {
1894  // These types can show up in private ivars in system headers, so
1895  // we need this to not be an error in those cases. Instead we
1896  // want to delay.
1900  diag::err_arc_indirect_no_ownership, type, isReference));
1901  } else {
1902  S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1903  }
1904  implicitLifetime = Qualifiers::OCL_Strong;
1905  }
1906  assert(implicitLifetime && "didn't infer any lifetime!");
1907 
1908  Qualifiers qs;
1909  qs.addObjCLifetime(implicitLifetime);
1910  return S.Context.getQualifiedType(type, qs);
1911 }
1912 
1913 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1914  std::string Quals = FnTy->getMethodQuals().getAsString();
1915 
1916  switch (FnTy->getRefQualifier()) {
1917  case RQ_None:
1918  break;
1919 
1920  case RQ_LValue:
1921  if (!Quals.empty())
1922  Quals += ' ';
1923  Quals += '&';
1924  break;
1925 
1926  case RQ_RValue:
1927  if (!Quals.empty())
1928  Quals += ' ';
1929  Quals += "&&";
1930  break;
1931  }
1932 
1933  return Quals;
1934 }
1935 
1936 namespace {
1937 /// Kinds of declarator that cannot contain a qualified function type.
1938 ///
1939 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1940 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1941 /// at the topmost level of a type.
1942 ///
1943 /// Parens and member pointers are permitted. We don't diagnose array and
1944 /// function declarators, because they don't allow function types at all.
1945 ///
1946 /// The values of this enum are used in diagnostics.
1947 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1948 } // end anonymous namespace
1949 
1950 /// Check whether the type T is a qualified function type, and if it is,
1951 /// diagnose that it cannot be contained within the given kind of declarator.
1953  QualifiedFunctionKind QFK) {
1954  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1955  const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1956  if (!FPT || (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1957  return false;
1958 
1959  S.Diag(Loc, diag::err_compound_qualified_function_type)
1960  << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1962  return true;
1963 }
1964 
1965 /// Build a pointer type.
1966 ///
1967 /// \param T The type to which we'll be building a pointer.
1968 ///
1969 /// \param Loc The location of the entity whose type involves this
1970 /// pointer type or, if there is no such entity, the location of the
1971 /// type that will have pointer type.
1972 ///
1973 /// \param Entity The name of the entity that involves the pointer
1974 /// type, if known.
1975 ///
1976 /// \returns A suitable pointer type, if there are no
1977 /// errors. Otherwise, returns a NULL type.
1979  SourceLocation Loc, DeclarationName Entity) {
1980  if (T->isReferenceType()) {
1981  // C++ 8.3.2p4: There shall be no ... pointers to references ...
1982  Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1983  << getPrintableNameForEntity(Entity) << T;
1984  return QualType();
1985  }
1986 
1987  if (T->isFunctionType() && getLangOpts().OpenCL) {
1988  Diag(Loc, diag::err_opencl_function_pointer);
1989  return QualType();
1990  }
1991 
1992  if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1993  return QualType();
1994 
1995  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1996 
1997  // In ARC, it is forbidden to build pointers to unqualified pointers.
1998  if (getLangOpts().ObjCAutoRefCount)
1999  T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2000 
2001  // Build the pointer type.
2002  return Context.getPointerType(T);
2003 }
2004 
2005 /// Build a reference type.
2006 ///
2007 /// \param T The type to which we'll be building a reference.
2008 ///
2009 /// \param Loc The location of the entity whose type involves this
2010 /// reference type or, if there is no such entity, the location of the
2011 /// type that will have reference type.
2012 ///
2013 /// \param Entity The name of the entity that involves the reference
2014 /// type, if known.
2015 ///
2016 /// \returns A suitable reference type, if there are no
2017 /// errors. Otherwise, returns a NULL type.
2019  SourceLocation Loc,
2020  DeclarationName Entity) {
2021  assert(Context.getCanonicalType(T) != Context.OverloadTy &&
2022  "Unresolved overloaded function type");
2023 
2024  // C++0x [dcl.ref]p6:
2025  // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2026  // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2027  // type T, an attempt to create the type "lvalue reference to cv TR" creates
2028  // the type "lvalue reference to T", while an attempt to create the type
2029  // "rvalue reference to cv TR" creates the type TR.
2030  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
2031 
2032  // C++ [dcl.ref]p4: There shall be no references to references.
2033  //
2034  // According to C++ DR 106, references to references are only
2035  // diagnosed when they are written directly (e.g., "int & &"),
2036  // but not when they happen via a typedef:
2037  //
2038  // typedef int& intref;
2039  // typedef intref& intref2;
2040  //
2041  // Parser::ParseDeclaratorInternal diagnoses the case where
2042  // references are written directly; here, we handle the
2043  // collapsing of references-to-references as described in C++0x.
2044  // DR 106 and 540 introduce reference-collapsing into C++98/03.
2045 
2046  // C++ [dcl.ref]p1:
2047  // A declarator that specifies the type "reference to cv void"
2048  // is ill-formed.
2049  if (T->isVoidType()) {
2050  Diag(Loc, diag::err_reference_to_void);
2051  return QualType();
2052  }
2053 
2054  if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2055  return QualType();
2056 
2057  // In ARC, it is forbidden to build references to unqualified pointers.
2058  if (getLangOpts().ObjCAutoRefCount)
2059  T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2060 
2061  // Handle restrict on references.
2062  if (LValueRef)
2063  return Context.getLValueReferenceType(T, SpelledAsLValue);
2064  return Context.getRValueReferenceType(T);
2065 }
2066 
2067 /// Build a Read-only Pipe type.
2068 ///
2069 /// \param T The type to which we'll be building a Pipe.
2070 ///
2071 /// \param Loc We do not use it for now.
2072 ///
2073 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2074 /// NULL type.
2076  return Context.getReadPipeType(T);
2077 }
2078 
2079 /// Build a Write-only Pipe type.
2080 ///
2081 /// \param T The type to which we'll be building a Pipe.
2082 ///
2083 /// \param Loc We do not use it for now.
2084 ///
2085 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2086 /// NULL type.
2088  return Context.getWritePipeType(T);
2089 }
2090 
2091 /// Check whether the specified array size makes the array type a VLA. If so,
2092 /// return true, if not, return the size of the array in SizeVal.
2093 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
2094  // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2095  // (like gnu99, but not c99) accept any evaluatable value as an extension.
2096  class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2097  public:
2098  VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
2099 
2100  void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
2101  }
2102 
2103  void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
2104  S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2105  }
2106  } Diagnoser;
2107 
2108  return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2109  S.LangOpts.GNUMode ||
2110  S.LangOpts.OpenCL).isInvalid();
2111 }
2112 
2113 /// Build an array type.
2114 ///
2115 /// \param T The type of each element in the array.
2116 ///
2117 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2118 ///
2119 /// \param ArraySize Expression describing the size of the array.
2120 ///
2121 /// \param Brackets The range from the opening '[' to the closing ']'.
2122 ///
2123 /// \param Entity The name of the entity that involves the array
2124 /// type, if known.
2125 ///
2126 /// \returns A suitable array type, if there are no errors. Otherwise,
2127 /// returns a NULL type.
2129  Expr *ArraySize, unsigned Quals,
2130  SourceRange Brackets, DeclarationName Entity) {
2131 
2132  SourceLocation Loc = Brackets.getBegin();
2133  if (getLangOpts().CPlusPlus) {
2134  // C++ [dcl.array]p1:
2135  // T is called the array element type; this type shall not be a reference
2136  // type, the (possibly cv-qualified) type void, a function type or an
2137  // abstract class type.
2138  //
2139  // C++ [dcl.array]p3:
2140  // When several "array of" specifications are adjacent, [...] only the
2141  // first of the constant expressions that specify the bounds of the arrays
2142  // may be omitted.
2143  //
2144  // Note: function types are handled in the common path with C.
2145  if (T->isReferenceType()) {
2146  Diag(Loc, diag::err_illegal_decl_array_of_references)
2147  << getPrintableNameForEntity(Entity) << T;
2148  return QualType();
2149  }
2150 
2151  if (T->isVoidType() || T->isIncompleteArrayType()) {
2152  Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2153  return QualType();
2154  }
2155 
2156  if (RequireNonAbstractType(Brackets.getBegin(), T,
2157  diag::err_array_of_abstract_type))
2158  return QualType();
2159 
2160  // Mentioning a member pointer type for an array type causes us to lock in
2161  // an inheritance model, even if it's inside an unused typedef.
2162  if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2163  if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2164  if (!MPTy->getClass()->isDependentType())
2165  (void)isCompleteType(Loc, T);
2166 
2167  } else {
2168  // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2169  // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2170  if (RequireCompleteType(Loc, T,
2171  diag::err_illegal_decl_array_incomplete_type))
2172  return QualType();
2173  }
2174 
2175  if (T->isFunctionType()) {
2176  Diag(Loc, diag::err_illegal_decl_array_of_functions)
2177  << getPrintableNameForEntity(Entity) << T;
2178  return QualType();
2179  }
2180 
2181  if (const RecordType *EltTy = T->getAs<RecordType>()) {
2182  // If the element type is a struct or union that contains a variadic
2183  // array, accept it as a GNU extension: C99 6.7.2.1p2.
2184  if (EltTy->getDecl()->hasFlexibleArrayMember())
2185  Diag(Loc, diag::ext_flexible_array_in_array) << T;
2186  } else if (T->isObjCObjectType()) {
2187  Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2188  return QualType();
2189  }
2190 
2191  // Do placeholder conversions on the array size expression.
2192  if (ArraySize && ArraySize->hasPlaceholderType()) {
2193  ExprResult Result = CheckPlaceholderExpr(ArraySize);
2194  if (Result.isInvalid()) return QualType();
2195  ArraySize = Result.get();
2196  }
2197 
2198  // Do lvalue-to-rvalue conversions on the array size expression.
2199  if (ArraySize && !ArraySize->isRValue()) {
2200  ExprResult Result = DefaultLvalueConversion(ArraySize);
2201  if (Result.isInvalid())
2202  return QualType();
2203 
2204  ArraySize = Result.get();
2205  }
2206 
2207  // C99 6.7.5.2p1: The size expression shall have integer type.
2208  // C++11 allows contextual conversions to such types.
2209  if (!getLangOpts().CPlusPlus11 &&
2210  ArraySize && !ArraySize->isTypeDependent() &&
2211  !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2212  Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2213  << ArraySize->getType() << ArraySize->getSourceRange();
2214  return QualType();
2215  }
2216 
2217  llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2218  if (!ArraySize) {
2219  if (ASM == ArrayType::Star)
2220  T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2221  else
2222  T = Context.getIncompleteArrayType(T, ASM, Quals);
2223  } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2224  T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2225  } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2226  !T->isConstantSizeType()) ||
2227  isArraySizeVLA(*this, ArraySize, ConstVal)) {
2228  // Even in C++11, don't allow contextual conversions in the array bound
2229  // of a VLA.
2230  if (getLangOpts().CPlusPlus11 &&
2231  !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2232  Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2233  << ArraySize->getType() << ArraySize->getSourceRange();
2234  return QualType();
2235  }
2236 
2237  // C99: an array with an element type that has a non-constant-size is a VLA.
2238  // C99: an array with a non-ICE size is a VLA. We accept any expression
2239  // that we can fold to a non-zero positive value as an extension.
2240  T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2241  } else {
2242  // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2243  // have a value greater than zero.
2244  if (ConstVal.isSigned() && ConstVal.isNegative()) {
2245  if (Entity)
2246  Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2247  << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2248  else
2249  Diag(ArraySize->getBeginLoc(), diag::err_typecheck_negative_array_size)
2250  << ArraySize->getSourceRange();
2251  return QualType();
2252  }
2253  if (ConstVal == 0) {
2254  // GCC accepts zero sized static arrays. We allow them when
2255  // we're not in a SFINAE context.
2256  Diag(ArraySize->getBeginLoc(), isSFINAEContext()
2257  ? diag::err_typecheck_zero_array_size
2258  : diag::ext_typecheck_zero_array_size)
2259  << ArraySize->getSourceRange();
2260 
2261  if (ASM == ArrayType::Static) {
2262  Diag(ArraySize->getBeginLoc(),
2263  diag::warn_typecheck_zero_static_array_size)
2264  << ArraySize->getSourceRange();
2265  ASM = ArrayType::Normal;
2266  }
2267  } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2268  !T->isIncompleteType() && !T->isUndeducedType()) {
2269  // Is the array too large?
2270  unsigned ActiveSizeBits
2271  = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2272  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2273  Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2274  << ConstVal.toString(10) << ArraySize->getSourceRange();
2275  return QualType();
2276  }
2277  }
2278 
2279  T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2280  }
2281 
2282  // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2283  if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2284  Diag(Loc, diag::err_opencl_vla);
2285  return QualType();
2286  }
2287 
2288  if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2289  // CUDA device code and some other targets don't support VLAs.
2290  targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2291  ? diag::err_cuda_vla
2292  : diag::err_vla_unsupported)
2293  << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2294  ? CurrentCUDATarget()
2295  : CFT_InvalidTarget);
2296  }
2297 
2298  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2299  if (!getLangOpts().C99) {
2300  if (T->isVariableArrayType()) {
2301  // Prohibit the use of VLAs during template argument deduction.
2302  if (isSFINAEContext()) {
2303  Diag(Loc, diag::err_vla_in_sfinae);
2304  return QualType();
2305  }
2306  // Just extwarn about VLAs.
2307  else
2308  Diag(Loc, diag::ext_vla);
2309  } else if (ASM != ArrayType::Normal || Quals != 0)
2310  Diag(Loc,
2311  getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2312  : diag::ext_c99_array_usage) << ASM;
2313  }
2314 
2315  if (T->isVariableArrayType()) {
2316  // Warn about VLAs for -Wvla.
2317  Diag(Loc, diag::warn_vla_used);
2318  }
2319 
2320  // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2321  // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2322  // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2323  if (getLangOpts().OpenCL) {
2324  const QualType ArrType = Context.getBaseElementType(T);
2325  if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2326  ArrType->isSamplerT() || ArrType->isImageType()) {
2327  Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2328  return QualType();
2329  }
2330  }
2331 
2332  return T;
2333 }
2334 
2336  SourceLocation AttrLoc) {
2337  // The base type must be integer (not Boolean or enumeration) or float, and
2338  // can't already be a vector.
2339  if (!CurType->isDependentType() &&
2340  (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2341  (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) {
2342  Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2343  return QualType();
2344  }
2345 
2346  if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2347  return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2349 
2350  llvm::APSInt VecSize(32);
2351  if (!SizeExpr->isIntegerConstantExpr(VecSize, Context)) {
2352  Diag(AttrLoc, diag::err_attribute_argument_type)
2353  << "vector_size" << AANT_ArgumentIntegerConstant
2354  << SizeExpr->getSourceRange();
2355  return QualType();
2356  }
2357 
2358  if (CurType->isDependentType())
2359  return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2361 
2362  unsigned VectorSize = static_cast<unsigned>(VecSize.getZExtValue() * 8);
2363  unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2364 
2365  if (VectorSize == 0) {
2366  Diag(AttrLoc, diag::err_attribute_zero_size) << SizeExpr->getSourceRange();
2367  return QualType();
2368  }
2369 
2370  // vecSize is specified in bytes - convert to bits.
2371  if (VectorSize % TypeSize) {
2372  Diag(AttrLoc, diag::err_attribute_invalid_size)
2373  << SizeExpr->getSourceRange();
2374  return QualType();
2375  }
2376 
2377  if (VectorType::isVectorSizeTooLarge(VectorSize / TypeSize)) {
2378  Diag(AttrLoc, diag::err_attribute_size_too_large)
2379  << SizeExpr->getSourceRange();
2380  return QualType();
2381  }
2382 
2383  return Context.getVectorType(CurType, VectorSize / TypeSize,
2385 }
2386 
2387 /// Build an ext-vector type.
2388 ///
2389 /// Run the required checks for the extended vector type.
2391  SourceLocation AttrLoc) {
2392  // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2393  // in conjunction with complex types (pointers, arrays, functions, etc.).
2394  //
2395  // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2396  // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2397  // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2398  // of bool aren't allowed.
2399  if ((!T->isDependentType() && !T->isIntegerType() &&
2400  !T->isRealFloatingType()) ||
2401  T->isBooleanType()) {
2402  Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2403  return QualType();
2404  }
2405 
2406  if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2407  llvm::APSInt vecSize(32);
2408  if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2409  Diag(AttrLoc, diag::err_attribute_argument_type)
2410  << "ext_vector_type" << AANT_ArgumentIntegerConstant
2411  << ArraySize->getSourceRange();
2412  return QualType();
2413  }
2414 
2415  // Unlike gcc's vector_size attribute, the size is specified as the
2416  // number of elements, not the number of bytes.
2417  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2418 
2419  if (vectorSize == 0) {
2420  Diag(AttrLoc, diag::err_attribute_zero_size)
2421  << ArraySize->getSourceRange();
2422  return QualType();
2423  }
2424 
2425  if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2426  Diag(AttrLoc, diag::err_attribute_size_too_large)
2427  << ArraySize->getSourceRange();
2428  return QualType();
2429  }
2430 
2431  return Context.getExtVectorType(T, vectorSize);
2432  }
2433 
2434  return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2435 }
2436 
2438  if (T->isArrayType() || T->isFunctionType()) {
2439  Diag(Loc, diag::err_func_returning_array_function)
2440  << T->isFunctionType() << T;
2441  return true;
2442  }
2443 
2444  // Functions cannot return half FP.
2445  if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2446  Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2447  FixItHint::CreateInsertion(Loc, "*");
2448  return true;
2449  }
2450 
2451  // Methods cannot return interface types. All ObjC objects are
2452  // passed by reference.
2453  if (T->isObjCObjectType()) {
2454  Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2455  << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2456  return true;
2457  }
2458 
2459  return false;
2460 }
2461 
2462 /// Check the extended parameter information. Most of the necessary
2463 /// checking should occur when applying the parameter attribute; the
2464 /// only other checks required are positional restrictions.
2467  llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2468  assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2469 
2470  bool hasCheckedSwiftCall = false;
2471  auto checkForSwiftCC = [&](unsigned paramIndex) {
2472  // Only do this once.
2473  if (hasCheckedSwiftCall) return;
2474  hasCheckedSwiftCall = true;
2475  if (EPI.ExtInfo.getCC() == CC_Swift) return;
2476  S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2477  << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2478  };
2479 
2480  for (size_t paramIndex = 0, numParams = paramTypes.size();
2481  paramIndex != numParams; ++paramIndex) {
2482  switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2483  // Nothing interesting to check for orindary-ABI parameters.
2485  continue;
2486 
2487  // swift_indirect_result parameters must be a prefix of the function
2488  // arguments.
2490  checkForSwiftCC(paramIndex);
2491  if (paramIndex != 0 &&
2492  EPI.ExtParameterInfos[paramIndex - 1].getABI()
2494  S.Diag(getParamLoc(paramIndex),
2495  diag::err_swift_indirect_result_not_first);
2496  }
2497  continue;
2498 
2500  checkForSwiftCC(paramIndex);
2501  continue;
2502 
2503  // swift_error parameters must be preceded by a swift_context parameter.
2505  checkForSwiftCC(paramIndex);
2506  if (paramIndex == 0 ||
2507  EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2509  S.Diag(getParamLoc(paramIndex),
2510  diag::err_swift_error_result_not_after_swift_context);
2511  }
2512  continue;
2513  }
2514  llvm_unreachable("bad ABI kind");
2515  }
2516 }
2517 
2519  MutableArrayRef<QualType> ParamTypes,
2520  SourceLocation Loc, DeclarationName Entity,
2521  const FunctionProtoType::ExtProtoInfo &EPI) {
2522  bool Invalid = false;
2523 
2524  Invalid |= CheckFunctionReturnType(T, Loc);
2525 
2526  for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2527  // FIXME: Loc is too inprecise here, should use proper locations for args.
2528  QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2529  if (ParamType->isVoidType()) {
2530  Diag(Loc, diag::err_param_with_void_type);
2531  Invalid = true;
2532  } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2533  // Disallow half FP arguments.
2534  Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2535  FixItHint::CreateInsertion(Loc, "*");
2536  Invalid = true;
2537  }
2538 
2539  ParamTypes[Idx] = ParamType;
2540  }
2541 
2542  if (EPI.ExtParameterInfos) {
2543  checkExtParameterInfos(*this, ParamTypes, EPI,
2544  [=](unsigned i) { return Loc; });
2545  }
2546 
2547  if (EPI.ExtInfo.getProducesResult()) {
2548  // This is just a warning, so we can't fail to build if we see it.
2549  checkNSReturnsRetainedReturnType(Loc, T);
2550  }
2551 
2552  if (Invalid)
2553  return QualType();
2554 
2555  return Context.getFunctionType(T, ParamTypes, EPI);
2556 }
2557 
2558 /// Build a member pointer type \c T Class::*.
2559 ///
2560 /// \param T the type to which the member pointer refers.
2561 /// \param Class the class type into which the member pointer points.
2562 /// \param Loc the location where this type begins
2563 /// \param Entity the name of the entity that will have this member pointer type
2564 ///
2565 /// \returns a member pointer type, if successful, or a NULL type if there was
2566 /// an error.
2568  SourceLocation Loc,
2569  DeclarationName Entity) {
2570  // Verify that we're not building a pointer to pointer to function with
2571  // exception specification.
2572  if (CheckDistantExceptionSpec(T)) {
2573  Diag(Loc, diag::err_distant_exception_spec);
2574  return QualType();
2575  }
2576 
2577  // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2578  // with reference type, or "cv void."
2579  if (T->isReferenceType()) {
2580  Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2581  << getPrintableNameForEntity(Entity) << T;
2582  return QualType();
2583  }
2584 
2585  if (T->isVoidType()) {
2586  Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2587  << getPrintableNameForEntity(Entity);
2588  return QualType();
2589  }
2590 
2591  if (!Class->isDependentType() && !Class->isRecordType()) {
2592  Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2593  return QualType();
2594  }
2595 
2596  // Adjust the default free function calling convention to the default method
2597  // calling convention.
2598  bool IsCtorOrDtor =
2601  if (T->isFunctionType())
2602  adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2603 
2604  return Context.getMemberPointerType(T, Class.getTypePtr());
2605 }
2606 
2607 /// Build a block pointer type.
2608 ///
2609 /// \param T The type to which we'll be building a block pointer.
2610 ///
2611 /// \param Loc The source location, used for diagnostics.
2612 ///
2613 /// \param Entity The name of the entity that involves the block pointer
2614 /// type, if known.
2615 ///
2616 /// \returns A suitable block pointer type, if there are no
2617 /// errors. Otherwise, returns a NULL type.
2619  SourceLocation Loc,
2620  DeclarationName Entity) {
2621  if (!T->isFunctionType()) {
2622  Diag(Loc, diag::err_nonfunction_block_type);
2623  return QualType();
2624  }
2625 
2626  if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2627  return QualType();
2628 
2629  return Context.getBlockPointerType(T);
2630 }
2631 
2633  QualType QT = Ty.get();
2634  if (QT.isNull()) {
2635  if (TInfo) *TInfo = nullptr;
2636  return QualType();
2637  }
2638 
2639  TypeSourceInfo *DI = nullptr;
2640  if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2641  QT = LIT->getType();
2642  DI = LIT->getTypeSourceInfo();
2643  }
2644 
2645  if (TInfo) *TInfo = DI;
2646  return QT;
2647 }
2648 
2649 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2650  Qualifiers::ObjCLifetime ownership,
2651  unsigned chunkIndex);
2652 
2653 /// Given that this is the declaration of a parameter under ARC,
2654 /// attempt to infer attributes and such for pointer-to-whatever
2655 /// types.
2656 static void inferARCWriteback(TypeProcessingState &state,
2657  QualType &declSpecType) {
2658  Sema &S = state.getSema();
2659  Declarator &declarator = state.getDeclarator();
2660 
2661  // TODO: should we care about decl qualifiers?
2662 
2663  // Check whether the declarator has the expected form. We walk
2664  // from the inside out in order to make the block logic work.
2665  unsigned outermostPointerIndex = 0;
2666  bool isBlockPointer = false;
2667  unsigned numPointers = 0;
2668  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2669  unsigned chunkIndex = i;
2670  DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2671  switch (chunk.Kind) {
2673  // Ignore parens.
2674  break;
2675 
2678  // Count the number of pointers. Treat references
2679  // interchangeably as pointers; if they're mis-ordered, normal
2680  // type building will discover that.
2681  outermostPointerIndex = chunkIndex;
2682  numPointers++;
2683  break;
2684 
2686  // If we have a pointer to block pointer, that's an acceptable
2687  // indirect reference; anything else is not an application of
2688  // the rules.
2689  if (numPointers != 1) return;
2690  numPointers++;
2691  outermostPointerIndex = chunkIndex;
2692  isBlockPointer = true;
2693 
2694  // We don't care about pointer structure in return values here.
2695  goto done;
2696 
2697  case DeclaratorChunk::Array: // suppress if written (id[])?
2700  case DeclaratorChunk::Pipe:
2701  return;
2702  }
2703  }
2704  done:
2705 
2706  // If we have *one* pointer, then we want to throw the qualifier on
2707  // the declaration-specifiers, which means that it needs to be a
2708  // retainable object type.
2709  if (numPointers == 1) {
2710  // If it's not a retainable object type, the rule doesn't apply.
2711  if (!declSpecType->isObjCRetainableType()) return;
2712 
2713  // If it already has lifetime, don't do anything.
2714  if (declSpecType.getObjCLifetime()) return;
2715 
2716  // Otherwise, modify the type in-place.
2717  Qualifiers qs;
2718 
2719  if (declSpecType->isObjCARCImplicitlyUnretainedType())
2721  else
2723  declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2724 
2725  // If we have *two* pointers, then we want to throw the qualifier on
2726  // the outermost pointer.
2727  } else if (numPointers == 2) {
2728  // If we don't have a block pointer, we need to check whether the
2729  // declaration-specifiers gave us something that will turn into a
2730  // retainable object pointer after we slap the first pointer on it.
2731  if (!isBlockPointer && !declSpecType->isObjCObjectType())
2732  return;
2733 
2734  // Look for an explicit lifetime attribute there.
2735  DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2736  if (chunk.Kind != DeclaratorChunk::Pointer &&
2738  return;
2739  for (const ParsedAttr &AL : chunk.getAttrs())
2740  if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2741  return;
2742 
2744  outermostPointerIndex);
2745 
2746  // Any other number of pointers/references does not trigger the rule.
2747  } else return;
2748 
2749  // TODO: mark whether we did this inference?
2750 }
2751 
2752 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2753  SourceLocation FallbackLoc,
2754  SourceLocation ConstQualLoc,
2755  SourceLocation VolatileQualLoc,
2756  SourceLocation RestrictQualLoc,
2757  SourceLocation AtomicQualLoc,
2758  SourceLocation UnalignedQualLoc) {
2759  if (!Quals)
2760  return;
2761 
2762  struct Qual {
2763  const char *Name;
2764  unsigned Mask;
2765  SourceLocation Loc;
2766  } const QualKinds[5] = {
2767  { "const", DeclSpec::TQ_const, ConstQualLoc },
2768  { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2769  { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2770  { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2771  { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2772  };
2773 
2774  SmallString<32> QualStr;
2775  unsigned NumQuals = 0;
2776  SourceLocation Loc;
2777  FixItHint FixIts[5];
2778 
2779  // Build a string naming the redundant qualifiers.
2780  for (auto &E : QualKinds) {
2781  if (Quals & E.Mask) {
2782  if (!QualStr.empty()) QualStr += ' ';
2783  QualStr += E.Name;
2784 
2785  // If we have a location for the qualifier, offer a fixit.
2786  SourceLocation QualLoc = E.Loc;
2787  if (QualLoc.isValid()) {
2788  FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2789  if (Loc.isInvalid() ||
2790  getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2791  Loc = QualLoc;
2792  }
2793 
2794  ++NumQuals;
2795  }
2796  }
2797 
2798  Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2799  << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2800 }
2801 
2802 // Diagnose pointless type qualifiers on the return type of a function.
2804  Declarator &D,
2805  unsigned FunctionChunkIndex) {
2806  if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2807  // FIXME: TypeSourceInfo doesn't preserve location information for
2808  // qualifiers.
2809  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2810  RetTy.getLocalCVRQualifiers(),
2811  D.getIdentifierLoc());
2812  return;
2813  }
2814 
2815  for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2816  End = D.getNumTypeObjects();
2817  OuterChunkIndex != End; ++OuterChunkIndex) {
2818  DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2819  switch (OuterChunk.Kind) {
2821  continue;
2822 
2823  case DeclaratorChunk::Pointer: {
2824  DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2826  diag::warn_qual_return_type,
2827  PTI.TypeQuals,
2828  SourceLocation(),
2834  return;
2835  }
2836 
2842  case DeclaratorChunk::Pipe:
2843  // FIXME: We can't currently provide an accurate source location and a
2844  // fix-it hint for these.
2845  unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2846  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2847  RetTy.getCVRQualifiers() | AtomicQual,
2848  D.getIdentifierLoc());
2849  return;
2850  }
2851 
2852  llvm_unreachable("unknown declarator chunk kind");
2853  }
2854 
2855  // If the qualifiers come from a conversion function type, don't diagnose
2856  // them -- they're not necessarily redundant, since such a conversion
2857  // operator can be explicitly called as "x.operator const int()".
2859  return;
2860 
2861  // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2862  // which are present there.
2863  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2865  D.getIdentifierLoc(),
2871 }
2872 
2873 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2874  TypeSourceInfo *&ReturnTypeInfo) {
2875  Sema &SemaRef = state.getSema();
2876  Declarator &D = state.getDeclarator();
2877  QualType T;
2878  ReturnTypeInfo = nullptr;
2879 
2880  // The TagDecl owned by the DeclSpec.
2881  TagDecl *OwnedTagDecl = nullptr;
2882 
2883  switch (D.getName().getKind()) {
2889  T = ConvertDeclSpecToType(state);
2890 
2891  if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2892  OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2893  // Owned declaration is embedded in declarator.
2894  OwnedTagDecl->setEmbeddedInDeclarator(true);
2895  }
2896  break;
2897 
2901  // Constructors and destructors don't have return types. Use
2902  // "void" instead.
2903  T = SemaRef.Context.VoidTy;
2904  processTypeAttrs(state, T, TAL_DeclSpec,
2906  break;
2907 
2909  // Deduction guides have a trailing return type and no type in their
2910  // decl-specifier sequence. Use a placeholder return type for now.
2911  T = SemaRef.Context.DependentTy;
2912  break;
2913 
2915  // The result type of a conversion function is the type that it
2916  // converts to.
2918  &ReturnTypeInfo);
2919  break;
2920  }
2921 
2922  if (!D.getAttributes().empty())
2924 
2925  // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2926  if (DeducedType *Deduced = T->getContainedDeducedType()) {
2927  AutoType *Auto = dyn_cast<AutoType>(Deduced);
2928  int Error = -1;
2929 
2930  // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
2931  // class template argument deduction)?
2932  bool IsCXXAutoType =
2933  (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
2934  bool IsDeducedReturnType = false;
2935 
2936  switch (D.getContext()) {
2938  // Declared return type of a lambda-declarator is implicit and is always
2939  // 'auto'.
2940  break;
2944  Error = 0;
2945  break;
2947  // In C++14, generic lambdas allow 'auto' in their parameters.
2948  if (!SemaRef.getLangOpts().CPlusPlus14 ||
2949  !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto)
2950  Error = 16;
2951  else {
2952  // If auto is mentioned in a lambda parameter context, convert it to a
2953  // template parameter type.
2954  sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda();
2955  assert(LSI && "No LambdaScopeInfo on the stack!");
2956  const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
2957  const unsigned AutoParameterPosition = LSI->TemplateParams.size();
2958  const bool IsParameterPack = D.hasEllipsis();
2959 
2960  // Create the TemplateTypeParmDecl here to retrieve the corresponding
2961  // template parameter type. Template parameters are temporarily added
2962  // to the TU until the associated TemplateDecl is created.
2963  TemplateTypeParmDecl *CorrespondingTemplateParam =
2965  SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(),
2966  /*KeyLoc*/ SourceLocation(), /*NameLoc*/ D.getBeginLoc(),
2967  TemplateParameterDepth, AutoParameterPosition,
2968  /*Identifier*/ nullptr, false, IsParameterPack);
2969  CorrespondingTemplateParam->setImplicit();
2970  LSI->TemplateParams.push_back(CorrespondingTemplateParam);
2971  // Replace the 'auto' in the function parameter with this invented
2972  // template type parameter.
2973  // FIXME: Retain some type sugar to indicate that this was written
2974  // as 'auto'.
2975  T = state.ReplaceAutoType(
2976  T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
2977  }
2978  break;
2982  break;
2983  bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2984  switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2985  case TTK_Enum: llvm_unreachable("unhandled tag kind");
2986  case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2987  case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
2988  case TTK_Class: Error = 5; /* Class member */ break;
2989  case TTK_Interface: Error = 6; /* Interface member */ break;
2990  }
2991  if (D.getDeclSpec().isFriendSpecified())
2992  Error = 20; // Friend type
2993  break;
2994  }
2997  Error = 7; // Exception declaration
2998  break;
3000  if (isa<DeducedTemplateSpecializationType>(Deduced))
3001  Error = 19; // Template parameter
3002  else if (!SemaRef.getLangOpts().CPlusPlus17)
3003  Error = 8; // Template parameter (until C++17)
3004  break;
3006  Error = 9; // Block literal
3007  break;
3009  // Within a template argument list, a deduced template specialization
3010  // type will be reinterpreted as a template template argument.
3011  if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3012  !D.getNumTypeObjects() &&
3014  break;
3015  LLVM_FALLTHROUGH;
3017  Error = 10; // Template type argument
3018  break;
3021  Error = 12; // Type alias
3022  break;
3025  if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3026  Error = 13; // Function return type
3027  IsDeducedReturnType = true;
3028  break;
3030  if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3031  Error = 14; // conversion-type-id
3032  IsDeducedReturnType = true;
3033  break;
3035  if (isa<DeducedTemplateSpecializationType>(Deduced))
3036  break;
3037  LLVM_FALLTHROUGH;
3039  Error = 15; // Generic
3040  break;
3046  // FIXME: P0091R3 (erroneously) does not permit class template argument
3047  // deduction in conditions, for-init-statements, and other declarations
3048  // that are not simple-declarations.
3049  break;
3051  // FIXME: P0091R3 does not permit class template argument deduction here,
3052  // but we follow GCC and allow it anyway.
3053  if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3054  Error = 17; // 'new' type
3055  break;
3057  Error = 18; // K&R function parameter
3058  break;
3059  }
3060 
3062  Error = 11;
3063 
3064  // In Objective-C it is an error to use 'auto' on a function declarator
3065  // (and everywhere for '__auto_type').
3066  if (D.isFunctionDeclarator() &&
3067  (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3068  Error = 13;
3069 
3070  bool HaveTrailing = false;
3071 
3072  // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
3073  // contains a trailing return type. That is only legal at the outermost
3074  // level. Check all declarator chunks (outermost first) anyway, to give
3075  // better diagnostics.
3076  // We don't support '__auto_type' with trailing return types.
3077  // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
3078  if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
3079  D.hasTrailingReturnType()) {
3080  HaveTrailing = true;
3081  Error = -1;
3082  }
3083 
3084  SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3086  AutoRange = D.getName().getSourceRange();
3087 
3088  if (Error != -1) {
3089  unsigned Kind;
3090  if (Auto) {
3091  switch (Auto->getKeyword()) {
3092  case AutoTypeKeyword::Auto: Kind = 0; break;
3093  case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3094  case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3095  }
3096  } else {
3097  assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3098  "unknown auto type");
3099  Kind = 3;
3100  }
3101 
3102  auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3103  TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3104 
3105  SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3106  << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3107  << QualType(Deduced, 0) << AutoRange;
3108  if (auto *TD = TN.getAsTemplateDecl())
3109  SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3110 
3111  T = SemaRef.Context.IntTy;
3112  D.setInvalidType(true);
3113  } else if (!HaveTrailing &&
3115  // If there was a trailing return type, we already got
3116  // warn_cxx98_compat_trailing_return_type in the parser.
3117  SemaRef.Diag(AutoRange.getBegin(),
3118  D.getContext() ==
3120  ? diag::warn_cxx11_compat_generic_lambda
3121  : IsDeducedReturnType
3122  ? diag::warn_cxx11_compat_deduced_return_type
3123  : diag::warn_cxx98_compat_auto_type_specifier)
3124  << AutoRange;
3125  }
3126  }
3127 
3128  if (SemaRef.getLangOpts().CPlusPlus &&
3129  OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3130  // Check the contexts where C++ forbids the declaration of a new class
3131  // or enumeration in a type-specifier-seq.
3132  unsigned DiagID = 0;
3133  switch (D.getContext()) {
3136  // Class and enumeration definitions are syntactically not allowed in
3137  // trailing return types.
3138  llvm_unreachable("parser should not have allowed this");
3139  break;
3147  // C++11 [dcl.type]p3:
3148  // A type-specifier-seq shall not define a class or enumeration unless
3149  // it appears in the type-id of an alias-declaration (7.1.3) that is not
3150  // the declaration of a template-declaration.
3152  break;
3154  DiagID = diag::err_type_defined_in_alias_template;
3155  break;
3165  DiagID = diag::err_type_defined_in_type_specifier;
3166  break;
3172  // C++ [dcl.fct]p6:
3173  // Types shall not be defined in return or parameter types.
3174  DiagID = diag::err_type_defined_in_param_type;
3175  break;
3177  // C++ 6.4p2:
3178  // The type-specifier-seq shall not contain typedef and shall not declare
3179  // a new class or enumeration.
3180  DiagID = diag::err_type_defined_in_condition;
3181  break;
3182  }
3183 
3184  if (DiagID != 0) {
3185  SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3186  << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3187  D.setInvalidType(true);
3188  }
3189  }
3190 
3191  assert(!T.isNull() && "This function should not return a null type");
3192  return T;
3193 }
3194 
3195 /// Produce an appropriate diagnostic for an ambiguity between a function
3196 /// declarator and a C++ direct-initializer.
3198  DeclaratorChunk &DeclType, QualType RT) {
3199  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3200  assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3201 
3202  // If the return type is void there is no ambiguity.
3203  if (RT->isVoidType())
3204  return;
3205 
3206  // An initializer for a non-class type can have at most one argument.
3207  if (!RT->isRecordType() && FTI.NumParams > 1)
3208  return;
3209 
3210  // An initializer for a reference must have exactly one argument.
3211  if (RT->isReferenceType() && FTI.NumParams != 1)
3212  return;
3213 
3214  // Only warn if this declarator is declaring a function at block scope, and
3215  // doesn't have a storage class (such as 'extern') specified.
3216  if (!D.isFunctionDeclarator() ||
3221  return;
3222 
3223  // Inside a condition, a direct initializer is not permitted. We allow one to
3224  // be parsed in order to give better diagnostics in condition parsing.
3226  return;
3227 
3228  SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3229 
3230  S.Diag(DeclType.Loc,
3231  FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3232  : diag::warn_empty_parens_are_function_decl)
3233  << ParenRange;
3234 
3235  // If the declaration looks like:
3236  // T var1,
3237  // f();
3238  // and name lookup finds a function named 'f', then the ',' was
3239  // probably intended to be a ';'.
3240  if (!D.isFirstDeclarator() && D.getIdentifier()) {
3243  if (Comma.getFileID() != Name.getFileID() ||
3244  Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3247  if (S.LookupName(Result, S.getCurScope()))
3248  S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3250  << D.getIdentifier();
3251  Result.suppressDiagnostics();
3252  }
3253  }
3254 
3255  if (FTI.NumParams > 0) {
3256  // For a declaration with parameters, eg. "T var(T());", suggest adding
3257  // parens around the first parameter to turn the declaration into a
3258  // variable declaration.
3259  SourceRange Range = FTI.Params[0].Param->getSourceRange();
3260  SourceLocation B = Range.getBegin();
3261  SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3262  // FIXME: Maybe we should suggest adding braces instead of parens
3263  // in C++11 for classes that don't have an initializer_list constructor.
3264  S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3265  << FixItHint::CreateInsertion(B, "(")
3266  << FixItHint::CreateInsertion(E, ")");
3267  } else {
3268  // For a declaration without parameters, eg. "T var();", suggest replacing
3269  // the parens with an initializer to turn the declaration into a variable
3270  // declaration.
3271  const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3272 
3273  // Empty parens mean value-initialization, and no parens mean
3274  // default initialization. These are equivalent if the default
3275  // constructor is user-provided or if zero-initialization is a
3276  // no-op.
3277  if (RD && RD->hasDefinition() &&
3278  (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3279  S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3280  << FixItHint::CreateRemoval(ParenRange);
3281  else {
3282  std::string Init =
3283  S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3284  if (Init.empty() && S.LangOpts.CPlusPlus11)
3285  Init = "{}";
3286  if (!Init.empty())
3287  S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3288  << FixItHint::CreateReplacement(ParenRange, Init);
3289  }
3290  }
3291 }
3292 
3293 /// Produce an appropriate diagnostic for a declarator with top-level
3294 /// parentheses.
3297  assert(Paren.Kind == DeclaratorChunk::Paren &&
3298  "do not have redundant top-level parentheses");
3299 
3300  // This is a syntactic check; we're not interested in cases that arise
3301  // during template instantiation.
3302  if (S.inTemplateInstantiation())
3303  return;
3304 
3305  // Check whether this could be intended to be a construction of a temporary
3306  // object in C++ via a function-style cast.
3307  bool CouldBeTemporaryObject =
3308  S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3309  !D.isInvalidType() && D.getIdentifier() &&
3311  (T->isRecordType() || T->isDependentType()) &&
3313 
3314  bool StartsWithDeclaratorId = true;
3315  for (auto &C : D.type_objects()) {
3316  switch (C.Kind) {
3318  if (&C == &Paren)
3319  continue;
3320  LLVM_FALLTHROUGH;
3322  StartsWithDeclaratorId = false;
3323  continue;
3324 
3326  if (!C.Arr.NumElts)
3327  CouldBeTemporaryObject = false;
3328  continue;
3329 
3331  // FIXME: Suppress the warning here if there is no initializer; we're
3332  // going to give an error anyway.
3333  // We assume that something like 'T (&x) = y;' is highly likely to not
3334  // be intended to be a temporary object.
3335  CouldBeTemporaryObject = false;
3336  StartsWithDeclaratorId = false;
3337  continue;
3338 
3340  // In a new-type-id, function chunks require parentheses.
3342  return;
3343  // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3344  // redundant-parens warning, but we don't know whether the function
3345  // chunk was syntactically valid as an expression here.
3346  CouldBeTemporaryObject = false;
3347  continue;
3348 
3351  case DeclaratorChunk::Pipe:
3352  // These cannot appear in expressions.
3353  CouldBeTemporaryObject = false;
3354  StartsWithDeclaratorId = false;
3355  continue;
3356  }
3357  }
3358 
3359  // FIXME: If there is an initializer, assume that this is not intended to be
3360  // a construction of a temporary object.
3361 
3362  // Check whether the name has already been declared; if not, this is not a
3363  // function-style cast.
3364  if (CouldBeTemporaryObject) {
3367  if (!S.LookupName(Result, S.getCurScope()))
3368  CouldBeTemporaryObject = false;
3369  Result.suppressDiagnostics();
3370  }
3371 
3372  SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3373 
3374  if (!CouldBeTemporaryObject) {
3375  // If we have A (::B), the parentheses affect the meaning of the program.
3376  // Suppress the warning in that case. Don't bother looking at the DeclSpec
3377  // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3378  // formally unambiguous.
3379  if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3380  for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3381  NNS = NNS->getPrefix()) {
3382  if (NNS->getKind() == NestedNameSpecifier::Global)
3383  return;
3384  }
3385  }
3386 
3387  S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3388  << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3389  << FixItHint::CreateRemoval(Paren.EndLoc);
3390  return;
3391  }
3392 
3393  S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3394  << ParenRange << D.getIdentifier();
3395  auto *RD = T->getAsCXXRecordDecl();
3396  if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3397  S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3398  << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3399  << D.getIdentifier();
3400  // FIXME: A cast to void is probably a better suggestion in cases where it's
3401  // valid (when there is no initializer and we're not in a condition).
3402  S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3405  S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3406  << FixItHint::CreateRemoval(Paren.Loc)
3407  << FixItHint::CreateRemoval(Paren.EndLoc);
3408 }
3409 
3410 /// Helper for figuring out the default CC for a function declarator type. If
3411 /// this is the outermost chunk, then we can determine the CC from the
3412 /// declarator context. If not, then this could be either a member function
3413 /// type or normal function type.
3415  Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3416  const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3417  assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3418 
3419  // Check for an explicit CC attribute.
3420  for (const ParsedAttr &AL : AttrList) {
3421  switch (AL.getKind()) {
3423  // Ignore attributes that don't validate or can't apply to the
3424  // function type. We'll diagnose the failure to apply them in
3425  // handleFunctionTypeAttr.
3426  CallingConv CC;
3427  if (!S.CheckCallingConvAttr(AL, CC) &&
3428  (!FTI.isVariadic || supportsVariadicCall(CC))) {
3429  return CC;
3430  }
3431  break;
3432  }
3433 
3434  default:
3435  break;
3436  }
3437  }
3438 
3439  bool IsCXXInstanceMethod = false;
3440 
3441  if (S.getLangOpts().CPlusPlus) {
3442  // Look inwards through parentheses to see if this chunk will form a
3443  // member pointer type or if we're the declarator. Any type attributes
3444  // between here and there will override the CC we choose here.
3445  unsigned I = ChunkIndex;
3446  bool FoundNonParen = false;
3447  while (I && !FoundNonParen) {
3448  --I;
3450  FoundNonParen = true;
3451  }
3452 
3453  if (FoundNonParen) {
3454  // If we're not the declarator, we're a regular function type unless we're
3455  // in a member pointer.
3456  IsCXXInstanceMethod =
3459  // This can only be a call operator for a lambda, which is an instance
3460  // method.
3461  IsCXXInstanceMethod = true;
3462  } else {
3463  // We're the innermost decl chunk, so must be a function declarator.
3464  assert(D.isFunctionDeclarator());
3465 
3466  // If we're inside a record, we're declaring a method, but it could be
3467  // explicitly or implicitly static.
3468  IsCXXInstanceMethod =
3471  !D.isStaticMember();
3472  }
3473  }
3474 
3476  IsCXXInstanceMethod);
3477 
3478  // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3479  // and AMDGPU targets, hence it cannot be treated as a calling
3480  // convention attribute. This is the simplest place to infer
3481  // calling convention for OpenCL kernels.
3482  if (S.getLangOpts().OpenCL) {
3483  for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3484  if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
3485  CC = CC_OpenCLKernel;
3486  break;
3487  }
3488  }
3489  }
3490 
3491  return CC;
3492 }
3493 
3494 namespace {
3495  /// A simple notion of pointer kinds, which matches up with the various
3496  /// pointer declarators.
3497  enum class SimplePointerKind {
3498  Pointer,
3499  BlockPointer,
3500  MemberPointer,
3501  Array,
3502  };
3503 } // end anonymous namespace
3504 
3506  switch (nullability) {
3508  if (!Ident__Nonnull)
3509  Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3510  return Ident__Nonnull;
3511 
3513  if (!Ident__Nullable)
3514  Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3515  return Ident__Nullable;
3516 
3518  if (!Ident__Null_unspecified)
3519  Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3520  return Ident__Null_unspecified;
3521  }
3522  llvm_unreachable("Unknown nullability kind.");
3523 }
3524 
3525 /// Retrieve the identifier "NSError".
3527  if (!Ident_NSError)
3528  Ident_NSError = PP.getIdentifierInfo("NSError");
3529 
3530  return Ident_NSError;
3531 }
3532 
3533 /// Check whether there is a nullability attribute of any kind in the given
3534 /// attribute list.
3535 static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3536  for (const ParsedAttr &AL : attrs) {
3537  if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3538  AL.getKind() == ParsedAttr::AT_TypeNullable ||
3539  AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3540  return true;
3541  }
3542 
3543  return false;
3544 }
3545 
3546 namespace {
3547  /// Describes the kind of a pointer a declarator describes.
3549  // Not a pointer.
3550  NonPointer,
3551  // Single-level pointer.
3552  SingleLevelPointer,
3553  // Multi-level pointer (of any pointer kind).
3554  MultiLevelPointer,
3555  // CFFooRef*
3556  MaybePointerToCFRef,
3557  // CFErrorRef*
3558  CFErrorRefPointer,
3559  // NSError**
3560  NSErrorPointerPointer,
3561  };
3562 
3563  /// Describes a declarator chunk wrapping a pointer that marks inference as
3564  /// unexpected.
3565  // These values must be kept in sync with diagnostics.
3567  /// Pointer is top-level.
3568  None = -1,
3569  /// Pointer is an array element.
3570  Array = 0,
3571  /// Pointer is the referent type of a C++ reference.
3572  Reference = 1
3573  };
3574 } // end anonymous namespace
3575 
3576 /// Classify the given declarator, whose type-specified is \c type, based on
3577 /// what kind of pointer it refers to.
3578 ///
3579 /// This is used to determine the default nullability.
3580 static PointerDeclaratorKind
3582  PointerWrappingDeclaratorKind &wrappingKind) {
3583  unsigned numNormalPointers = 0;
3584 
3585  // For any dependent type, we consider it a non-pointer.
3586  if (type->isDependentType())
3587  return PointerDeclaratorKind::NonPointer;
3588 
3589  // Look through the declarator chunks to identify pointers.
3590  for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3591  DeclaratorChunk &chunk = declarator.getTypeObject(i);
3592  switch (chunk.Kind) {
3594  if (numNormalPointers == 0)
3595  wrappingKind = PointerWrappingDeclaratorKind::Array;
3596  break;
3597 
3599  case DeclaratorChunk::Pipe:
3600  break;
3601 
3604  return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3605  : PointerDeclaratorKind::SingleLevelPointer;
3606 
3608  break;
3609 
3611  if (numNormalPointers == 0)
3612  wrappingKind = PointerWrappingDeclaratorKind::Reference;
3613  break;
3614 
3616  ++numNormalPointers;
3617  if (numNormalPointers > 2)
3618  return PointerDeclaratorKind::MultiLevelPointer;
3619  break;
3620  }
3621  }
3622 
3623  // Then, dig into the type specifier itself.
3624  unsigned numTypeSpecifierPointers = 0;
3625  do {
3626  // Decompose normal pointers.
3627  if (auto ptrType = type->getAs<PointerType>()) {
3628  ++numNormalPointers;
3629 
3630  if (numNormalPointers > 2)
3631  return PointerDeclaratorKind::MultiLevelPointer;
3632 
3633  type = ptrType->getPointeeType();
3634  ++numTypeSpecifierPointers;
3635  continue;
3636  }
3637 
3638  // Decompose block pointers.
3639  if (type->getAs<BlockPointerType>()) {
3640  return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3641  : PointerDeclaratorKind::SingleLevelPointer;
3642  }
3643 
3644  // Decompose member pointers.
3645  if (type->getAs<MemberPointerType>()) {
3646  return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3647  : PointerDeclaratorKind::SingleLevelPointer;
3648  }
3649 
3650  // Look at Objective-C object pointers.
3651  if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3652  ++numNormalPointers;
3653  ++numTypeSpecifierPointers;
3654 
3655  // If this is NSError**, report that.
3656  if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3657  if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3658  numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3659  return PointerDeclaratorKind::NSErrorPointerPointer;
3660  }
3661  }
3662 
3663  break;
3664  }
3665 
3666  // Look at Objective-C class types.
3667  if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3668  if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3669  if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3670  return PointerDeclaratorKind::NSErrorPointerPointer;
3671  }
3672 
3673  break;
3674  }
3675 
3676  // If at this point we haven't seen a pointer, we won't see one.
3677  if (numNormalPointers == 0)
3678  return PointerDeclaratorKind::NonPointer;
3679 
3680  if (auto recordType = type->getAs<RecordType>()) {
3681  RecordDecl *recordDecl = recordType->getDecl();
3682 
3683  bool isCFError = false;
3684  if (S.CFError) {
3685  // If we already know about CFError, test it directly.
3686  isCFError = (S.CFError == recordDecl);
3687  } else {
3688  // Check whether this is CFError, which we identify based on its bridge
3689  // to NSError. CFErrorRef used to be declared with "objc_bridge" but is
3690  // now declared with "objc_bridge_mutable", so look for either one of
3691  // the two attributes.
3692  if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3693  IdentifierInfo *bridgedType = nullptr;
3694  if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>())
3695  bridgedType = bridgeAttr->getBridgedType();
3696  else if (auto bridgeAttr =
3697  recordDecl->getAttr<ObjCBridgeMutableAttr>())
3698  bridgedType = bridgeAttr->getBridgedType();
3699 
3700  if (bridgedType == S.getNSErrorIdent()) {
3701  S.CFError = recordDecl;
3702  isCFError = true;
3703  }
3704  }
3705  }
3706 
3707  // If this is CFErrorRef*, report it as such.
3708  if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3709  return PointerDeclaratorKind::CFErrorRefPointer;
3710  }
3711  break;
3712  }
3713 
3714  break;
3715  } while (true);
3716 
3717  switch (numNormalPointers) {
3718  case 0:
3719  return PointerDeclaratorKind::NonPointer;
3720 
3721  case 1:
3722  return PointerDeclaratorKind::SingleLevelPointer;
3723 
3724  case 2:
3725  return PointerDeclaratorKind::MaybePointerToCFRef;
3726 
3727  default:
3728  return PointerDeclaratorKind::MultiLevelPointer;
3729  }
3730 }
3731 
3733  SourceLocation loc) {
3734  // If we're anywhere in a function, method, or closure context, don't perform
3735  // completeness checks.
3736  for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3737  if (ctx->isFunctionOrMethod())
3738  return FileID();
3739 
3740  if (ctx->isFileContext())
3741  break;
3742  }
3743 
3744  // We only care about the expansion location.
3745  loc = S.SourceMgr.getExpansionLoc(loc);
3746  FileID file = S.SourceMgr.getFileID(loc);
3747  if (file.isInvalid())
3748  return FileID();
3749 
3750  // Retrieve file information.
3751  bool invalid = false;
3752  const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3753  if (invalid || !sloc.isFile())
3754  return FileID();
3755 
3756  // We don't want to perform completeness checks on the main file or in
3757  // system headers.
3758  const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3759  if (fileInfo.getIncludeLoc().isInvalid())
3760  return FileID();
3761  if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3763  return FileID();
3764  }
3765 
3766  return file;
3767 }
3768 
3769 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
3770 /// taking into account whitespace before and after.
3772  SourceLocation PointerLoc,
3774  assert(PointerLoc.isValid());
3775  if (PointerLoc.isMacroID())
3776  return;
3777 
3778  SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
3779  if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
3780  return;
3781 
3782  const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
3783  if (!NextChar)
3784  return;
3785 
3786  SmallString<32> InsertionTextBuf{" "};
3787  InsertionTextBuf += getNullabilitySpelling(Nullability);
3788  InsertionTextBuf += " ";
3789  StringRef InsertionText = InsertionTextBuf.str();
3790 
3791  if (isWhitespace(*NextChar)) {
3792  InsertionText = InsertionText.drop_back();
3793  } else if (NextChar[-1] == '[') {
3794  if (NextChar[0] == ']')
3795  InsertionText = InsertionText.drop_back().drop_front();
3796  else
3797  InsertionText = InsertionText.drop_front();
3798  } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
3799  !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
3800  InsertionText = InsertionText.drop_back().drop_front();
3801  }
3802 
3803  Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
3804 }
3805 
3807  SimplePointerKind PointerKind,
3808  SourceLocation PointerLoc,
3809  SourceLocation PointerEndLoc) {
3810  assert(PointerLoc.isValid());
3811 
3812  if (PointerKind == SimplePointerKind::Array) {
3813  S.Diag(PointerLoc, diag::warn_nullability_missing_array);
3814  } else {
3815  S.Diag(PointerLoc, diag::warn_nullability_missing)
3816  << static_cast<unsigned>(PointerKind);
3817  }
3818 
3819  auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
3820  if (FixItLoc.isMacroID())
3821  return;
3822 
3823  auto addFixIt = [&](NullabilityKind Nullability) {
3824  auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
3825  Diag << static_cast<unsigned>(Nullability);
3826  Diag << static_cast<unsigned>(PointerKind);
3827  fixItNullability(S, Diag, FixItLoc, Nullability);
3828  };
3829  addFixIt(NullabilityKind::Nullable);
3830  addFixIt(NullabilityKind::NonNull);
3831 }
3832 
3833 /// Complains about missing nullability if the file containing \p pointerLoc
3834 /// has other uses of nullability (either the keywords or the \c assume_nonnull
3835 /// pragma).
3836 ///
3837 /// If the file has \e not seen other uses of nullability, this particular
3838 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
3839 static void
3841  SourceLocation pointerLoc,
3842  SourceLocation pointerEndLoc = SourceLocation()) {
3843  // Determine which file we're performing consistency checking for.
3844  FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3845  if (file.isInvalid())
3846  return;
3847 
3848  // If we haven't seen any type nullability in this file, we won't warn now
3849  // about anything.
3850  FileNullability &fileNullability = S.NullabilityMap[file];
3851  if (!fileNullability.SawTypeNullability) {
3852  // If this is the first pointer declarator in the file, and the appropriate
3853  // warning is on, record it in case we need to diagnose it retroactively.
3854  diag::kind diagKind;
3855  if (pointerKind == SimplePointerKind::Array)
3856  diagKind = diag::warn_nullability_missing_array;
3857  else
3858  diagKind = diag::warn_nullability_missing;
3859 
3860  if (fileNullability.PointerLoc.isInvalid() &&
3861  !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
3862  fileNullability.PointerLoc = pointerLoc;
3863  fileNullability.PointerEndLoc = pointerEndLoc;
3864  fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3865  }
3866 
3867  return;
3868  }
3869 
3870  // Complain about missing nullability.
3871  emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
3872 }
3873 
3874 /// Marks that a nullability feature has been used in the file containing
3875 /// \p loc.
3876 ///
3877 /// If this file already had pointer types in it that were missing nullability,
3878 /// the first such instance is retroactively diagnosed.
3879 ///
3880 /// \sa checkNullabilityConsistency
3883  if (file.isInvalid())
3884  return;
3885 
3886  FileNullability &fileNullability = S.NullabilityMap[file];
3887  if (fileNullability.SawTypeNullability)
3888  return;
3889  fileNullability.SawTypeNullability = true;
3890 
3891  // If we haven't seen any type nullability before, now we have. Retroactively
3892  // diagnose the first unannotated pointer, if there was one.
3893  if (fileNullability.PointerLoc.isInvalid())
3894  return;
3895 
3896  auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
3898  fileNullability.PointerEndLoc);
3899 }
3900 
3901 /// Returns true if any of the declarator chunks before \p endIndex include a
3902 /// level of indirection: array, pointer, reference, or pointer-to-member.
3903 ///
3904 /// Because declarator chunks are stored in outer-to-inner order, testing
3905 /// every chunk before \p endIndex is testing all chunks that embed the current
3906 /// chunk as part of their type.
3907 ///
3908 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
3909 /// end index, in which case all chunks are tested.
3910 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
3911  unsigned i = endIndex;
3912  while (i != 0) {
3913  // Walk outwards along the declarator chunks.
3914  --i;
3915  const DeclaratorChunk &DC = D.getTypeObject(i);
3916  switch (DC.Kind) {
3918  break;
3923  return true;
3926  case DeclaratorChunk::Pipe:
3927  // These are invalid anyway, so just ignore.
3928  break;
3929  }
3930  }
3931  return false;
3932 }
3933 
3935  return (Chunk.Kind == DeclaratorChunk::Pointer ||
3936  Chunk.Kind == DeclaratorChunk::Array);
3937 }
3938 
3939 template<typename AttrT>
3941  Attr.setUsedAsTypeAttr();
3942  return ::new (Ctx)
3943  AttrT(Attr.getRange(), Ctx, Attr.getAttributeSpellingListIndex());
3944 }
3945 
3947  NullabilityKind NK) {
3948  switch (NK) {
3950  return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
3951 
3953  return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
3954 
3956  return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
3957  }
3958  llvm_unreachable("unknown NullabilityKind");
3959 }
3960 
3961 // Diagnose whether this is a case with the multiple addr spaces.
3962 // Returns true if this is an invalid case.
3963 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
3964 // by qualifiers for two or more different address spaces."
3966  LangAS ASNew,
3967  SourceLocation AttrLoc) {
3968  if (ASOld != LangAS::Default) {
3969  if (ASOld != ASNew) {
3970  S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
3971  return true;
3972  }
3973  // Emit a warning if they are identical; it's likely unintended.
3974  S.Diag(AttrLoc,
3975  diag::warn_attribute_address_multiple_identical_qualifiers);
3976  }
3977  return false;
3978 }
3979 
3980 static TypeSourceInfo *
3981 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3982  QualType T, TypeSourceInfo *ReturnTypeInfo);
3983 
3984 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3985  QualType declSpecType,
3986  TypeSourceInfo *TInfo) {
3987  // The TypeSourceInfo that this function returns will not be a null type.
3988  // If there is an error, this function will fill in a dummy type as fallback.
3989  QualType T = declSpecType;
3990  Declarator &D = state.getDeclarator();
3991  Sema &S = state.getSema();
3992  ASTContext &Context = S.Context;
3993  const LangOptions &LangOpts = S.getLangOpts();
3994 
3995  // The name we're declaring, if any.
3996  DeclarationName Name;
3997  if (D.getIdentifier())
3998  Name = D.getIdentifier();
3999 
4000  // Does this declaration declare a typedef-name?
4001  bool IsTypedefName =
4005 
4006  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4007  bool IsQualifiedFunction = T->isFunctionProtoType() &&
4008  (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4009  T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4010 
4011  // If T is 'decltype(auto)', the only declarators we can have are parens
4012  // and at most one function declarator if this is a function declaration.
4013  // If T is a deduced class template specialization type, we can have no
4014  // declarator chunks at all.
4015  if (auto *DT = T->getAs<DeducedType>()) {
4016  const AutoType *AT = T->getAs<AutoType>();
4017  bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4018  if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4019  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4020  unsigned Index = E - I - 1;
4021  DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4022  unsigned DiagId = IsClassTemplateDeduction
4023  ? diag::err_deduced_class_template_compound_type
4024  : diag::err_decltype_auto_compound_type;
4025  unsigned DiagKind = 0;
4026  switch (DeclChunk.Kind) {
4028  // FIXME: Rejecting this is a little silly.
4029  if (IsClassTemplateDeduction) {
4030  DiagKind = 4;
4031  break;
4032  }
4033  continue;
4035  if (IsClassTemplateDeduction) {
4036  DiagKind = 3;
4037  break;
4038  }
4039  unsigned FnIndex;
4040  if (D.isFunctionDeclarationContext() &&
4041  D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4042  continue;
4043  DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4044  break;
4045  }
4049  DiagKind = 0;
4050  break;
4052  DiagKind = 1;
4053  break;
4055  DiagKind = 2;
4056  break;
4057  case DeclaratorChunk::Pipe:
4058  break;
4059  }
4060 
4061  S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4062  D.setInvalidType(true);
4063  break;
4064  }
4065  }
4066  }
4067 
4068  // Determine whether we should infer _Nonnull on pointer types.
4069  Optional<NullabilityKind> inferNullability;
4070  bool inferNullabilityCS = false;
4071  bool inferNullabilityInnerOnly = false;
4072  bool inferNullabilityInnerOnlyComplete = false;
4073 
4074  // Are we in an assume-nonnull region?
4075  bool inAssumeNonNullRegion = false;
4076  SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4077  if (assumeNonNullLoc.isValid()) {
4078  inAssumeNonNullRegion = true;
4079  recordNullabilitySeen(S, assumeNonNullLoc);
4080  }
4081 
4082  // Whether to complain about missing nullability specifiers or not.
4083  enum {
4084  /// Never complain.
4085  CAMN_No,
4086  /// Complain on the inner pointers (but not the outermost
4087  /// pointer).
4088  CAMN_InnerPointers,
4089  /// Complain about any pointers that don't have nullability
4090  /// specified or inferred.
4091  CAMN_Yes
4092  } complainAboutMissingNullability = CAMN_No;
4093  unsigned NumPointersRemaining = 0;
4094  auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4095 
4096  if (IsTypedefName) {
4097  // For typedefs, we do not infer any nullability (the default),
4098  // and we only complain about missing nullability specifiers on
4099  // inner pointers.
4100  complainAboutMissingNullability = CAMN_InnerPointers;
4101 
4102  if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4103  !T->getNullability(S.Context)) {
4104  // Note that we allow but don't require nullability on dependent types.
4105  ++NumPointersRemaining;
4106  }
4107 
4108  for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4109  DeclaratorChunk &chunk = D.getTypeObject(i);
4110  switch (chunk.Kind) {
4113  case DeclaratorChunk::Pipe:
4114  break;
4115 
4118  ++NumPointersRemaining;
4119  break;
4120 
4123  continue;
4124 
4126  ++NumPointersRemaining;
4127  continue;
4128  }
4129  }
4130  } else {
4131  bool isFunctionOrMethod = false;
4132  switch (auto context = state.getDeclarator().getContext()) {
4138  isFunctionOrMethod = true;
4139  LLVM_FALLTHROUGH;
4140 
4142  if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4143  complainAboutMissingNullability = CAMN_No;
4144  break;
4145  }
4146 
4147  // Weak properties are inferred to be nullable.
4148  if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
4149  inferNullability = NullabilityKind::Nullable;
4150  break;
4151  }
4152 
4153  LLVM_FALLTHROUGH;
4154 
4157  complainAboutMissingNullability = CAMN_Yes;
4158 
4159  // Nullability inference depends on the type and declarator.
4160  auto wrappingKind = PointerWrappingDeclaratorKind::None;
4161  switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4162  case PointerDeclaratorKind::NonPointer:
4163  case PointerDeclaratorKind::MultiLevelPointer:
4164  // Cannot infer nullability.
4165  break;
4166 
4167  case PointerDeclaratorKind::SingleLevelPointer:
4168  // Infer _Nonnull if we are in an assumes-nonnull region.
4169  if (inAssumeNonNullRegion) {
4170  complainAboutInferringWithinChunk = wrappingKind;
4171  inferNullability = NullabilityKind::NonNull;
4172  inferNullabilityCS =
4175  }
4176  break;
4177 
4178  case PointerDeclaratorKind::CFErrorRefPointer:
4179  case PointerDeclaratorKind::NSErrorPointerPointer:
4180  // Within a function or method signature, infer _Nullable at both
4181  // levels.
4182  if (isFunctionOrMethod && inAssumeNonNullRegion)
4183  inferNullability = NullabilityKind::Nullable;
4184  break;
4185 
4186  case PointerDeclaratorKind::MaybePointerToCFRef:
4187  if (isFunctionOrMethod) {
4188  // On pointer-to-pointer parameters marked cf_returns_retained or
4189  // cf_returns_not_retained, if the outer pointer is explicit then
4190  // infer the inner pointer as _Nullable.
4191  auto hasCFReturnsAttr =
4192  [](const ParsedAttributesView &AttrList) -> bool {
4193  return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4194  AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4195  };
4196  if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4197  if (hasCFReturnsAttr(D.getAttributes()) ||
4198  hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4199  hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4200  inferNullability = NullabilityKind::Nullable;
4201  inferNullabilityInnerOnly = true;
4202  }
4203  }
4204  }
4205  break;
4206  }
4207  break;
4208  }
4209 
4211  complainAboutMissingNullability = CAMN_Yes;
4212  break;
4213 
4231  // Don't infer in these contexts.
4232  break;
4233  }
4234  }
4235 
4236  // Local function that returns true if its argument looks like a va_list.
4237  auto isVaList = [&S](QualType T) -> bool {
4238  auto *typedefTy = T->getAs<TypedefType>();
4239  if (!typedefTy)
4240  return false;
4241  TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4242  do {
4243  if (typedefTy->getDecl() == vaListTypedef)
4244  return true;
4245  if (auto *name = typedefTy->getDecl()->getIdentifier())
4246  if (name->isStr("va_list"))
4247  return true;
4248  typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4249  } while (typedefTy);
4250  return false;
4251  };
4252 
4253  // Local function that checks the nullability for a given pointer declarator.
4254  // Returns true if _Nonnull was inferred.
4255  auto inferPointerNullability =
4256  [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4257  SourceLocation pointerEndLoc,
4258  ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4259  // We've seen a pointer.
4260  if (NumPointersRemaining > 0)
4261  --NumPointersRemaining;
4262 
4263  // If a nullability attribute is present, there's nothing to do.
4264  if (hasNullabilityAttr(attrs))
4265  return nullptr;
4266 
4267  // If we're supposed to infer nullability, do so now.
4268  if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4269  ParsedAttr::Syntax syntax = inferNullabilityCS
4272  ParsedAttr *nullabilityAttr = Pool.create(
4273  S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4274  nullptr, SourceLocation(), nullptr, 0, syntax);
4275 
4276  attrs.addAtEnd(nullabilityAttr);
4277 
4278  if (inferNullabilityCS) {
4279  state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4280  ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4281  }
4282 
4283  if (pointerLoc.isValid() &&
4284  complainAboutInferringWithinChunk !=
4286  auto Diag =
4287  S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4288  Diag << static_cast<int>(complainAboutInferringWithinChunk);
4290  }
4291 
4292  if (inferNullabilityInnerOnly)
4293  inferNullabilityInnerOnlyComplete = true;
4294  return nullabilityAttr;
4295  }
4296 
4297  // If we're supposed to complain about missing nullability, do so
4298  // now if it's truly missing.
4299  switch (complainAboutMissingNullability) {
4300  case CAMN_No:
4301  break;
4302 
4303  case CAMN_InnerPointers:
4304  if (NumPointersRemaining == 0)
4305  break;
4306  LLVM_FALLTHROUGH;
4307 
4308  case CAMN_Yes:
4309  checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4310  }
4311  return nullptr;
4312  };
4313 
4314  // If the type itself could have nullability but does not, infer pointer
4315  // nullability and perform consistency checking.
4316  if (S.CodeSynthesisContexts.empty()) {
4317  if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4318  !T->getNullability(S.Context)) {
4319  if (isVaList(T)) {
4320  // Record that we've seen a pointer, but do nothing else.
4321  if (NumPointersRemaining > 0)
4322  --NumPointersRemaining;
4323  } else {
4324  SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4325  if (T->isBlockPointerType())
4326  pointerKind = SimplePointerKind::BlockPointer;
4327  else if (T->isMemberPointerType())
4328  pointerKind = SimplePointerKind::MemberPointer;
4329 
4330  if (auto *attr = inferPointerNullability(
4331  pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4332  D.getDeclSpec().getEndLoc(),
4335  T = state.getAttributedType(
4336  createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4337  }
4338  }
4339  }
4340 
4341  if (complainAboutMissingNullability == CAMN_Yes &&
4342  T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4343  D.isPrototypeContext() &&
4345  checkNullabilityConsistency(S, SimplePointerKind::Array,
4347  }
4348  }
4349 
4350  bool ExpectNoDerefChunk =
4351  state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4352 
4353  // Walk the DeclTypeInfo, building the recursive type as we go.
4354  // DeclTypeInfos are ordered from the identifier out, which is
4355  // opposite of what we want :).
4356  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4357  unsigned chunkIndex = e - i - 1;
4358  state.setCurrentChunkIndex(chunkIndex);
4359  DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4360  IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4361  switch (DeclType.Kind) {
4363  if (i == 0)
4364  warnAboutRedundantParens(S, D, T);
4365  T = S.BuildParenType(T);
4366  break;
4368  // If blocks are disabled, emit an error.
4369  if (!LangOpts.Blocks)
4370  S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4371 
4372  // Handle pointer nullability.
4373  inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4374  DeclType.EndLoc, DeclType.getAttrs(),
4375  state.getDeclarator().getAttributePool());
4376 
4377  T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4378  if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4379  // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4380  // qualified with const.
4381  if (LangOpts.OpenCL)
4382  DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4383  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4384  }
4385  break;
4387  // Verify that we're not building a pointer to pointer to function with
4388  // exception specification.
4389  if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4390  S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4391  D.setInvalidType(true);
4392  // Build the type anyway.
4393  }
4394 
4395  // Handle pointer nullability
4396  inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4397  DeclType.EndLoc, DeclType.getAttrs(),
4398  state.getDeclarator().getAttributePool());
4399 
4400  if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4401  T = Context.getObjCObjectPointerType(T);
4402  if (DeclType.Ptr.TypeQuals)
4403  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4404  break;
4405  }
4406 
4407  // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4408  // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4409  // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4410  if (LangOpts.OpenCL) {
4411  if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4412  T->isBlockPointerType()) {
4413  S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4414  D.setInvalidType(true);
4415  }
4416  }
4417 
4418  T = S.BuildPointerType(T, DeclType.Loc, Name);
4419  if (DeclType.Ptr.TypeQuals)
4420  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4421  break;
4423  // Verify that we're not building a reference to pointer to function with
4424  // exception specification.
4425  if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4426  S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4427  D.setInvalidType(true);
4428  // Build the type anyway.
4429  }
4430  T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4431 
4432  if (DeclType.Ref.HasRestrict)
4433  T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4434  break;
4435  }
4436  case DeclaratorChunk::Array: {
4437  // Verify that we're not building an array of pointers to function with
4438  // exception specification.
4439  if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4440  S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4441  D.setInvalidType(true);
4442  // Build the type anyway.
4443  }
4444  DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4445  Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4447  if (ATI.isStar)
4448  ASM = ArrayType::Star;
4449  else if (ATI.hasStatic)
4450  ASM = ArrayType::Static;
4451  else
4452  ASM = ArrayType::Normal;
4453  if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4454  // FIXME: This check isn't quite right: it allows star in prototypes
4455  // for function definitions, and disallows some edge cases detailed
4456  // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4457  S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4458  ASM = ArrayType::Normal;
4459  D.setInvalidType(true);
4460  }
4461 
4462  // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4463  // shall appear only in a declaration of a function parameter with an
4464  // array type, ...
4465  if (ASM == ArrayType::Static || ATI.TypeQuals) {
4466  if (!(D.isPrototypeContext() ||
4468  S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4469  (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4470  // Remove the 'static' and the type qualifiers.
4471  if (ASM == ArrayType::Static)
4472  ASM = ArrayType::Normal;
4473  ATI.TypeQuals = 0;
4474  D.setInvalidType(true);
4475  }
4476 
4477  // C99 6.7.5.2p1: ... and then only in the outermost array type
4478  // derivation.
4479  if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4480  S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4481  (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4482  if (ASM == ArrayType::Static)
4483  ASM = ArrayType::Normal;
4484  ATI.TypeQuals = 0;
4485  D.setInvalidType(true);
4486  }
4487  }
4488  const AutoType *AT = T->getContainedAutoType();
4489  // Allow arrays of auto if we are a generic lambda parameter.
4490  // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4491  if (AT &&
4493  // We've already diagnosed this for decltype(auto).
4494  if (!AT->isDecltypeAuto())
4495  S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4496  << getPrintableNameForEntity(Name) << T;
4497  T = QualType();
4498  break;
4499  }
4500 
4501  // Array parameters can be marked nullable as well, although it's not
4502  // necessary if they're marked 'static'.
4503  if (complainAboutMissingNullability == CAMN_Yes &&
4504  !hasNullabilityAttr(DeclType.getAttrs()) &&
4505  ASM != ArrayType::Static &&
4506  D.isPrototypeContext() &&
4507  !hasOuterPointerLikeChunk(D, chunkIndex)) {
4508  checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4509  }
4510 
4511  T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4512  SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4513  break;
4514  }
4516  // If the function declarator has a prototype (i.e. it is not () and
4517  // does not have a K&R-style identifier list), then the arguments are part
4518  // of the type, otherwise the argument list is ().
4519  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4520  IsQualifiedFunction =
4522 
4523  // Check for auto functions and trailing return type and adjust the
4524  // return type accordingly.
4525  if (!D.isInvalidType()) {
4526  // trailing-return-type is only required if we're declaring a function,
4527  // and not, for instance, a pointer to a function.
4528  if (D.getDeclSpec().hasAutoTypeSpec() &&
4529  !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4530  if (!S.getLangOpts().CPlusPlus14) {
4533  ? diag::err_auto_missing_trailing_return
4534  : diag::err_deduced_return_type);
4535  T = Context.IntTy;
4536  D.setInvalidType(true);
4537  } else {
4539  diag::warn_cxx11_compat_deduced_return_type);
4540  }
4541  } else if (FTI.hasTrailingReturnType()) {
4542  // T must be exactly 'auto' at this point. See CWG issue 681.
4543  if (isa<ParenType>(T)) {
4544  S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4545  << T << D.getSourceRange();
4546  D.setInvalidType(true);
4547  } else if (D.getName().getKind() ==
4549  if (T != Context.DependentTy) {
4550  S.Diag(D.getDeclSpec().getBeginLoc(),
4551  diag::err_deduction_guide_with_complex_decl)
4552  << D.getSourceRange();
4553  D.setInvalidType(true);
4554  }
4556  (T.hasQualifiers() || !isa<AutoType>(T) ||
4557  cast<AutoType>(T)->getKeyword() !=
4560  diag::err_trailing_return_without_auto)
4561  << T << D.getDeclSpec().getSourceRange();
4562  D.setInvalidType(true);
4563  }
4564  T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4565  if (T.isNull()) {
4566  // An error occurred parsing the trailing return type.
4567  T = Context.IntTy;
4568  D.setInvalidType(true);
4569  }
4570  } else {
4571  // This function type is not the type of the entity being declared,
4572  // so checking the 'auto' is not the responsibility of this chunk.
4573  }
4574  }
4575 
4576  // C99 6.7.5.3p1: The return type may not be a function or array type.
4577  // For conversion functions, we'll diagnose this particular error later.
4578  if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4579  (D.getName().getKind() !=
4581  unsigned diagID = diag::err_func_returning_array_function;
4582  // Last processing chunk in block context means this function chunk
4583  // represents the block.
4584  if (chunkIndex == 0 &&
4586  diagID = diag::err_block_returning_array_function;
4587  S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4588  T = Context.IntTy;
4589  D.setInvalidType(true);
4590  }
4591 
4592  // Do not allow returning half FP value.
4593  // FIXME: This really should be in BuildFunctionType.
4594  if (T->isHalfType()) {
4595  if (S.getLangOpts().OpenCL) {
4596  if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4597  S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4598  << T << 0 /*pointer hint*/;
4599  D.setInvalidType(true);
4600  }
4601  } else if (!S.getLangOpts().HalfArgsAndReturns) {
4602  S.Diag(D.getIdentifierLoc(),
4603  diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4604  D.setInvalidType(true);
4605  }
4606  }
4607 
4608  if (LangOpts.OpenCL) {
4609  // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4610  // function.
4611  if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4612  T->isPipeType()) {
4613  S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4614  << T << 1 /*hint off*/;
4615  D.setInvalidType(true);
4616  }
4617  // OpenCL doesn't support variadic functions and blocks
4618  // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4619  // We also allow here any toolchain reserved identifiers.
4620  if (FTI.isVariadic &&
4621  !(D.getIdentifier() &&
4622  ((D.getIdentifier()->getName() == "printf" &&
4623  (LangOpts.OpenCLCPlusPlus || LangOpts.OpenCLVersion >= 120)) ||
4624  D.getIdentifier()->getName().startswith("__")))) {
4625  S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4626  D.setInvalidType(true);
4627  }
4628  }
4629 
4630  // Methods cannot return interface types. All ObjC objects are
4631  // passed by reference.
4632  if (T->isObjCObjectType()) {
4633  SourceLocation DiagLoc, FixitLoc;
4634  if (TInfo) {
4635  DiagLoc = TInfo->getTypeLoc().getBeginLoc();
4636  FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
4637  } else {
4638  DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4639  FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
4640  }
4641  S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4642  << 0 << T
4643  << FixItHint::CreateInsertion(FixitLoc, "*");
4644 
4645  T = Context.getObjCObjectPointerType(T);
4646  if (TInfo) {
4647  TypeLocBuilder TLB;
4648  TLB.pushFullCopy(TInfo->getTypeLoc());
4650  TLoc.setStarLoc(FixitLoc);
4651  TInfo = TLB.getTypeSourceInfo(Context, T);
4652  }
4653 
4654  D.setInvalidType(true);
4655  }
4656 
4657  // cv-qualifiers on return types are pointless except when the type is a
4658  // class type in C++.
4659  if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4660  !(S.getLangOpts().CPlusPlus &&
4661  (T->isDependentType() || T->isRecordType()))) {
4662  if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4664  // [6.9.1/3] qualified void return is invalid on a C
4665  // function definition. Apparently ok on declarations and
4666  // in C++ though (!)
4667  S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4668  } else
4669  diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4670  }
4671 
4672  // Objective-C ARC ownership qualifiers are ignored on the function
4673  // return type (by type canonicalization). Complain if this attribute
4674  // was written here.
4675  if (T.getQualifiers().hasObjCLifetime()) {
4676  SourceLocation AttrLoc;
4677  if (chunkIndex + 1 < D.getNumTypeObjects()) {
4678  DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4679  for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
4680  if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
4681  AttrLoc = AL.getLoc();
4682  break;
4683  }
4684  }
4685  }
4686  if (AttrLoc.isInvalid()) {
4687  for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4688  if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
4689  AttrLoc = AL.getLoc();
4690  break;
4691  }
4692  }
4693  }
4694 
4695  if (AttrLoc.isValid()) {
4696  // The ownership attributes are almost always written via
4697  // the predefined
4698  // __strong/__weak/__autoreleasing/__unsafe_unretained.
4699  if (AttrLoc.isMacroID())
4700  AttrLoc =
4702 
4703  S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4704  << T.getQualifiers().getObjCLifetime();
4705  }
4706  }
4707 
4708  if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4709  // C++ [dcl.fct]p6:
4710  // Types shall not be defined in return or parameter types.
4711  TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4712  S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4713  << Context.getTypeDeclType(Tag);
4714  }
4715 
4716  // Exception specs are not allowed in typedefs. Complain, but add it
4717  // anyway.
4718  if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
4719  S.Diag(FTI.getExceptionSpecLocBeg(),
4720  diag::err_exception_spec_in_typedef)
4723 
4724  // If we see "T var();" or "T var(T());" at block scope, it is probably
4725  // an attempt to initialize a variable, not a function declaration.
4726  if (FTI.isAmbiguous)
4727  warnAboutAmbiguousFunction(S, D, DeclType, T);
4728 
4730  getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
4731 
4732  if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
4733  && !LangOpts.OpenCL) {
4734  // Simple void foo(), where the incoming T is the result type.
4735  T = Context.getFunctionNoProtoType(T, EI);
4736  } else {
4737  // We allow a zero-parameter variadic function in C if the
4738  // function is marked with the "overloadable" attribute. Scan
4739  // for this attribute now.
4740  if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus)
4741  if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable))
4742  S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4743 
4744  if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4745  // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4746  // definition.
4747  S.Diag(FTI.Params[0].IdentLoc,
4748  diag::err_ident_list_in_fn_declaration);
4749  D.setInvalidType(true);
4750  // Recover by creating a K&R-style function type.
4751  T = Context.getFunctionNoProtoType(T, EI);
4752  break;
4753  }
4754 
4756  EPI.ExtInfo = EI;
4757  EPI.Variadic = FTI.isVariadic;
4761  : 0);
4762  EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4764  : RQ_RValue;
4765 
4766  // Otherwise, we have a function with a parameter list that is
4767  // potentially variadic.
4768  SmallVector<QualType, 16> ParamTys;
4769  ParamTys.reserve(FTI.NumParams);
4770 
4772  ExtParameterInfos(FTI.NumParams);
4773  bool HasAnyInterestingExtParameterInfos = false;
4774 
4775  for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4776  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4777  QualType ParamTy = Param->getType();
4778  assert(!ParamTy.isNull() && "Couldn't parse type?");
4779 
4780  // Look for 'void'. void is allowed only as a single parameter to a
4781  // function with no other parameters (C99 6.7.5.3p10). We record
4782  // int(void) as a FunctionProtoType with an empty parameter list.
4783  if (ParamTy->isVoidType()) {
4784  // If this is something like 'float(int, void)', reject it. 'void'
4785  // is an incomplete type (C99 6.2.5p19) and function decls cannot
4786  // have parameters of incomplete type.
4787  if (FTI.NumParams != 1 || FTI.isVariadic) {
4788  S.Diag(DeclType.Loc, diag::err_void_only_param);
4789  ParamTy = Context.IntTy;
4790  Param->setType(ParamTy);
4791  } else if (FTI.Params[i].Ident) {
4792  // Reject, but continue to parse 'int(void abc)'.
4793  S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4794  ParamTy = Context.IntTy;
4795  Param->setType(ParamTy);
4796  } else {
4797  // Reject, but continue to parse 'float(const void)'.
4798  if (ParamTy.hasQualifiers())
4799  S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4800 
4801  // Do not add 'void' to the list.
4802  break;
4803  }
4804  } else if (ParamTy->isHalfType()) {
4805  // Disallow half FP parameters.
4806  // FIXME: This really should be in BuildFunctionType.
4807  if (S.getLangOpts().OpenCL) {
4808  if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4809  S.Diag(Param->getLocation(),
4810  diag::err_opencl_half_param) << ParamTy;
4811  D.setInvalidType();
4812  Param->setInvalidDecl();
4813  }
4814  } else if (!S.getLangOpts().HalfArgsAndReturns) {
4815  S.Diag(Param->getLocation(),
4816  diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4817  D.setInvalidType();
4818  }
4819  } else if (!FTI.hasPrototype) {
4820  if (ParamTy->isPromotableIntegerType()) {
4821  ParamTy = Context.getPromotedIntegerType(ParamTy);
4822  Param->setKNRPromoted(true);
4823  } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4824  if (BTy->getKind() == BuiltinType::Float) {
4825  ParamTy = Context.DoubleTy;
4826  Param->setKNRPromoted(true);
4827  }
4828  }
4829  }
4830 
4831  if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4832  ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4833  HasAnyInterestingExtParameterInfos = true;
4834  }
4835 
4836  if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4837  ExtParameterInfos[i] =
4838  ExtParameterInfos[i].withABI(attr->getABI());
4839  HasAnyInterestingExtParameterInfos = true;
4840  }
4841 
4842  if (Param->hasAttr<PassObjectSizeAttr>()) {
4843  ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
4844  HasAnyInterestingExtParameterInfos = true;
4845  }
4846 
4847  if (Param->hasAttr<NoEscapeAttr>()) {
4848  ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
4849  HasAnyInterestingExtParameterInfos = true;
4850  }
4851 
4852  ParamTys.push_back(ParamTy);
4853  }
4854 
4855  if (HasAnyInterestingExtParameterInfos) {
4856  EPI.ExtParameterInfos = ExtParameterInfos.data();
4857  checkExtParameterInfos(S, ParamTys, EPI,
4858  [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4859  }
4860 
4861  SmallVector<QualType, 4> Exceptions;
4862  SmallVector<ParsedType, 2> DynamicExceptions;
4863  SmallVector<SourceRange, 2> DynamicExceptionRanges;
4864  Expr *NoexceptExpr = nullptr;
4865 
4866  if (FTI.getExceptionSpecType() == EST_Dynamic) {
4867  // FIXME: It's rather inefficient to have to split into two vectors
4868  // here.
4869  unsigned N = FTI.getNumExceptions();
4870  DynamicExceptions.reserve(N);
4871  DynamicExceptionRanges.reserve(N);
4872  for (unsigned I = 0; I != N; ++I) {
4873  DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4874  DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4875  }
4876  } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
4877  NoexceptExpr = FTI.NoexceptExpr;
4878  }
4879 
4881  FTI.getExceptionSpecType(),
4882  DynamicExceptions,
4883  DynamicExceptionRanges,
4884  NoexceptExpr,
4885  Exceptions,
4886  EPI.ExceptionSpec);
4887 
4888  // FIXME: Set address space from attrs for C++ mode here.
4889  // OpenCLCPlusPlus: A class member function has an address space.
4890  auto IsClassMember = [&]() {
4891  return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
4892  state.getDeclarator()
4893  .getCXXScopeSpec()
4894  .getScopeRep()
4895  ->getKind() == NestedNameSpecifier::TypeSpec) ||
4896  state.getDeclarator().getContext() ==
4898  };
4899 
4900  if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
4901  LangAS ASIdx = LangAS::Default;
4902  // Take address space attr if any and mark as invalid to avoid adding
4903  // them later while creating QualType.
4904  if (FTI.MethodQualifiers)
4905  for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
4906  LangAS ASIdxNew = attr.asOpenCLLangAS();
4907  if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
4908  attr.getLoc()))
4909  D.setInvalidType(true);
4910  else
4911  ASIdx = ASIdxNew;
4912  }
4913  // If a class member function's address space is not set, set it to
4914  // __generic.
4915  LangAS AS =
4916  (ASIdx == LangAS::Default ? LangAS::opencl_generic : ASIdx);
4917  EPI.TypeQuals.addAddressSpace(AS);
4918  }
4919  T = Context.getFunctionType(T, ParamTys, EPI);
4920  }
4921  break;
4922  }
4924  // The scope spec must refer to a class, or be dependent.
4925  CXXScopeSpec &SS = DeclType.Mem.Scope();
4926  QualType ClsType;
4927 
4928  // Handle pointer nullability.
4929  inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
4930  DeclType.EndLoc, DeclType.getAttrs(),
4931  state.getDeclarator().getAttributePool());
4932 
4933  if (SS.isInvalid()) {
4934  // Avoid emitting extra errors if we already errored on the scope.
4935  D.setInvalidType(true);
4936  } else if (S.isDependentScopeSpecifier(SS) ||
4937  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4938  NestedNameSpecifier *NNS = SS.getScopeRep();
4939  NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4940  switch (NNS->getKind()) {
4942  ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4943  NNS->getAsIdentifier());
4944  break;
4945 
4950  llvm_unreachable("Nested-name-specifier must name a type");
4951 
4954  ClsType = QualType(NNS->getAsType(), 0);
4955  // Note: if the NNS has a prefix and ClsType is a nondependent
4956  // TemplateSpecializationType, then the NNS prefix is NOT included
4957  // in ClsType; hence we wrap ClsType into an ElaboratedType.
4958  // NOTE: in particular, no wrap occurs if ClsType already is an
4959  // Elaborated, DependentName, or DependentTemplateSpecialization.
4960  if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4961  ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4962  break;
4963  }
4964  } else {
4965  S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4966  diag::err_illegal_decl_mempointer_in_nonclass)
4967  << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4968  << DeclType.Mem.Scope().getRange();
4969  D.setInvalidType(true);
4970  }
4971 
4972  if (!ClsType.isNull())
4973  T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4974  D.getIdentifier());
4975  if (T.isNull()) {
4976  T = Context.IntTy;
4977  D.setInvalidType(true);
4978  } else if (DeclType.Mem.TypeQuals) {
4979  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4980  }
4981  break;
4982  }
4983 
4984  case DeclaratorChunk::Pipe: {
4985  T = S.BuildReadPipeType(T, DeclType.Loc);
4986  processTypeAttrs(state, T, TAL_DeclSpec,
4988  break;
4989  }
4990  }
4991 
4992  if (T.isNull()) {
4993  D.setInvalidType(true);
4994  T = Context.IntTy;
4995  }
4996 
4997  // See if there are any attributes on this declarator chunk.
4998  processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
4999 
5000  if (DeclType.Kind != DeclaratorChunk::Paren) {
5001  if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5002  S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5003 
5004  ExpectNoDerefChunk = state.didParseNoDeref();
5005  }
5006  }
5007 
5008  if (ExpectNoDerefChunk)
5009  S.Diag(state.getDeclarator().getBeginLoc(),
5010  diag::warn_noderef_on_non_pointer_or_array);
5011 
5012  // GNU warning -Wstrict-prototypes
5013  // Warn if a function declaration is without a prototype.
5014  // This warning is issued for all kinds of unprototyped function
5015  // declarations (i.e. function type typedef, function pointer etc.)
5016  // C99 6.7.5.3p14:
5017  // The empty list in a function declarator that is not part of a definition
5018  // of that function specifies that no information about the number or types
5019  // of the parameters is supplied.
5020  if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) {
5021  bool IsBlock = false;
5022  for (const DeclaratorChunk &DeclType : D.type_objects()) {
5023  switch (DeclType.Kind) {
5025  IsBlock = true;
5026  break;
5028  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5029  // We supress the warning when there's no LParen location, as this
5030  // indicates the declaration was an implicit declaration, which gets
5031  // warned about separately via -Wimplicit-function-declaration.
5032  if (FTI.NumParams == 0 && !FTI.isVariadic && FTI.getLParenLoc().isValid())
5033  S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5034  << IsBlock
5035  << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5036  IsBlock = false;
5037  break;
5038  }
5039  default:
5040  break;
5041  }
5042  }
5043  }
5044 
5045  assert(!T.isNull() && "T must not be null after this point");
5046 
5047  if (LangOpts.CPlusPlus && T->isFunctionType()) {
5048  const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5049  assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5050 
5051  // C++ 8.3.5p4:
5052  // A cv-qualifier-seq shall only be part of the function type
5053  // for a nonstatic member function, the function type to which a pointer
5054  // to member refers, or the top-level function type of a function typedef
5055  // declaration.
5056  //
5057  // Core issue 547 also allows cv-qualifiers on function types that are
5058  // top-level template type arguments.
5059  enum { NonMember, Member, DeductionGuide } Kind = NonMember;
5061  Kind = DeductionGuide;
5062  else if (!D.getCXXScopeSpec().isSet()) {
5066  Kind = Member;
5067  } else {
5069  if (!DC || DC->isRecord())
5070  Kind = Member;
5071  }
5072 
5073  // C++11 [dcl.fct]p6 (w/DR1417):
5074  // An attempt to specify a function type with a cv-qualifier-seq or a
5075  // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5076  // - the function type for a non-static member function,
5077  // - the function type to which a pointer to member refers,
5078  // - the top-level function type of a function typedef declaration or
5079  // alias-declaration,
5080  // - the type-id in the default argument of a type-parameter, or
5081  // - the type-id of a template-argument for a type-parameter
5082  //
5083  // FIXME: Checking this here is insufficient. We accept-invalid on:
5084  //
5085  // template<typename T> struct S { void f(T); };
5086  // S<int() const> s;
5087  //
5088  // ... for instance.
5089  if (IsQualifiedFunction &&
5090  !(Kind == Member &&
5092  !IsTypedefName &&
5095  SourceLocation Loc = D.getBeginLoc();
5096  SourceRange RemovalRange;
5097  unsigned I;
5098  if (D.isFunctionDeclarator(I)) {
5099  SmallVector<SourceLocation, 4> RemovalLocs;
5100  const DeclaratorChunk &Chunk = D.getTypeObject(I);
5101  assert(Chunk.Kind == DeclaratorChunk::Function);
5102 
5103  if (Chunk.Fun.hasRefQualifier())
5104  RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5105 
5106  if (Chunk.Fun.hasMethodTypeQualifiers())
5108  [&](DeclSpec::TQ TypeQual, StringRef QualName,
5109  SourceLocation SL) { RemovalLocs.push_back(SL); });
5110 
5111  if (!RemovalLocs.empty()) {
5112  llvm::sort(RemovalLocs,
5114  RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5115  Loc = RemovalLocs.front();
5116  }
5117  }
5118 
5119  S.Diag(Loc, diag::err_invalid_qualified_function_type)
5120  << Kind << D.isFunctionDeclarator() << T
5122  << FixItHint::CreateRemoval(RemovalRange);
5123 
5124  // Strip the cv-qualifiers and ref-qualifiers from the type.
5127  EPI.RefQualifier = RQ_None;
5128 
5129  T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5130  EPI);
5131  // Rebuild any parens around the identifier in the function type.
5132  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5134  break;
5135  T = S.BuildParenType(T);
5136  }
5137  }
5138  }
5139 
5140  // Apply any undistributed attributes from the declarator.
5142 
5143  // Diagnose any ignored type attributes.
5144  state.diagnoseIgnoredTypeAttrs(T);
5145 
5146  // C++0x [dcl.constexpr]p9:
5147  // A constexpr specifier used in an object declaration declares the object
5148  // as const.
5149  if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
5150  T.addConst();
5151  }
5152 
5153  // If there was an ellipsis in the declarator, the declaration declares a
5154  // parameter pack whose type may be a pack expansion type.
5155  if (D.hasEllipsis()) {
5156  // C++0x [dcl.fct]p13:
5157  // A declarator-id or abstract-declarator containing an ellipsis shall
5158  // only be used in a parameter-declaration. Such a parameter-declaration
5159  // is a parameter pack (14.5.3). [...]
5160  switch (D.getContext()) {
5163  // C++0x [dcl.fct]p13:
5164  // [...] When it is part of a parameter-declaration-clause, the
5165  // parameter pack is a function parameter pack (14.5.3). The type T
5166  // of the declarator-id of the function parameter pack shall contain
5167  // a template parameter pack; each template parameter pack in T is
5168  // expanded by the function parameter pack.
5169  //
5170  // We represent function parameter packs as function parameters whose
5171  // type is a pack expansion.
5172  if (!T->containsUnexpandedParameterPack()) {
5173  S.Diag(D.getEllipsisLoc(),
5174  diag::err_function_parameter_pack_without_parameter_packs)
5175  << T << D.getSourceRange();
5177  } else {
5178  T = Context.getPackExpansionType(T, None);
5179  }
5180  break;
5182  // C++0x [temp.param]p15:
5183  // If a template-parameter is a [...] is a parameter-declaration that
5184  // declares a parameter pack (8.3.5), then the template-parameter is a
5185  // template parameter pack (14.5.3).
5186  //
5187  // Note: core issue 778 clarifies that, if there are any unexpanded
5188  // parameter packs in the type of the non-type template parameter, then
5189  // it expands those parameter packs.
5191  T = Context.getPackExpansionType(T, None);
5192  else
5193  S.Diag(D.getEllipsisLoc(),
5194  LangOpts.CPlusPlus11
5195  ? diag::warn_cxx98_compat_variadic_templates
5196  : diag::ext_variadic_templates);
5197  break;
5198 
5201  case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic
5202  // here?
5203  case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic
5204  // here?
5224  // FIXME: We may want to allow parameter packs in block-literal contexts
5225  // in the future.
5226  S.Diag(D.getEllipsisLoc(),
5227  diag::err_ellipsis_in_declarator_not_parameter);
5229  break;
5230  }
5231  }
5232 
5233  assert(!T.isNull() && "T must not be null at the end of this function");
5234  if (D.isInvalidType())
5235  return Context.getTrivialTypeSourceInfo(T);
5236 
5237  return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5238 }
5239 
5240 /// GetTypeForDeclarator - Convert the type for the specified
5241 /// declarator to Type instances.
5242 ///
5243 /// The result of this call will never be null, but the associated
5244 /// type may be a null type if there's an unrecoverable error.
5246  // Determine the type of the declarator. Not all forms of declarator
5247  // have a type.
5248 
5249  TypeProcessingState state(*this, D);
5250 
5251  TypeSourceInfo *ReturnTypeInfo = nullptr;
5252  QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5253  if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5254  inferARCWriteback(state, T);
5255 
5256  return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5257 }
5258 
5260  QualType &declSpecTy,
5261  Qualifiers::ObjCLifetime ownership) {
5262  if (declSpecTy->isObjCRetainableType() &&
5263  declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5264  Qualifiers qs;
5265  qs.addObjCLifetime(ownership);
5266  declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5267  }
5268 }
5269 
5270 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5271  Qualifiers::ObjCLifetime ownership,
5272  unsigned chunkIndex) {
5273  Sema &S = state.getSema();
5274  Declarator &D = state.getDeclarator();
5275 
5276  // Look for an explicit lifetime attribute.
5277  DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5278  if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5279  return;
5280 
5281  const char *attrStr = nullptr;
5282  switch (ownership) {
5283  case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5284  case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5285  case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5286  case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5287  case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5288  }
5289 
5290  IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5291  Arg->Ident = &S.Context.Idents.get(attrStr);
5292  Arg->Loc = SourceLocation();
5293 
5294  ArgsUnion Args(Arg);
5295 
5296  // If there wasn't one, add one (with an invalid source location
5297  // so that we don't make an AttributedType for it).
5298  ParsedAttr *attr = D.getAttributePool().create(
5299  &S.Context.Idents.get("objc_ownership"), SourceLocation(),
5300  /*scope*/ nullptr, SourceLocation(),
5301  /*args*/ &Args, 1, ParsedAttr::AS_GNU);
5302  chunk.getAttrs().addAtEnd(attr);
5303  // TODO: mark whether we did this inference?
5304 }
5305 
5306 /// Used for transferring ownership in casts resulting in l-values.
5307 static void transferARCOwnership(TypeProcessingState &state,
5308  QualType &declSpecTy,
5309  Qualifiers::ObjCLifetime ownership) {
5310  Sema &S = state.getSema();
5311  Declarator &D = state.getDeclarator();
5312 
5313  int inner = -1;
5314  bool hasIndirection = false;
5315  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5316  DeclaratorChunk &chunk = D.getTypeObject(i);
5317  switch (chunk.Kind) {
5319  // Ignore parens.
5320  break;
5321 
5325  if (inner != -1)
5326  hasIndirection = true;
5327  inner = i;
5328  break;
5329 
5331  if (inner != -1)
5332  transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5333  return;
5334 
5337  case DeclaratorChunk::Pipe:
5338  return;
5339  }
5340  }
5341 
5342  if (inner == -1)
5343  return;
5344 
5345  DeclaratorChunk &chunk = D.getTypeObject(inner);
5346  if (chunk.Kind == DeclaratorChunk::Pointer) {
5347  if (declSpecTy->isObjCRetainableType())
5348  return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5349  if (declSpecTy->isObjCObjectType() && hasIndirection)
5350  return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5351  } else {
5352  assert(chunk.Kind == DeclaratorChunk::Array ||
5353  chunk.Kind == DeclaratorChunk::Reference);
5354  return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5355  }
5356 }
5357 
5359  TypeProcessingState state(*this, D);
5360 
5361  TypeSourceInfo *ReturnTypeInfo = nullptr;
5362  QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5363 
5364  if (getLangOpts().ObjC) {
5365  Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5366  if (ownership != Qualifiers::OCL_None)
5367  transferARCOwnership(state, declSpecTy, ownership);
5368  }
5369 
5370  return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5371 }
5372 
5374  TypeProcessingState &State) {
5375  TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5376 }
5377 
5378 namespace {
5379  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5380  ASTContext &Context;
5381  TypeProcessingState &State;
5382  const DeclSpec &DS;
5383 
5384  public:
5385  TypeSpecLocFiller(ASTContext &Context, TypeProcessingState &State,
5386  const DeclSpec &DS)
5387  : Context(Context), State(State), DS(DS) {}
5388 
5389  void VisitAttributedTypeLoc(AttributedTypeLoc