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