clang  8.0.0
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"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/Support/ErrorHandling.h"
39 
40 using namespace clang;
41 
46 };
47 
48 /// isOmittedBlockReturnType - Return true if this declarator is missing a
49 /// return type because this is a omitted return type on a block literal.
50 static bool isOmittedBlockReturnType(const Declarator &D) {
53  return false;
54 
55  if (D.getNumTypeObjects() == 0)
56  return true; // ^{ ... }
57 
58  if (D.getNumTypeObjects() == 1 &&
60  return true; // ^(int X, float Y) { ... }
61 
62  return false;
63 }
64 
65 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
66 /// doesn't apply to the given type.
67 static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
68  QualType type) {
69  TypeDiagSelector WhichType;
70  bool useExpansionLoc = true;
71  switch (attr.getKind()) {
72  case ParsedAttr::AT_ObjCGC:
73  WhichType = TDS_Pointer;
74  break;
75  case ParsedAttr::AT_ObjCOwnership:
76  WhichType = TDS_ObjCObjOrBlock;
77  break;
78  default:
79  // Assume everything else was a function attribute.
80  WhichType = TDS_Function;
81  useExpansionLoc = false;
82  break;
83  }
84 
85  SourceLocation loc = attr.getLoc();
86  StringRef name = attr.getName()->getName();
87 
88  // The GC attributes are usually written with macros; special-case them.
89  IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
90  : nullptr;
91  if (useExpansionLoc && loc.isMacroID() && II) {
92  if (II->isStr("strong")) {
93  if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
94  } else if (II->isStr("weak")) {
95  if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
96  }
97  }
98 
99  S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
100  << type;
101 }
102 
103 // objc_gc applies to Objective-C pointers or, otherwise, to the
104 // smallest available pointer type (i.e. 'void*' in 'void**').
105 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
106  case ParsedAttr::AT_ObjCGC: \
107  case ParsedAttr::AT_ObjCOwnership
108 
109 // Calling convention attributes.
110 #define CALLING_CONV_ATTRS_CASELIST \
111  case ParsedAttr::AT_CDecl: \
112  case ParsedAttr::AT_FastCall: \
113  case ParsedAttr::AT_StdCall: \
114  case ParsedAttr::AT_ThisCall: \
115  case ParsedAttr::AT_RegCall: \
116  case ParsedAttr::AT_Pascal: \
117  case ParsedAttr::AT_SwiftCall: \
118  case ParsedAttr::AT_VectorCall: \
119  case ParsedAttr::AT_AArch64VectorPcs: \
120  case ParsedAttr::AT_MSABI: \
121  case ParsedAttr::AT_SysVABI: \
122  case ParsedAttr::AT_Pcs: \
123  case ParsedAttr::AT_IntelOclBicc: \
124  case ParsedAttr::AT_PreserveMost: \
125  case ParsedAttr::AT_PreserveAll
126 
127 // Function type attributes.
128 #define FUNCTION_TYPE_ATTRS_CASELIST \
129  case ParsedAttr::AT_NSReturnsRetained: \
130  case ParsedAttr::AT_NoReturn: \
131  case ParsedAttr::AT_Regparm: \
132  case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
133  case ParsedAttr::AT_AnyX86NoCfCheck: \
134  CALLING_CONV_ATTRS_CASELIST
135 
136 // Microsoft-specific type qualifiers.
137 #define MS_TYPE_ATTRS_CASELIST \
138  case ParsedAttr::AT_Ptr32: \
139  case ParsedAttr::AT_Ptr64: \
140  case ParsedAttr::AT_SPtr: \
141  case ParsedAttr::AT_UPtr
142 
143 // Nullability qualifiers.
144 #define NULLABILITY_TYPE_ATTRS_CASELIST \
145  case ParsedAttr::AT_TypeNonNull: \
146  case ParsedAttr::AT_TypeNullable: \
147  case ParsedAttr::AT_TypeNullUnspecified
148 
149 namespace {
150  /// An object which stores processing state for the entire
151  /// GetTypeForDeclarator process.
152  class TypeProcessingState {
153  Sema &sema;
154 
155  /// The declarator being processed.
156  Declarator &declarator;
157 
158  /// The index of the declarator chunk we're currently processing.
159  /// May be the total number of valid chunks, indicating the
160  /// DeclSpec.
161  unsigned chunkIndex;
162 
163  /// Whether there are non-trivial modifications to the decl spec.
164  bool trivial;
165 
166  /// Whether we saved the attributes in the decl spec.
167  bool hasSavedAttrs;
168 
169  /// The original set of attributes on the DeclSpec.
170  SmallVector<ParsedAttr *, 2> savedAttrs;
171 
172  /// A list of attributes to diagnose the uselessness of when the
173  /// processing is complete.
174  SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
175 
176  /// Attributes corresponding to AttributedTypeLocs that we have not yet
177  /// populated.
178  // FIXME: The two-phase mechanism by which we construct Types and fill
179  // their TypeLocs makes it hard to correctly assign these. We keep the
180  // attributes in creation order as an attempt to make them line up
181  // properly.
182  using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
183  SmallVector<TypeAttrPair, 8> AttrsForTypes;
184  bool AttrsForTypesSorted = true;
185 
186  /// Flag to indicate we parsed a noderef attribute. This is used for
187  /// validating that noderef was used on a pointer or array.
188  bool parsedNoDeref;
189 
190  public:
191  TypeProcessingState(Sema &sema, Declarator &declarator)
192  : sema(sema), declarator(declarator),
193  chunkIndex(declarator.getNumTypeObjects()), trivial(true),
194  hasSavedAttrs(false), parsedNoDeref(false) {}
195 
196  Sema &getSema() const {
197  return sema;
198  }
199 
200  Declarator &getDeclarator() const {
201  return declarator;
202  }
203 
204  bool isProcessingDeclSpec() const {
205  return chunkIndex == declarator.getNumTypeObjects();
206  }
207 
208  unsigned getCurrentChunkIndex() const {
209  return chunkIndex;
210  }
211 
212  void setCurrentChunkIndex(unsigned idx) {
213  assert(idx <= declarator.getNumTypeObjects());
214  chunkIndex = idx;
215  }
216 
217  ParsedAttributesView &getCurrentAttributes() const {
218  if (isProcessingDeclSpec())
219  return getMutableDeclSpec().getAttributes();
220  return declarator.getTypeObject(chunkIndex).getAttrs();
221  }
222 
223  /// Save the current set of attributes on the DeclSpec.
224  void saveDeclSpecAttrs() {
225  // Don't try to save them multiple times.
226  if (hasSavedAttrs) return;
227 
228  DeclSpec &spec = getMutableDeclSpec();
229  for (ParsedAttr &AL : spec.getAttributes())
230  savedAttrs.push_back(&AL);
231  trivial &= savedAttrs.empty();
232  hasSavedAttrs = true;
233  }
234 
235  /// Record that we had nowhere to put the given type attribute.
236  /// We will diagnose such attributes later.
237  void addIgnoredTypeAttr(ParsedAttr &attr) {
238  ignoredTypeAttrs.push_back(&attr);
239  }
240 
241  /// Diagnose all the ignored type attributes, given that the
242  /// declarator worked out to the given type.
243  void diagnoseIgnoredTypeAttrs(QualType type) const {
244  for (auto *Attr : ignoredTypeAttrs)
245  diagnoseBadTypeAttribute(getSema(), *Attr, type);
246  }
247 
248  /// Get an attributed type for the given attribute, and remember the Attr
249  /// object so that we can attach it to the AttributedTypeLoc.
250  QualType getAttributedType(Attr *A, QualType ModifiedType,
251  QualType EquivType) {
252  QualType T =
253  sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
254  AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
255  AttrsForTypesSorted = false;
256  return T;
257  }
258 
259  /// Extract and remove the Attr* for a given attributed type.
260  const Attr *takeAttrForAttributedType(const AttributedType *AT) {
261  if (!AttrsForTypesSorted) {
262  std::stable_sort(AttrsForTypes.begin(), AttrsForTypes.end(),
263  [](const TypeAttrPair &A, const TypeAttrPair &B) {
264  return A.first < B.first;
265  });
266  AttrsForTypesSorted = true;
267  }
268 
269  // FIXME: This is quadratic if we have lots of reuses of the same
270  // attributed type.
271  for (auto It = std::partition_point(
272  AttrsForTypes.begin(), AttrsForTypes.end(),
273  [=](const TypeAttrPair &A) { return A.first < AT; });
274  It != AttrsForTypes.end() && It->first == AT; ++It) {
275  if (It->second) {
276  const Attr *Result = It->second;
277  It->second = nullptr;
278  return Result;
279  }
280  }
281 
282  llvm_unreachable("no Attr* for AttributedType*");
283  }
284 
285  void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
286 
287  bool didParseNoDeref() const { return parsedNoDeref; }
288 
289  ~TypeProcessingState() {
290  if (trivial) return;
291 
292  restoreDeclSpecAttrs();
293  }
294 
295  private:
296  DeclSpec &getMutableDeclSpec() const {
297  return const_cast<DeclSpec&>(declarator.getDeclSpec());
298  }
299 
300  void restoreDeclSpecAttrs() {
301  assert(hasSavedAttrs);
302 
303  getMutableDeclSpec().getAttributes().clearListOnly();
304  for (ParsedAttr *AL : savedAttrs)
305  getMutableDeclSpec().getAttributes().addAtEnd(AL);
306  }
307  };
308 } // end anonymous namespace
309 
311  ParsedAttributesView &fromList,
312  ParsedAttributesView &toList) {
313  fromList.remove(&attr);
314  toList.addAtEnd(&attr);
315 }
316 
317 /// The location of a type attribute.
319  /// The attribute is in the decl-specifier-seq.
321  /// The attribute is part of a DeclaratorChunk.
323  /// The attribute is immediately after the declaration's name.
325 };
326 
327 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
329 
330 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
331  QualType &type);
332 
333 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
334  ParsedAttr &attr, QualType &type);
335 
336 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
337  QualType &type);
338 
339 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
340  ParsedAttr &attr, QualType &type);
341 
342 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
343  ParsedAttr &attr, QualType &type) {
344  if (attr.getKind() == ParsedAttr::AT_ObjCGC)
345  return handleObjCGCTypeAttr(state, attr, type);
346  assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
347  return handleObjCOwnershipTypeAttr(state, attr, type);
348 }
349 
350 /// Given the index of a declarator chunk, check whether that chunk
351 /// directly specifies the return type of a function and, if so, find
352 /// an appropriate place for it.
353 ///
354 /// \param i - a notional index which the search will start
355 /// immediately inside
356 ///
357 /// \param onlyBlockPointers Whether we should only look into block
358 /// pointer types (vs. all pointer types).
360  unsigned i,
361  bool onlyBlockPointers) {
362  assert(i <= declarator.getNumTypeObjects());
363 
364  DeclaratorChunk *result = nullptr;
365 
366  // First, look inwards past parens for a function declarator.
367  for (; i != 0; --i) {
368  DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
369  switch (fnChunk.Kind) {
371  continue;
372 
373  // If we find anything except a function, bail out.
380  return result;
381 
382  // If we do find a function declarator, scan inwards from that,
383  // looking for a (block-)pointer declarator.
385  for (--i; i != 0; --i) {
386  DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
387  switch (ptrChunk.Kind) {
393  continue;
394 
397  if (onlyBlockPointers)
398  continue;
399 
400  LLVM_FALLTHROUGH;
401 
403  result = &ptrChunk;
404  goto continue_outer;
405  }
406  llvm_unreachable("bad declarator chunk kind");
407  }
408 
409  // If we run out of declarators doing that, we're done.
410  return result;
411  }
412  llvm_unreachable("bad declarator chunk kind");
413 
414  // Okay, reconsider from our new point.
415  continue_outer: ;
416  }
417 
418  // Ran out of chunks, bail out.
419  return result;
420 }
421 
422 /// Given that an objc_gc attribute was written somewhere on a
423 /// declaration *other* than on the declarator itself (for which, use
424 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
425 /// didn't apply in whatever position it was written in, try to move
426 /// it to a more appropriate position.
427 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
428  ParsedAttr &attr, QualType type) {
429  Declarator &declarator = state.getDeclarator();
430 
431  // Move it to the outermost normal or block pointer declarator.
432  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
433  DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
434  switch (chunk.Kind) {
437  // But don't move an ARC ownership attribute to the return type
438  // of a block.
439  DeclaratorChunk *destChunk = nullptr;
440  if (state.isProcessingDeclSpec() &&
441  attr.getKind() == ParsedAttr::AT_ObjCOwnership)
442  destChunk = maybeMovePastReturnType(declarator, i - 1,
443  /*onlyBlockPointers=*/true);
444  if (!destChunk) destChunk = &chunk;
445 
446  moveAttrFromListToList(attr, state.getCurrentAttributes(),
447  destChunk->getAttrs());
448  return;
449  }
450 
453  continue;
454 
455  // We may be starting at the return type of a block.
457  if (state.isProcessingDeclSpec() &&
458  attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
460  declarator, i,
461  /*onlyBlockPointers=*/true)) {
462  moveAttrFromListToList(attr, state.getCurrentAttributes(),
463  dest->getAttrs());
464  return;
465  }
466  }
467  goto error;
468 
469  // Don't walk through these.
473  goto error;
474  }
475  }
476  error:
477 
478  diagnoseBadTypeAttribute(state.getSema(), attr, type);
479 }
480 
481 /// Distribute an objc_gc type attribute that was written on the
482 /// declarator.
484  TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
485  Declarator &declarator = state.getDeclarator();
486 
487  // objc_gc goes on the innermost pointer to something that's not a
488  // pointer.
489  unsigned innermost = -1U;
490  bool considerDeclSpec = true;
491  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
492  DeclaratorChunk &chunk = declarator.getTypeObject(i);
493  switch (chunk.Kind) {
496  innermost = i;
497  continue;
498 
504  continue;
505 
507  considerDeclSpec = false;
508  goto done;
509  }
510  }
511  done:
512 
513  // That might actually be the decl spec if we weren't blocked by
514  // anything in the declarator.
515  if (considerDeclSpec) {
516  if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
517  // Splice the attribute into the decl spec. Prevents the
518  // attribute from being applied multiple times and gives
519  // the source-location-filler something to work with.
520  state.saveDeclSpecAttrs();
521  moveAttrFromListToList(attr, declarator.getAttributes(),
522  declarator.getMutableDeclSpec().getAttributes());
523  return;
524  }
525  }
526 
527  // Otherwise, if we found an appropriate chunk, splice the attribute
528  // into it.
529  if (innermost != -1U) {
530  moveAttrFromListToList(attr, declarator.getAttributes(),
531  declarator.getTypeObject(innermost).getAttrs());
532  return;
533  }
534 
535  // Otherwise, diagnose when we're done building the type.
536  declarator.getAttributes().remove(&attr);
537  state.addIgnoredTypeAttr(attr);
538 }
539 
540 /// A function type attribute was written somewhere in a declaration
541 /// *other* than on the declarator itself or in the decl spec. Given
542 /// that it didn't apply in whatever position it was written in, try
543 /// to move it to a more appropriate position.
544 static void distributeFunctionTypeAttr(TypeProcessingState &state,
545  ParsedAttr &attr, QualType type) {
546  Declarator &declarator = state.getDeclarator();
547 
548  // Try to push the attribute from the return type of a function to
549  // the function itself.
550  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
551  DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
552  switch (chunk.Kind) {
554  moveAttrFromListToList(attr, state.getCurrentAttributes(),
555  chunk.getAttrs());
556  return;
557 
565  continue;
566  }
567  }
568 
569  diagnoseBadTypeAttribute(state.getSema(), attr, type);
570 }
571 
572 /// Try to distribute a function type attribute to the innermost
573 /// function chunk or type. Returns true if the attribute was
574 /// distributed, false if no location was found.
576  TypeProcessingState &state, ParsedAttr &attr,
577  ParsedAttributesView &attrList, QualType &declSpecType) {
578  Declarator &declarator = state.getDeclarator();
579 
580  // Put it on the innermost function chunk, if there is one.
581  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
582  DeclaratorChunk &chunk = declarator.getTypeObject(i);
583  if (chunk.Kind != DeclaratorChunk::Function) continue;
584 
585  moveAttrFromListToList(attr, attrList, chunk.getAttrs());
586  return true;
587  }
588 
589  return handleFunctionTypeAttr(state, attr, declSpecType);
590 }
591 
592 /// A function type attribute was written in the decl spec. Try to
593 /// apply it somewhere.
594 static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
595  ParsedAttr &attr,
596  QualType &declSpecType) {
597  state.saveDeclSpecAttrs();
598 
599  // C++11 attributes before the decl specifiers actually appertain to
600  // the declarators. Move them straight there. We don't support the
601  // 'put them wherever you like' semantics we allow for GNU attributes.
602  if (attr.isCXX11Attribute()) {
603  moveAttrFromListToList(attr, state.getCurrentAttributes(),
604  state.getDeclarator().getAttributes());
605  return;
606  }
607 
608  // Try to distribute to the innermost.
610  state, attr, state.getCurrentAttributes(), declSpecType))
611  return;
612 
613  // If that failed, diagnose the bad attribute when the declarator is
614  // fully built.
615  state.addIgnoredTypeAttr(attr);
616 }
617 
618 /// A function type attribute was written on the declarator. Try to
619 /// apply it somewhere.
620 static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
621  ParsedAttr &attr,
622  QualType &declSpecType) {
623  Declarator &declarator = state.getDeclarator();
624 
625  // Try to distribute to the innermost.
627  state, attr, declarator.getAttributes(), declSpecType))
628  return;
629 
630  // If that failed, diagnose the bad attribute when the declarator is
631  // fully built.
632  declarator.getAttributes().remove(&attr);
633  state.addIgnoredTypeAttr(attr);
634 }
635 
636 /// Given that there are attributes written on the declarator
637 /// itself, try to distribute any type attributes to the appropriate
638 /// declarator chunk.
639 ///
640 /// These are attributes like the following:
641 /// int f ATTR;
642 /// int (f ATTR)();
643 /// but not necessarily this:
644 /// int f() ATTR;
645 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
646  QualType &declSpecType) {
647  // Collect all the type attributes from the declarator itself.
648  assert(!state.getDeclarator().getAttributes().empty() &&
649  "declarator has no attrs!");
650  // The called functions in this loop actually remove things from the current
651  // list, so iterating over the existing list isn't possible. Instead, make a
652  // non-owning copy and iterate over that.
653  ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
654  for (ParsedAttr &attr : AttrsCopy) {
655  // Do not distribute C++11 attributes. They have strict rules for what
656  // they appertain to.
657  if (attr.isCXX11Attribute())
658  continue;
659 
660  switch (attr.getKind()) {
662  distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
663  break;
664 
666  distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
667  break;
668 
670  // Microsoft type attributes cannot go after the declarator-id.
671  continue;
672 
674  // Nullability specifiers cannot go after the declarator-id.
675 
676  // Objective-C __kindof does not get distributed.
677  case ParsedAttr::AT_ObjCKindOf:
678  continue;
679 
680  default:
681  break;
682  }
683  }
684 }
685 
686 /// Add a synthetic '()' to a block-literal declarator if it is
687 /// required, given the return type.
688 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
689  QualType declSpecType) {
690  Declarator &declarator = state.getDeclarator();
691 
692  // First, check whether the declarator would produce a function,
693  // i.e. whether the innermost semantic chunk is a function.
694  if (declarator.isFunctionDeclarator()) {
695  // If so, make that declarator a prototyped declarator.
696  declarator.getFunctionTypeInfo().hasPrototype = true;
697  return;
698  }
699 
700  // If there are any type objects, the type as written won't name a
701  // function, regardless of the decl spec type. This is because a
702  // block signature declarator is always an abstract-declarator, and
703  // abstract-declarators can't just be parentheses chunks. Therefore
704  // we need to build a function chunk unless there are no type
705  // objects and the decl spec type is a function.
706  if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
707  return;
708 
709  // Note that there *are* cases with invalid declarators where
710  // declarators consist solely of parentheses. In general, these
711  // occur only in failed efforts to make function declarators, so
712  // faking up the function chunk is still the right thing to do.
713 
714  // Otherwise, we need to fake up a function declarator.
715  SourceLocation loc = declarator.getBeginLoc();
716 
717  // ...and *prepend* it to the declarator.
718  SourceLocation NoLoc;
720  /*HasProto=*/true,
721  /*IsAmbiguous=*/false,
722  /*LParenLoc=*/NoLoc,
723  /*ArgInfo=*/nullptr,
724  /*NumArgs=*/0,
725  /*EllipsisLoc=*/NoLoc,
726  /*RParenLoc=*/NoLoc,
727  /*RefQualifierIsLvalueRef=*/true,
728  /*RefQualifierLoc=*/NoLoc,
729  /*MutableLoc=*/NoLoc, EST_None,
730  /*ESpecRange=*/SourceRange(),
731  /*Exceptions=*/nullptr,
732  /*ExceptionRanges=*/nullptr,
733  /*NumExceptions=*/0,
734  /*NoexceptExpr=*/nullptr,
735  /*ExceptionSpecTokens=*/nullptr,
736  /*DeclsInPrototype=*/None, loc, loc, declarator));
737 
738  // For consistency, make sure the state still has us as processing
739  // the decl spec.
740  assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
741  state.setCurrentChunkIndex(declarator.getNumTypeObjects());
742 }
743 
745  unsigned &TypeQuals,
746  QualType TypeSoFar,
747  unsigned RemoveTQs,
748  unsigned DiagID) {
749  // If this occurs outside a template instantiation, warn the user about
750  // it; they probably didn't mean to specify a redundant qualifier.
751  typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
752  for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
755  QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
756  if (!(RemoveTQs & Qual.first))
757  continue;
758 
759  if (!S.inTemplateInstantiation()) {
760  if (TypeQuals & Qual.first)
761  S.Diag(Qual.second, DiagID)
762  << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
763  << FixItHint::CreateRemoval(Qual.second);
764  }
765 
766  TypeQuals &= ~Qual.first;
767  }
768 }
769 
770 /// Return true if this is omitted block return type. Also check type
771 /// attributes and type qualifiers when returning true.
772 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
773  QualType Result) {
774  if (!isOmittedBlockReturnType(declarator))
775  return false;
776 
777  // Warn if we see type attributes for omitted return type on a block literal.
778  SmallVector<ParsedAttr *, 2> ToBeRemoved;
779  for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
780  if (AL.isInvalid() || !AL.isTypeAttr())
781  continue;
782  S.Diag(AL.getLoc(),
783  diag::warn_block_literal_attributes_on_omitted_return_type)
784  << AL.getName();
785  ToBeRemoved.push_back(&AL);
786  }
787  // Remove bad attributes from the list.
788  for (ParsedAttr *AL : ToBeRemoved)
789  declarator.getMutableDeclSpec().getAttributes().remove(AL);
790 
791  // Warn if we see type qualifiers for omitted return type on a block literal.
792  const DeclSpec &DS = declarator.getDeclSpec();
793  unsigned TypeQuals = DS.getTypeQualifiers();
794  diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
795  diag::warn_block_literal_qualifiers_on_omitted_return_type);
797 
798  return true;
799 }
800 
801 /// Apply Objective-C type arguments to the given type.
804  SourceRange typeArgsRange,
805  bool failOnError = false) {
806  // We can only apply type arguments to an Objective-C class type.
807  const auto *objcObjectType = type->getAs<ObjCObjectType>();
808  if (!objcObjectType || !objcObjectType->getInterface()) {
809  S.Diag(loc, diag::err_objc_type_args_non_class)
810  << type
811  << typeArgsRange;
812 
813  if (failOnError)
814  return QualType();
815  return type;
816  }
817 
818  // The class type must be parameterized.
819  ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
820  ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
821  if (!typeParams) {
822  S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
823  << objcClass->getDeclName()
824  << FixItHint::CreateRemoval(typeArgsRange);
825 
826  if (failOnError)
827  return QualType();
828 
829  return type;
830  }
831 
832  // The type must not already be specialized.
833  if (objcObjectType->isSpecialized()) {
834  S.Diag(loc, diag::err_objc_type_args_specialized_class)
835  << type
836  << FixItHint::CreateRemoval(typeArgsRange);
837 
838  if (failOnError)
839  return QualType();
840 
841  return type;
842  }
843 
844  // Check the type arguments.
845  SmallVector<QualType, 4> finalTypeArgs;
846  unsigned numTypeParams = typeParams->size();
847  bool anyPackExpansions = false;
848  for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
849  TypeSourceInfo *typeArgInfo = typeArgs[i];
850  QualType typeArg = typeArgInfo->getType();
851 
852  // Type arguments cannot have explicit qualifiers or nullability.
853  // We ignore indirect sources of these, e.g. behind typedefs or
854  // template arguments.
855  if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
856  bool diagnosed = false;
857  SourceRange rangeToRemove;
858  if (auto attr = qual.getAs<AttributedTypeLoc>()) {
859  rangeToRemove = attr.getLocalSourceRange();
860  if (attr.getTypePtr()->getImmediateNullability()) {
861  typeArg = attr.getTypePtr()->getModifiedType();
862  S.Diag(attr.getBeginLoc(),
863  diag::err_objc_type_arg_explicit_nullability)
864  << typeArg << FixItHint::CreateRemoval(rangeToRemove);
865  diagnosed = true;
866  }
867  }
868 
869  if (!diagnosed) {
870  S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
871  << typeArg << typeArg.getQualifiers().getAsString()
872  << FixItHint::CreateRemoval(rangeToRemove);
873  }
874  }
875 
876  // Remove qualifiers even if they're non-local.
877  typeArg = typeArg.getUnqualifiedType();
878 
879  finalTypeArgs.push_back(typeArg);
880 
881  if (typeArg->getAs<PackExpansionType>())
882  anyPackExpansions = true;
883 
884  // Find the corresponding type parameter, if there is one.
885  ObjCTypeParamDecl *typeParam = nullptr;
886  if (!anyPackExpansions) {
887  if (i < numTypeParams) {
888  typeParam = typeParams->begin()[i];
889  } else {
890  // Too many arguments.
891  S.Diag(loc, diag::err_objc_type_args_wrong_arity)
892  << false
893  << objcClass->getDeclName()
894  << (unsigned)typeArgs.size()
895  << numTypeParams;
896  S.Diag(objcClass->getLocation(), diag::note_previous_decl)
897  << objcClass;
898 
899  if (failOnError)
900  return QualType();
901 
902  return type;
903  }
904  }
905 
906  // Objective-C object pointer types must be substitutable for the bounds.
907  if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
908  // If we don't have a type parameter to match against, assume
909  // everything is fine. There was a prior pack expansion that
910  // means we won't be able to match anything.
911  if (!typeParam) {
912  assert(anyPackExpansions && "Too many arguments?");
913  continue;
914  }
915 
916  // Retrieve the bound.
917  QualType bound = typeParam->getUnderlyingType();
918  const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
919 
920  // Determine whether the type argument is substitutable for the bound.
921  if (typeArgObjC->isObjCIdType()) {
922  // When the type argument is 'id', the only acceptable type
923  // parameter bound is 'id'.
924  if (boundObjC->isObjCIdType())
925  continue;
926  } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
927  // Otherwise, we follow the assignability rules.
928  continue;
929  }
930 
931  // Diagnose the mismatch.
932  S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
933  diag::err_objc_type_arg_does_not_match_bound)
934  << typeArg << bound << typeParam->getDeclName();
935  S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
936  << typeParam->getDeclName();
937 
938  if (failOnError)
939  return QualType();
940 
941  return type;
942  }
943 
944  // Block pointer types are permitted for unqualified 'id' bounds.
945  if (typeArg->isBlockPointerType()) {
946  // If we don't have a type parameter to match against, assume
947  // everything is fine. There was a prior pack expansion that
948  // means we won't be able to match anything.
949  if (!typeParam) {
950  assert(anyPackExpansions && "Too many arguments?");
951  continue;
952  }
953 
954  // Retrieve the bound.
955  QualType bound = typeParam->getUnderlyingType();
957  continue;
958 
959  // Diagnose the mismatch.
960  S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
961  diag::err_objc_type_arg_does_not_match_bound)
962  << typeArg << bound << typeParam->getDeclName();
963  S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
964  << typeParam->getDeclName();
965 
966  if (failOnError)
967  return QualType();
968 
969  return type;
970  }
971 
972  // Dependent types will be checked at instantiation time.
973  if (typeArg->isDependentType()) {
974  continue;
975  }
976 
977  // Diagnose non-id-compatible type arguments.
978  S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
979  diag::err_objc_type_arg_not_id_compatible)
980  << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
981 
982  if (failOnError)
983  return QualType();
984 
985  return type;
986  }
987 
988  // Make sure we didn't have the wrong number of arguments.
989  if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
990  S.Diag(loc, diag::err_objc_type_args_wrong_arity)
991  << (typeArgs.size() < typeParams->size())
992  << objcClass->getDeclName()
993  << (unsigned)finalTypeArgs.size()
994  << (unsigned)numTypeParams;
995  S.Diag(objcClass->getLocation(), diag::note_previous_decl)
996  << objcClass;
997 
998  if (failOnError)
999  return QualType();
1000 
1001  return type;
1002  }
1003 
1004  // Success. Form the specialized type.
1005  return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1006 }
1007 
1009  SourceLocation ProtocolLAngleLoc,
1010  ArrayRef<ObjCProtocolDecl *> Protocols,
1011  ArrayRef<SourceLocation> ProtocolLocs,
1012  SourceLocation ProtocolRAngleLoc,
1013  bool FailOnError) {
1014  QualType Result = QualType(Decl->getTypeForDecl(), 0);
1015  if (!Protocols.empty()) {
1016  bool HasError;
1017  Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1018  HasError);
1019  if (HasError) {
1020  Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1021  << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1022  if (FailOnError) Result = QualType();
1023  }
1024  if (FailOnError && Result.isNull())
1025  return QualType();
1026  }
1027 
1028  return Result;
1029 }
1030 
1032  SourceLocation Loc,
1033  SourceLocation TypeArgsLAngleLoc,
1034  ArrayRef<TypeSourceInfo *> TypeArgs,
1035  SourceLocation TypeArgsRAngleLoc,
1036  SourceLocation ProtocolLAngleLoc,
1037  ArrayRef<ObjCProtocolDecl *> Protocols,
1038  ArrayRef<SourceLocation> ProtocolLocs,
1039  SourceLocation ProtocolRAngleLoc,
1040  bool FailOnError) {
1041  QualType Result = BaseType;
1042  if (!TypeArgs.empty()) {
1043  Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1044  SourceRange(TypeArgsLAngleLoc,
1045  TypeArgsRAngleLoc),
1046  FailOnError);
1047  if (FailOnError && Result.isNull())
1048  return QualType();
1049  }
1050 
1051  if (!Protocols.empty()) {
1052  bool HasError;
1053  Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1054  HasError);
1055  if (HasError) {
1056  Diag(Loc, diag::err_invalid_protocol_qualifiers)
1057  << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1058  if (FailOnError) Result = QualType();
1059  }
1060  if (FailOnError && Result.isNull())
1061  return QualType();
1062  }
1063 
1064  return Result;
1065 }
1066 
1068  SourceLocation lAngleLoc,
1069  ArrayRef<Decl *> protocols,
1070  ArrayRef<SourceLocation> protocolLocs,
1071  SourceLocation rAngleLoc) {
1072  // Form id<protocol-list>.
1073  QualType Result = Context.getObjCObjectType(
1074  Context.ObjCBuiltinIdTy, { },
1075  llvm::makeArrayRef(
1076  (ObjCProtocolDecl * const *)protocols.data(),
1077  protocols.size()),
1078  false);
1079  Result = Context.getObjCObjectPointerType(Result);
1080 
1081  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1082  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1083 
1084  auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1085  ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1086 
1087  auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1088  .castAs<ObjCObjectTypeLoc>();
1089  ObjCObjectTL.setHasBaseTypeAsWritten(false);
1090  ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1091 
1092  // No type arguments.
1093  ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1094  ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1095 
1096  // Fill in protocol qualifiers.
1097  ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1098  ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1099  for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1100  ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1101 
1102  // We're done. Return the completed type to the parser.
1103  return CreateParsedType(Result, ResultTInfo);
1104 }
1105 
1107  Scope *S,
1108  SourceLocation Loc,
1109  ParsedType BaseType,
1110  SourceLocation TypeArgsLAngleLoc,
1111  ArrayRef<ParsedType> TypeArgs,
1112  SourceLocation TypeArgsRAngleLoc,
1113  SourceLocation ProtocolLAngleLoc,
1114  ArrayRef<Decl *> Protocols,
1115  ArrayRef<SourceLocation> ProtocolLocs,
1116  SourceLocation ProtocolRAngleLoc) {
1117  TypeSourceInfo *BaseTypeInfo = nullptr;
1118  QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1119  if (T.isNull())
1120  return true;
1121 
1122  // Handle missing type-source info.
1123  if (!BaseTypeInfo)
1124  BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1125 
1126  // Extract type arguments.
1127  SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1128  for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1129  TypeSourceInfo *TypeArgInfo = nullptr;
1130  QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1131  if (TypeArg.isNull()) {
1132  ActualTypeArgInfos.clear();
1133  break;
1134  }
1135 
1136  assert(TypeArgInfo && "No type source info?");
1137  ActualTypeArgInfos.push_back(TypeArgInfo);
1138  }
1139 
1140  // Build the object type.
1141  QualType Result = BuildObjCObjectType(
1142  T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1143  TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1144  ProtocolLAngleLoc,
1145  llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1146  Protocols.size()),
1147  ProtocolLocs, ProtocolRAngleLoc,
1148  /*FailOnError=*/false);
1149 
1150  if (Result == T)
1151  return BaseType;
1152 
1153  // Create source information for this type.
1154  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1155  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1156 
1157  // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1158  // object pointer type. Fill in source information for it.
1159  if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1160  // The '*' is implicit.
1161  ObjCObjectPointerTL.setStarLoc(SourceLocation());
1162  ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1163  }
1164 
1165  if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1166  // Protocol qualifier information.
1167  if (OTPTL.getNumProtocols() > 0) {
1168  assert(OTPTL.getNumProtocols() == Protocols.size());
1169  OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1170  OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1171  for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1172  OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1173  }
1174 
1175  // We're done. Return the completed type to the parser.
1176  return CreateParsedType(Result, ResultTInfo);
1177  }
1178 
1179  auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1180 
1181  // Type argument information.
1182  if (ObjCObjectTL.getNumTypeArgs() > 0) {
1183  assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1184  ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1185  ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1186  for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1187  ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1188  } else {
1189  ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1190  ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1191  }
1192 
1193  // Protocol qualifier information.
1194  if (ObjCObjectTL.getNumProtocols() > 0) {
1195  assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1196  ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1197  ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1198  for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1199  ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1200  } else {
1201  ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1202  ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1203  }
1204 
1205  // Base type.
1206  ObjCObjectTL.setHasBaseTypeAsWritten(true);
1207  if (ObjCObjectTL.getType() == T)
1208  ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1209  else
1210  ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1211 
1212  // We're done. Return the completed type to the parser.
1213  return CreateParsedType(Result, ResultTInfo);
1214 }
1215 
1216 static OpenCLAccessAttr::Spelling
1218  for (const ParsedAttr &AL : Attrs)
1219  if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1220  return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1221  return OpenCLAccessAttr::Keyword_read_only;
1222 }
1223 
1224 /// Convert the specified declspec to the appropriate type
1225 /// object.
1226 /// \param state Specifies the declarator containing the declaration specifier
1227 /// to be converted, along with other associated processing state.
1228 /// \returns The type described by the declaration specifiers. This function
1229 /// never returns null.
1230 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1231  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1232  // checking.
1233 
1234  Sema &S = state.getSema();
1235  Declarator &declarator = state.getDeclarator();
1236  DeclSpec &DS = declarator.getMutableDeclSpec();
1237  SourceLocation DeclLoc = declarator.getIdentifierLoc();
1238  if (DeclLoc.isInvalid())
1239  DeclLoc = DS.getBeginLoc();
1240 
1241  ASTContext &Context = S.Context;
1242 
1243  QualType Result;
1244  switch (DS.getTypeSpecType()) {
1245  case DeclSpec::TST_void:
1246  Result = Context.VoidTy;
1247  break;
1248  case DeclSpec::TST_char:
1250  Result = Context.CharTy;
1251  else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1252  Result = Context.SignedCharTy;
1253  else {
1254  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1255  "Unknown TSS value");
1256  Result = Context.UnsignedCharTy;
1257  }
1258  break;
1259  case DeclSpec::TST_wchar:
1261  Result = Context.WCharTy;
1262  else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1263  S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1264  << DS.getSpecifierName(DS.getTypeSpecType(),
1265  Context.getPrintingPolicy());
1266  Result = Context.getSignedWCharType();
1267  } else {
1268  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1269  "Unknown TSS value");
1270  S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1271  << DS.getSpecifierName(DS.getTypeSpecType(),
1272  Context.getPrintingPolicy());
1273  Result = Context.getUnsignedWCharType();
1274  }
1275  break;
1276  case DeclSpec::TST_char8:
1277  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1278  "Unknown TSS value");
1279  Result = Context.Char8Ty;
1280  break;
1281  case DeclSpec::TST_char16:
1282  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1283  "Unknown TSS value");
1284  Result = Context.Char16Ty;
1285  break;
1286  case DeclSpec::TST_char32:
1287  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1288  "Unknown TSS value");
1289  Result = Context.Char32Ty;
1290  break;
1292  // If this is a missing declspec in a block literal return context, then it
1293  // is inferred from the return statements inside the block.
1294  // The declspec is always missing in a lambda expr context; it is either
1295  // specified with a trailing return type or inferred.
1296  if (S.getLangOpts().CPlusPlus14 &&
1298  // In C++1y, a lambda's implicit return type is 'auto'.
1299  Result = Context.getAutoDeductType();
1300  break;
1301  } else if (declarator.getContext() ==
1303  checkOmittedBlockReturnType(S, declarator,
1304  Context.DependentTy)) {
1305  Result = Context.DependentTy;
1306  break;
1307  }
1308 
1309  // Unspecified typespec defaults to int in C90. However, the C90 grammar
1310  // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1311  // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1312  // Note that the one exception to this is function definitions, which are
1313  // allowed to be completely missing a declspec. This is handled in the
1314  // parser already though by it pretending to have seen an 'int' in this
1315  // case.
1316  if (S.getLangOpts().ImplicitInt) {
1317  // In C89 mode, we only warn if there is a completely missing declspec
1318  // when one is not allowed.
1319  if (DS.isEmpty()) {
1320  S.Diag(DeclLoc, diag::ext_missing_declspec)
1321  << DS.getSourceRange()
1322  << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1323  }
1324  } else if (!DS.hasTypeSpecifier()) {
1325  // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1326  // "At least one type specifier shall be given in the declaration
1327  // specifiers in each declaration, and in the specifier-qualifier list in
1328  // each struct declaration and type name."
1329  if (S.getLangOpts().CPlusPlus) {
1330  S.Diag(DeclLoc, diag::err_missing_type_specifier)
1331  << DS.getSourceRange();
1332 
1333  // When this occurs in C++ code, often something is very broken with the
1334  // value being declared, poison it as invalid so we don't get chains of
1335  // errors.
1336  declarator.setInvalidType(true);
1337  } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1338  S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1339  << DS.getSourceRange();
1340  declarator.setInvalidType(true);
1341  } else {
1342  S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1343  << DS.getSourceRange();
1344  }
1345  }
1346 
1347  LLVM_FALLTHROUGH;
1348  case DeclSpec::TST_int: {
1350  switch (DS.getTypeSpecWidth()) {
1351  case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1352  case DeclSpec::TSW_short: Result = Context.ShortTy; break;
1353  case DeclSpec::TSW_long: Result = Context.LongTy; break;
1355  Result = Context.LongLongTy;
1356 
1357  // 'long long' is a C99 or C++11 feature.
1358  if (!S.getLangOpts().C99) {
1359  if (S.getLangOpts().CPlusPlus)
1360  S.Diag(DS.getTypeSpecWidthLoc(),
1361  S.getLangOpts().CPlusPlus11 ?
1362  diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1363  else
1364  S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1365  }
1366  break;
1367  }
1368  } else {
1369  switch (DS.getTypeSpecWidth()) {
1370  case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1371  case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
1372  case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
1374  Result = Context.UnsignedLongLongTy;
1375 
1376  // 'long long' is a C99 or C++11 feature.
1377  if (!S.getLangOpts().C99) {
1378  if (S.getLangOpts().CPlusPlus)
1379  S.Diag(DS.getTypeSpecWidthLoc(),
1380  S.getLangOpts().CPlusPlus11 ?
1381  diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1382  else
1383  S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1384  }
1385  break;
1386  }
1387  }
1388  break;
1389  }
1390  case DeclSpec::TST_accum: {
1391  switch (DS.getTypeSpecWidth()) {
1392  case DeclSpec::TSW_short:
1393  Result = Context.ShortAccumTy;
1394  break;
1396  Result = Context.AccumTy;
1397  break;
1398  case DeclSpec::TSW_long:
1399  Result = Context.LongAccumTy;
1400  break;
1402  llvm_unreachable("Unable to specify long long as _Accum width");
1403  }
1404 
1406  Result = Context.getCorrespondingUnsignedType(Result);
1407 
1408  if (DS.isTypeSpecSat())
1409  Result = Context.getCorrespondingSaturatedType(Result);
1410 
1411  break;
1412  }
1413  case DeclSpec::TST_fract: {
1414  switch (DS.getTypeSpecWidth()) {
1415  case DeclSpec::TSW_short:
1416  Result = Context.ShortFractTy;
1417  break;
1419  Result = Context.FractTy;
1420  break;
1421  case DeclSpec::TSW_long:
1422  Result = Context.LongFractTy;
1423  break;
1425  llvm_unreachable("Unable to specify long long as _Fract width");
1426  }
1427 
1429  Result = Context.getCorrespondingUnsignedType(Result);
1430 
1431  if (DS.isTypeSpecSat())
1432  Result = Context.getCorrespondingSaturatedType(Result);
1433 
1434  break;
1435  }
1436  case DeclSpec::TST_int128:
1437  if (!S.Context.getTargetInfo().hasInt128Type())
1438  S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1439  << "__int128";
1441  Result = Context.UnsignedInt128Ty;
1442  else
1443  Result = Context.Int128Ty;
1444  break;
1445  case DeclSpec::TST_float16: Result = Context.Float16Ty; break;
1446  case DeclSpec::TST_half: Result = Context.HalfTy; break;
1447  case DeclSpec::TST_float: Result = Context.FloatTy; break;
1448  case DeclSpec::TST_double:
1450  Result = Context.LongDoubleTy;
1451  else
1452  Result = Context.DoubleTy;
1453  break;
1456  S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1457  << "__float128";
1458  Result = Context.Float128Ty;
1459  break;
1460  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1461  break;
1462  case DeclSpec::TST_decimal32: // _Decimal32
1463  case DeclSpec::TST_decimal64: // _Decimal64
1464  case DeclSpec::TST_decimal128: // _Decimal128
1465  S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1466  Result = Context.IntTy;
1467  declarator.setInvalidType(true);
1468  break;
1469  case DeclSpec::TST_class:
1470  case DeclSpec::TST_enum:
1471  case DeclSpec::TST_union:
1472  case DeclSpec::TST_struct:
1473  case DeclSpec::TST_interface: {
1474  TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1475  if (!D) {
1476  // This can happen in C++ with ambiguous lookups.
1477  Result = Context.IntTy;
1478  declarator.setInvalidType(true);
1479  break;
1480  }
1481 
1482  // If the type is deprecated or unavailable, diagnose it.
1484 
1485  assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1486  DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1487 
1488  // TypeQuals handled by caller.
1489  Result = Context.getTypeDeclType(D);
1490 
1491  // In both C and C++, make an ElaboratedType.
1492  ElaboratedTypeKeyword Keyword
1494  Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1495  DS.isTypeSpecOwned() ? D : nullptr);
1496  break;
1497  }
1498  case DeclSpec::TST_typename: {
1499  assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1500  DS.getTypeSpecSign() == 0 &&
1501  "Can't handle qualifiers on typedef names yet!");
1502  Result = S.GetTypeFromParser(DS.getRepAsType());
1503  if (Result.isNull()) {
1504  declarator.setInvalidType(true);
1505  }
1506 
1507  // TypeQuals handled by caller.
1508  break;
1509  }
1511  // FIXME: Preserve type source info.
1512  Result = S.GetTypeFromParser(DS.getRepAsType());
1513  assert(!Result.isNull() && "Didn't get a type for typeof?");
1514  if (!Result->isDependentType())
1515  if (const TagType *TT = Result->getAs<TagType>())
1516  S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1517  // TypeQuals handled by caller.
1518  Result = Context.getTypeOfType(Result);
1519  break;
1520  case DeclSpec::TST_typeofExpr: {
1521  Expr *E = DS.getRepAsExpr();
1522  assert(E && "Didn't get an expression for typeof?");
1523  // TypeQuals handled by caller.
1524  Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1525  if (Result.isNull()) {
1526  Result = Context.IntTy;
1527  declarator.setInvalidType(true);
1528  }
1529  break;
1530  }
1531  case DeclSpec::TST_decltype: {
1532  Expr *E = DS.getRepAsExpr();
1533  assert(E && "Didn't get an expression for decltype?");
1534  // TypeQuals handled by caller.
1535  Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1536  if (Result.isNull()) {
1537  Result = Context.IntTy;
1538  declarator.setInvalidType(true);
1539  }
1540  break;
1541  }
1543  Result = S.GetTypeFromParser(DS.getRepAsType());
1544  assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1545  Result = S.BuildUnaryTransformType(Result,
1547  DS.getTypeSpecTypeLoc());
1548  if (Result.isNull()) {
1549  Result = Context.IntTy;
1550  declarator.setInvalidType(true);
1551  }
1552  break;
1553 
1554  case DeclSpec::TST_auto:
1555  Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1556  break;
1557 
1559  Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1560  break;
1561 
1564  /*IsDependent*/ false);
1565  break;
1566 
1568  Result = Context.UnknownAnyTy;
1569  break;
1570 
1571  case DeclSpec::TST_atomic:
1572  Result = S.GetTypeFromParser(DS.getRepAsType());
1573  assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1574  Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1575  if (Result.isNull()) {
1576  Result = Context.IntTy;
1577  declarator.setInvalidType(true);
1578  }
1579  break;
1580 
1581 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1582  case DeclSpec::TST_##ImgType##_t: \
1583  switch (getImageAccess(DS.getAttributes())) { \
1584  case OpenCLAccessAttr::Keyword_write_only: \
1585  Result = Context.Id##WOTy; \
1586  break; \
1587  case OpenCLAccessAttr::Keyword_read_write: \
1588  Result = Context.Id##RWTy; \
1589  break; \
1590  case OpenCLAccessAttr::Keyword_read_only: \
1591  Result = Context.Id##ROTy; \
1592  break; \
1593  } \
1594  break;
1595 #include "clang/Basic/OpenCLImageTypes.def"
1596 
1597  case DeclSpec::TST_error:
1598  Result = Context.IntTy;
1599  declarator.setInvalidType(true);
1600  break;
1601  }
1602 
1603  if (S.getLangOpts().OpenCL &&
1605  declarator.setInvalidType(true);
1606 
1607  bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1608  DS.getTypeSpecType() == DeclSpec::TST_fract;
1609 
1610  // Only fixed point types can be saturated
1611  if (DS.isTypeSpecSat() && !IsFixedPointType)
1612  S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1613  << DS.getSpecifierName(DS.getTypeSpecType(),
1614  Context.getPrintingPolicy());
1615 
1616  // Handle complex types.
1617  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1618  if (S.getLangOpts().Freestanding)
1619  S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1620  Result = Context.getComplexType(Result);
1621  } else if (DS.isTypeAltiVecVector()) {
1622  unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1623  assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1625  if (DS.isTypeAltiVecPixel())
1626  VecKind = VectorType::AltiVecPixel;
1627  else if (DS.isTypeAltiVecBool())
1628  VecKind = VectorType::AltiVecBool;
1629  Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1630  }
1631 
1632  // FIXME: Imaginary.
1633  if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1634  S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1635 
1636  // Before we process any type attributes, synthesize a block literal
1637  // function declarator if necessary.
1638  if (declarator.getContext() == DeclaratorContext::BlockLiteralContext)
1640 
1641  // Apply any type attributes from the decl spec. This may cause the
1642  // list of type attributes to be temporarily saved while the type
1643  // attributes are pushed around.
1644  // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1645  if (!DS.isTypeSpecPipe())
1646  processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1647 
1648  // Apply const/volatile/restrict qualifiers to T.
1649  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1650  // Warn about CV qualifiers on function types.
1651  // C99 6.7.3p8:
1652  // If the specification of a function type includes any type qualifiers,
1653  // the behavior is undefined.
1654  // C++11 [dcl.fct]p7:
1655  // The effect of a cv-qualifier-seq in a function declarator is not the
1656  // same as adding cv-qualification on top of the function type. In the
1657  // latter case, the cv-qualifiers are ignored.
1658  if (TypeQuals && Result->isFunctionType()) {
1660  S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1661  S.getLangOpts().CPlusPlus
1662  ? diag::warn_typecheck_function_qualifiers_ignored
1663  : diag::warn_typecheck_function_qualifiers_unspecified);
1664  // No diagnostic for 'restrict' or '_Atomic' applied to a
1665  // function type; we'll diagnose those later, in BuildQualifiedType.
1666  }
1667 
1668  // C++11 [dcl.ref]p1:
1669  // Cv-qualified references are ill-formed except when the
1670  // cv-qualifiers are introduced through the use of a typedef-name
1671  // or decltype-specifier, in which case the cv-qualifiers are ignored.
1672  //
1673  // There don't appear to be any other contexts in which a cv-qualified
1674  // reference type could be formed, so the 'ill-formed' clause here appears
1675  // to never happen.
1676  if (TypeQuals && Result->isReferenceType()) {
1678  S, DS, TypeQuals, Result,
1680  diag::warn_typecheck_reference_qualifiers);
1681  }
1682 
1683  // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1684  // than once in the same specifier-list or qualifier-list, either directly
1685  // or via one or more typedefs."
1686  if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1687  && TypeQuals & Result.getCVRQualifiers()) {
1688  if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1689  S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1690  << "const";
1691  }
1692 
1693  if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1694  S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1695  << "volatile";
1696  }
1697 
1698  // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1699  // produce a warning in this case.
1700  }
1701 
1702  QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1703 
1704  // If adding qualifiers fails, just use the unqualified type.
1705  if (Qualified.isNull())
1706  declarator.setInvalidType(true);
1707  else
1708  Result = Qualified;
1709  }
1710 
1711  assert(!Result.isNull() && "This function should not return a null type");
1712  return Result;
1713 }
1714 
1715 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1716  if (Entity)
1717  return Entity.getAsString();
1718 
1719  return "type name";
1720 }
1721 
1723  Qualifiers Qs, const DeclSpec *DS) {
1724  if (T.isNull())
1725  return QualType();
1726 
1727  // Ignore any attempt to form a cv-qualified reference.
1728  if (T->isReferenceType()) {
1729  Qs.removeConst();
1730  Qs.removeVolatile();
1731  }
1732 
1733  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1734  // object or incomplete types shall not be restrict-qualified."
1735  if (Qs.hasRestrict()) {
1736  unsigned DiagID = 0;
1737  QualType ProblemTy;
1738 
1739  if (T->isAnyPointerType() || T->isReferenceType() ||
1740  T->isMemberPointerType()) {
1741  QualType EltTy;
1742  if (T->isObjCObjectPointerType())
1743  EltTy = T;
1744  else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1745  EltTy = PTy->getPointeeType();
1746  else
1747  EltTy = T->getPointeeType();
1748 
1749  // If we have a pointer or reference, the pointee must have an object
1750  // incomplete type.
1751  if (!EltTy->isIncompleteOrObjectType()) {
1752  DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1753  ProblemTy = EltTy;
1754  }
1755  } else if (!T->isDependentType()) {
1756  DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1757  ProblemTy = T;
1758  }
1759 
1760  if (DiagID) {
1761  Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1762  Qs.removeRestrict();
1763  }
1764  }
1765 
1766  return Context.getQualifiedType(T, Qs);
1767 }
1768 
1770  unsigned CVRAU, const DeclSpec *DS) {
1771  if (T.isNull())
1772  return QualType();
1773 
1774  // Ignore any attempt to form a cv-qualified reference.
1775  if (T->isReferenceType())
1776  CVRAU &=
1778 
1779  // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1780  // TQ_unaligned;
1781  unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1782 
1783  // C11 6.7.3/5:
1784  // If the same qualifier appears more than once in the same
1785  // specifier-qualifier-list, either directly or via one or more typedefs,
1786  // the behavior is the same as if it appeared only once.
1787  //
1788  // It's not specified what happens when the _Atomic qualifier is applied to
1789  // a type specified with the _Atomic specifier, but we assume that this
1790  // should be treated as if the _Atomic qualifier appeared multiple times.
1791  if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1792  // C11 6.7.3/5:
1793  // If other qualifiers appear along with the _Atomic qualifier in a
1794  // specifier-qualifier-list, the resulting type is the so-qualified
1795  // atomic type.
1796  //
1797  // Don't need to worry about array types here, since _Atomic can't be
1798  // applied to such types.
1800  T = BuildAtomicType(QualType(Split.Ty, 0),
1801  DS ? DS->getAtomicSpecLoc() : Loc);
1802  if (T.isNull())
1803  return T;
1804  Split.Quals.addCVRQualifiers(CVR);
1805  return BuildQualifiedType(T, Loc, Split.Quals);
1806  }
1807 
1810  return BuildQualifiedType(T, Loc, Q, DS);
1811 }
1812 
1813 /// Build a paren type including \p T.
1815  return Context.getParenType(T);
1816 }
1817 
1818 /// Given that we're building a pointer or reference to the given
1820  SourceLocation loc,
1821  bool isReference) {
1822  // Bail out if retention is unrequired or already specified.
1823  if (!type->isObjCLifetimeType() ||
1825  return type;
1826 
1828 
1829  // If the object type is const-qualified, we can safely use
1830  // __unsafe_unretained. This is safe (because there are no read
1831  // barriers), and it'll be safe to coerce anything but __weak* to
1832  // the resulting type.
1833  if (type.isConstQualified()) {
1834  implicitLifetime = Qualifiers::OCL_ExplicitNone;
1835 
1836  // Otherwise, check whether the static type does not require
1837  // retaining. This currently only triggers for Class (possibly
1838  // protocol-qualifed, and arrays thereof).
1839  } else if (type->isObjCARCImplicitlyUnretainedType()) {
1840  implicitLifetime = Qualifiers::OCL_ExplicitNone;
1841 
1842  // If we are in an unevaluated context, like sizeof, skip adding a
1843  // qualification.
1844  } else if (S.isUnevaluatedContext()) {
1845  return type;
1846 
1847  // If that failed, give an error and recover using __strong. __strong
1848  // is the option most likely to prevent spurious second-order diagnostics,
1849  // like when binding a reference to a field.
1850  } else {
1851  // These types can show up in private ivars in system headers, so
1852  // we need this to not be an error in those cases. Instead we
1853  // want to delay.
1857  diag::err_arc_indirect_no_ownership, type, isReference));
1858  } else {
1859  S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1860  }
1861  implicitLifetime = Qualifiers::OCL_Strong;
1862  }
1863  assert(implicitLifetime && "didn't infer any lifetime!");
1864 
1865  Qualifiers qs;
1866  qs.addObjCLifetime(implicitLifetime);
1867  return S.Context.getQualifiedType(type, qs);
1868 }
1869 
1870 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1871  std::string Quals = FnTy->getTypeQuals().getAsString();
1872 
1873  switch (FnTy->getRefQualifier()) {
1874  case RQ_None:
1875  break;
1876 
1877  case RQ_LValue:
1878  if (!Quals.empty())
1879  Quals += ' ';
1880  Quals += '&';
1881  break;
1882 
1883  case RQ_RValue:
1884  if (!Quals.empty())
1885  Quals += ' ';
1886  Quals += "&&";
1887  break;
1888  }
1889 
1890  return Quals;
1891 }
1892 
1893 namespace {
1894 /// Kinds of declarator that cannot contain a qualified function type.
1895 ///
1896 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1897 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1898 /// at the topmost level of a type.
1899 ///
1900 /// Parens and member pointers are permitted. We don't diagnose array and
1901 /// function declarators, because they don't allow function types at all.
1902 ///
1903 /// The values of this enum are used in diagnostics.
1904 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1905 } // end anonymous namespace
1906 
1907 /// Check whether the type T is a qualified function type, and if it is,
1908 /// diagnose that it cannot be contained within the given kind of declarator.
1910  QualifiedFunctionKind QFK) {
1911  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1912  const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1913  if (!FPT || (FPT->getTypeQuals().empty() && FPT->getRefQualifier() == RQ_None))
1914  return false;
1915 
1916  S.Diag(Loc, diag::err_compound_qualified_function_type)
1917  << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1919  return true;
1920 }
1921 
1922 /// Build a pointer type.
1923 ///
1924 /// \param T The type to which we'll be building a pointer.
1925 ///
1926 /// \param Loc The location of the entity whose type involves this
1927 /// pointer type or, if there is no such entity, the location of the
1928 /// type that will have pointer type.
1929 ///
1930 /// \param Entity The name of the entity that involves the pointer
1931 /// type, if known.
1932 ///
1933 /// \returns A suitable pointer type, if there are no
1934 /// errors. Otherwise, returns a NULL type.
1936  SourceLocation Loc, DeclarationName Entity) {
1937  if (T->isReferenceType()) {
1938  // C++ 8.3.2p4: There shall be no ... pointers to references ...
1939  Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1940  << getPrintableNameForEntity(Entity) << T;
1941  return QualType();
1942  }
1943 
1944  if (T->isFunctionType() && getLangOpts().OpenCL) {
1945  Diag(Loc, diag::err_opencl_function_pointer);
1946  return QualType();
1947  }
1948 
1949  if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1950  return QualType();
1951 
1952  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1953 
1954  // In ARC, it is forbidden to build pointers to unqualified pointers.
1955  if (getLangOpts().ObjCAutoRefCount)
1956  T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1957 
1958  // Build the pointer type.
1959  return Context.getPointerType(T);
1960 }
1961 
1962 /// Build a reference type.
1963 ///
1964 /// \param T The type to which we'll be building a reference.
1965 ///
1966 /// \param Loc The location of the entity whose type involves this
1967 /// reference type or, if there is no such entity, the location of the
1968 /// type that will have reference type.
1969 ///
1970 /// \param Entity The name of the entity that involves the reference
1971 /// type, if known.
1972 ///
1973 /// \returns A suitable reference type, if there are no
1974 /// errors. Otherwise, returns a NULL type.
1976  SourceLocation Loc,
1977  DeclarationName Entity) {
1978  assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1979  "Unresolved overloaded function type");
1980 
1981  // C++0x [dcl.ref]p6:
1982  // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1983  // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1984  // type T, an attempt to create the type "lvalue reference to cv TR" creates
1985  // the type "lvalue reference to T", while an attempt to create the type
1986  // "rvalue reference to cv TR" creates the type TR.
1987  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1988 
1989  // C++ [dcl.ref]p4: There shall be no references to references.
1990  //
1991  // According to C++ DR 106, references to references are only
1992  // diagnosed when they are written directly (e.g., "int & &"),
1993  // but not when they happen via a typedef:
1994  //
1995  // typedef int& intref;
1996  // typedef intref& intref2;
1997  //
1998  // Parser::ParseDeclaratorInternal diagnoses the case where
1999  // references are written directly; here, we handle the
2000  // collapsing of references-to-references as described in C++0x.
2001  // DR 106 and 540 introduce reference-collapsing into C++98/03.
2002 
2003  // C++ [dcl.ref]p1:
2004  // A declarator that specifies the type "reference to cv void"
2005  // is ill-formed.
2006  if (T->isVoidType()) {
2007  Diag(Loc, diag::err_reference_to_void);
2008  return QualType();
2009  }
2010 
2011  if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2012  return QualType();
2013 
2014  // In ARC, it is forbidden to build references to unqualified pointers.
2015  if (getLangOpts().ObjCAutoRefCount)
2016  T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2017 
2018  // Handle restrict on references.
2019  if (LValueRef)
2020  return Context.getLValueReferenceType(T, SpelledAsLValue);
2021  return Context.getRValueReferenceType(T);
2022 }
2023 
2024 /// Build a Read-only Pipe type.
2025 ///
2026 /// \param T The type to which we'll be building a Pipe.
2027 ///
2028 /// \param Loc We do not use it for now.
2029 ///
2030 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2031 /// NULL type.
2033  return Context.getReadPipeType(T);
2034 }
2035 
2036 /// Build a Write-only Pipe type.
2037 ///
2038 /// \param T The type to which we'll be building a Pipe.
2039 ///
2040 /// \param Loc We do not use it for now.
2041 ///
2042 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2043 /// NULL type.
2045  return Context.getWritePipeType(T);
2046 }
2047 
2048 /// Check whether the specified array size makes the array type a VLA. If so,
2049 /// return true, if not, return the size of the array in SizeVal.
2050 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
2051  // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2052  // (like gnu99, but not c99) accept any evaluatable value as an extension.
2053  class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2054  public:
2055  VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
2056 
2057  void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
2058  }
2059 
2060  void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
2061  S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2062  }
2063  } Diagnoser;
2064 
2065  return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2066  S.LangOpts.GNUMode ||
2067  S.LangOpts.OpenCL).isInvalid();
2068 }
2069 
2070 /// Build an array type.
2071 ///
2072 /// \param T The type of each element in the array.
2073 ///
2074 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2075 ///
2076 /// \param ArraySize Expression describing the size of the array.
2077 ///
2078 /// \param Brackets The range from the opening '[' to the closing ']'.
2079 ///
2080 /// \param Entity The name of the entity that involves the array
2081 /// type, if known.
2082 ///
2083 /// \returns A suitable array type, if there are no errors. Otherwise,
2084 /// returns a NULL type.
2086  Expr *ArraySize, unsigned Quals,
2087  SourceRange Brackets, DeclarationName Entity) {
2088 
2089  SourceLocation Loc = Brackets.getBegin();
2090  if (getLangOpts().CPlusPlus) {
2091  // C++ [dcl.array]p1:
2092  // T is called the array element type; this type shall not be a reference
2093  // type, the (possibly cv-qualified) type void, a function type or an
2094  // abstract class type.
2095  //
2096  // C++ [dcl.array]p3:
2097  // When several "array of" specifications are adjacent, [...] only the
2098  // first of the constant expressions that specify the bounds of the arrays
2099  // may be omitted.
2100  //
2101  // Note: function types are handled in the common path with C.
2102  if (T->isReferenceType()) {
2103  Diag(Loc, diag::err_illegal_decl_array_of_references)
2104  << getPrintableNameForEntity(Entity) << T;
2105  return QualType();
2106  }
2107 
2108  if (T->isVoidType() || T->isIncompleteArrayType()) {
2109  Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2110  return QualType();
2111  }
2112 
2113  if (RequireNonAbstractType(Brackets.getBegin(), T,
2114  diag::err_array_of_abstract_type))
2115  return QualType();
2116 
2117  // Mentioning a member pointer type for an array type causes us to lock in
2118  // an inheritance model, even if it's inside an unused typedef.
2119  if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2120  if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2121  if (!MPTy->getClass()->isDependentType())
2122  (void)isCompleteType(Loc, T);
2123 
2124  } else {
2125  // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2126  // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2127  if (RequireCompleteType(Loc, T,
2128  diag::err_illegal_decl_array_incomplete_type))
2129  return QualType();
2130  }
2131 
2132  if (T->isFunctionType()) {
2133  Diag(Loc, diag::err_illegal_decl_array_of_functions)
2134  << getPrintableNameForEntity(Entity) << T;
2135  return QualType();
2136  }
2137 
2138  if (const RecordType *EltTy = T->getAs<RecordType>()) {
2139  // If the element type is a struct or union that contains a variadic
2140  // array, accept it as a GNU extension: C99 6.7.2.1p2.
2141  if (EltTy->getDecl()->hasFlexibleArrayMember())
2142  Diag(Loc, diag::ext_flexible_array_in_array) << T;
2143  } else if (T->isObjCObjectType()) {
2144  Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2145  return QualType();
2146  }
2147 
2148  // Do placeholder conversions on the array size expression.
2149  if (ArraySize && ArraySize->hasPlaceholderType()) {
2150  ExprResult Result = CheckPlaceholderExpr(ArraySize);
2151  if (Result.isInvalid()) return QualType();
2152  ArraySize = Result.get();
2153  }
2154 
2155  // Do lvalue-to-rvalue conversions on the array size expression.
2156  if (ArraySize && !ArraySize->isRValue()) {
2157  ExprResult Result = DefaultLvalueConversion(ArraySize);
2158  if (Result.isInvalid())
2159  return QualType();
2160 
2161  ArraySize = Result.get();
2162  }
2163 
2164  // C99 6.7.5.2p1: The size expression shall have integer type.
2165  // C++11 allows contextual conversions to such types.
2166  if (!getLangOpts().CPlusPlus11 &&
2167  ArraySize && !ArraySize->isTypeDependent() &&
2168  !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2169  Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2170  << ArraySize->getType() << ArraySize->getSourceRange();
2171  return QualType();
2172  }
2173 
2174  llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2175  if (!ArraySize) {
2176  if (ASM == ArrayType::Star)
2177  T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2178  else
2179  T = Context.getIncompleteArrayType(T, ASM, Quals);
2180  } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2181  T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2182  } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2183  !T->isConstantSizeType()) ||
2184  isArraySizeVLA(*this, ArraySize, ConstVal)) {
2185  // Even in C++11, don't allow contextual conversions in the array bound
2186  // of a VLA.
2187  if (getLangOpts().CPlusPlus11 &&
2188  !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2189  Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2190  << ArraySize->getType() << ArraySize->getSourceRange();
2191  return QualType();
2192  }
2193 
2194  // C99: an array with an element type that has a non-constant-size is a VLA.
2195  // C99: an array with a non-ICE size is a VLA. We accept any expression
2196  // that we can fold to a non-zero positive value as an extension.
2197  T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2198  } else {
2199  // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2200  // have a value greater than zero.
2201  if (ConstVal.isSigned() && ConstVal.isNegative()) {
2202  if (Entity)
2203  Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2204  << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2205  else
2206  Diag(ArraySize->getBeginLoc(), diag::err_typecheck_negative_array_size)
2207  << ArraySize->getSourceRange();
2208  return QualType();
2209  }
2210  if (ConstVal == 0) {
2211  // GCC accepts zero sized static arrays. We allow them when
2212  // we're not in a SFINAE context.
2213  Diag(ArraySize->getBeginLoc(), isSFINAEContext()
2214  ? diag::err_typecheck_zero_array_size
2215  : diag::ext_typecheck_zero_array_size)
2216  << ArraySize->getSourceRange();
2217 
2218  if (ASM == ArrayType::Static) {
2219  Diag(ArraySize->getBeginLoc(),
2220  diag::warn_typecheck_zero_static_array_size)
2221  << ArraySize->getSourceRange();
2222  ASM = ArrayType::Normal;
2223  }
2224  } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2225  !T->isIncompleteType() && !T->isUndeducedType()) {
2226  // Is the array too large?
2227  unsigned ActiveSizeBits
2228  = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2229  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2230  Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2231  << ConstVal.toString(10) << ArraySize->getSourceRange();
2232  return QualType();
2233  }
2234  }
2235 
2236  T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2237  }
2238 
2239  // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2240  if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2241  Diag(Loc, diag::err_opencl_vla);
2242  return QualType();
2243  }
2244 
2245  if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2246  if (getLangOpts().CUDA) {
2247  // CUDA device code doesn't support VLAs.
2248  CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget();
2249  } else if (!getLangOpts().OpenMP ||
2250  shouldDiagnoseTargetSupportFromOpenMP()) {
2251  // Some targets don't support VLAs.
2252  Diag(Loc, diag::err_vla_unsupported);
2253  return QualType();
2254  }
2255  }
2256 
2257  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2258  if (!getLangOpts().C99) {
2259  if (T->isVariableArrayType()) {
2260  // Prohibit the use of VLAs during template argument deduction.
2261  if (isSFINAEContext()) {
2262  Diag(Loc, diag::err_vla_in_sfinae);
2263  return QualType();
2264  }
2265  // Just extwarn about VLAs.
2266  else
2267  Diag(Loc, diag::ext_vla);
2268  } else if (ASM != ArrayType::Normal || Quals != 0)
2269  Diag(Loc,
2270  getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2271  : diag::ext_c99_array_usage) << ASM;
2272  }
2273 
2274  if (T->isVariableArrayType()) {
2275  // Warn about VLAs for -Wvla.
2276  Diag(Loc, diag::warn_vla_used);
2277  }
2278 
2279  // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2280  // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2281  // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2282  if (getLangOpts().OpenCL) {
2283  const QualType ArrType = Context.getBaseElementType(T);
2284  if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2285  ArrType->isSamplerT() || ArrType->isImageType()) {
2286  Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2287  return QualType();
2288  }
2289  }
2290 
2291  return T;
2292 }
2293 
2295  SourceLocation AttrLoc) {
2296  // The base type must be integer (not Boolean or enumeration) or float, and
2297  // can't already be a vector.
2298  if (!CurType->isDependentType() &&
2299  (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2300  (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) {
2301  Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2302  return QualType();
2303  }
2304 
2305  if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2306  return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2308 
2309  llvm::APSInt VecSize(32);
2310  if (!SizeExpr->isIntegerConstantExpr(VecSize, Context)) {
2311  Diag(AttrLoc, diag::err_attribute_argument_type)
2312  << "vector_size" << AANT_ArgumentIntegerConstant
2313  << SizeExpr->getSourceRange();
2314  return QualType();
2315  }
2316 
2317  if (CurType->isDependentType())
2318  return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2320 
2321  unsigned VectorSize = static_cast<unsigned>(VecSize.getZExtValue() * 8);
2322  unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2323 
2324  if (VectorSize == 0) {
2325  Diag(AttrLoc, diag::err_attribute_zero_size) << SizeExpr->getSourceRange();
2326  return QualType();
2327  }
2328 
2329  // vecSize is specified in bytes - convert to bits.
2330  if (VectorSize % TypeSize) {
2331  Diag(AttrLoc, diag::err_attribute_invalid_size)
2332  << SizeExpr->getSourceRange();
2333  return QualType();
2334  }
2335 
2336  if (VectorType::isVectorSizeTooLarge(VectorSize / TypeSize)) {
2337  Diag(AttrLoc, diag::err_attribute_size_too_large)
2338  << SizeExpr->getSourceRange();
2339  return QualType();
2340  }
2341 
2342  return Context.getVectorType(CurType, VectorSize / TypeSize,
2344 }
2345 
2346 /// Build an ext-vector type.
2347 ///
2348 /// Run the required checks for the extended vector type.
2350  SourceLocation AttrLoc) {
2351  // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2352  // in conjunction with complex types (pointers, arrays, functions, etc.).
2353  //
2354  // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2355  // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2356  // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2357  // of bool aren't allowed.
2358  if ((!T->isDependentType() && !T->isIntegerType() &&
2359  !T->isRealFloatingType()) ||
2360  T->isBooleanType()) {
2361  Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2362  return QualType();
2363  }
2364 
2365  if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2366  llvm::APSInt vecSize(32);
2367  if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2368  Diag(AttrLoc, diag::err_attribute_argument_type)
2369  << "ext_vector_type" << AANT_ArgumentIntegerConstant
2370  << ArraySize->getSourceRange();
2371  return QualType();
2372  }
2373 
2374  // Unlike gcc's vector_size attribute, the size is specified as the
2375  // number of elements, not the number of bytes.
2376  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2377 
2378  if (vectorSize == 0) {
2379  Diag(AttrLoc, diag::err_attribute_zero_size)
2380  << ArraySize->getSourceRange();
2381  return QualType();
2382  }
2383 
2384  if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2385  Diag(AttrLoc, diag::err_attribute_size_too_large)
2386  << ArraySize->getSourceRange();
2387  return QualType();
2388  }
2389 
2390  return Context.getExtVectorType(T, vectorSize);
2391  }
2392 
2393  return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2394 }
2395 
2397  if (T->isArrayType() || T->isFunctionType()) {
2398  Diag(Loc, diag::err_func_returning_array_function)
2399  << T->isFunctionType() << T;
2400  return true;
2401  }
2402 
2403  // Functions cannot return half FP.
2404  if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2405  Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2406  FixItHint::CreateInsertion(Loc, "*");
2407  return true;
2408  }
2409 
2410  // Methods cannot return interface types. All ObjC objects are
2411  // passed by reference.
2412  if (T->isObjCObjectType()) {
2413  Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2414  << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2415  return true;
2416  }
2417 
2418  return false;
2419 }
2420 
2421 /// Check the extended parameter information. Most of the necessary
2422 /// checking should occur when applying the parameter attribute; the
2423 /// only other checks required are positional restrictions.
2426  llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2427  assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2428 
2429  bool hasCheckedSwiftCall = false;
2430  auto checkForSwiftCC = [&](unsigned paramIndex) {
2431  // Only do this once.
2432  if (hasCheckedSwiftCall) return;
2433  hasCheckedSwiftCall = true;
2434  if (EPI.ExtInfo.getCC() == CC_Swift) return;
2435  S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2436  << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2437  };
2438 
2439  for (size_t paramIndex = 0, numParams = paramTypes.size();
2440  paramIndex != numParams; ++paramIndex) {
2441  switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2442  // Nothing interesting to check for orindary-ABI parameters.
2444  continue;
2445 
2446  // swift_indirect_result parameters must be a prefix of the function
2447  // arguments.
2449  checkForSwiftCC(paramIndex);
2450  if (paramIndex != 0 &&
2451  EPI.ExtParameterInfos[paramIndex - 1].getABI()
2453  S.Diag(getParamLoc(paramIndex),
2454  diag::err_swift_indirect_result_not_first);
2455  }
2456  continue;
2457 
2459  checkForSwiftCC(paramIndex);
2460  continue;
2461 
2462  // swift_error parameters must be preceded by a swift_context parameter.
2464  checkForSwiftCC(paramIndex);
2465  if (paramIndex == 0 ||
2466  EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2468  S.Diag(getParamLoc(paramIndex),
2469  diag::err_swift_error_result_not_after_swift_context);
2470  }
2471  continue;
2472  }
2473  llvm_unreachable("bad ABI kind");
2474  }
2475 }
2476 
2478  MutableArrayRef<QualType> ParamTypes,
2479  SourceLocation Loc, DeclarationName Entity,
2480  const FunctionProtoType::ExtProtoInfo &EPI) {
2481  bool Invalid = false;
2482 
2483  Invalid |= CheckFunctionReturnType(T, Loc);
2484 
2485  for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2486  // FIXME: Loc is too inprecise here, should use proper locations for args.
2487  QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2488  if (ParamType->isVoidType()) {
2489  Diag(Loc, diag::err_param_with_void_type);
2490  Invalid = true;
2491  } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2492  // Disallow half FP arguments.
2493  Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2494  FixItHint::CreateInsertion(Loc, "*");
2495  Invalid = true;
2496  }
2497 
2498  ParamTypes[Idx] = ParamType;
2499  }
2500 
2501  if (EPI.ExtParameterInfos) {
2502  checkExtParameterInfos(*this, ParamTypes, EPI,
2503  [=](unsigned i) { return Loc; });
2504  }
2505 
2506  if (EPI.ExtInfo.getProducesResult()) {
2507  // This is just a warning, so we can't fail to build if we see it.
2508  checkNSReturnsRetainedReturnType(Loc, T);
2509  }
2510 
2511  if (Invalid)
2512  return QualType();
2513 
2514  return Context.getFunctionType(T, ParamTypes, EPI);
2515 }
2516 
2517 /// Build a member pointer type \c T Class::*.
2518 ///
2519 /// \param T the type to which the member pointer refers.
2520 /// \param Class the class type into which the member pointer points.
2521 /// \param Loc the location where this type begins
2522 /// \param Entity the name of the entity that will have this member pointer type
2523 ///
2524 /// \returns a member pointer type, if successful, or a NULL type if there was
2525 /// an error.
2527  SourceLocation Loc,
2528  DeclarationName Entity) {
2529  // Verify that we're not building a pointer to pointer to function with
2530  // exception specification.
2531  if (CheckDistantExceptionSpec(T)) {
2532  Diag(Loc, diag::err_distant_exception_spec);
2533  return QualType();
2534  }
2535 
2536  // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2537  // with reference type, or "cv void."
2538  if (T->isReferenceType()) {
2539  Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2540  << getPrintableNameForEntity(Entity) << T;
2541  return QualType();
2542  }
2543 
2544  if (T->isVoidType()) {
2545  Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2546  << getPrintableNameForEntity(Entity);
2547  return QualType();
2548  }
2549 
2550  if (!Class->isDependentType() && !Class->isRecordType()) {
2551  Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2552  return QualType();
2553  }
2554 
2555  // Adjust the default free function calling convention to the default method
2556  // calling convention.
2557  bool IsCtorOrDtor =
2560  if (T->isFunctionType())
2561  adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2562 
2563  return Context.getMemberPointerType(T, Class.getTypePtr());
2564 }
2565 
2566 /// Build a block pointer type.
2567 ///
2568 /// \param T The type to which we'll be building a block pointer.
2569 ///
2570 /// \param Loc The source location, used for diagnostics.
2571 ///
2572 /// \param Entity The name of the entity that involves the block pointer
2573 /// type, if known.
2574 ///
2575 /// \returns A suitable block pointer type, if there are no
2576 /// errors. Otherwise, returns a NULL type.
2578  SourceLocation Loc,
2579  DeclarationName Entity) {
2580  if (!T->isFunctionType()) {
2581  Diag(Loc, diag::err_nonfunction_block_type);
2582  return QualType();
2583  }
2584 
2585  if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2586  return QualType();
2587 
2588  return Context.getBlockPointerType(T);
2589 }
2590 
2592  QualType QT = Ty.get();
2593  if (QT.isNull()) {
2594  if (TInfo) *TInfo = nullptr;
2595  return QualType();
2596  }
2597 
2598  TypeSourceInfo *DI = nullptr;
2599  if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2600  QT = LIT->getType();
2601  DI = LIT->getTypeSourceInfo();
2602  }
2603 
2604  if (TInfo) *TInfo = DI;
2605  return QT;
2606 }
2607 
2608 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2609  Qualifiers::ObjCLifetime ownership,
2610  unsigned chunkIndex);
2611 
2612 /// Given that this is the declaration of a parameter under ARC,
2613 /// attempt to infer attributes and such for pointer-to-whatever
2614 /// types.
2615 static void inferARCWriteback(TypeProcessingState &state,
2616  QualType &declSpecType) {
2617  Sema &S = state.getSema();
2618  Declarator &declarator = state.getDeclarator();
2619 
2620  // TODO: should we care about decl qualifiers?
2621 
2622  // Check whether the declarator has the expected form. We walk
2623  // from the inside out in order to make the block logic work.
2624  unsigned outermostPointerIndex = 0;
2625  bool isBlockPointer = false;
2626  unsigned numPointers = 0;
2627  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2628  unsigned chunkIndex = i;
2629  DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2630  switch (chunk.Kind) {
2632  // Ignore parens.
2633  break;
2634 
2637  // Count the number of pointers. Treat references
2638  // interchangeably as pointers; if they're mis-ordered, normal
2639  // type building will discover that.
2640  outermostPointerIndex = chunkIndex;
2641  numPointers++;
2642  break;
2643 
2645  // If we have a pointer to block pointer, that's an acceptable
2646  // indirect reference; anything else is not an application of
2647  // the rules.
2648  if (numPointers != 1) return;
2649  numPointers++;
2650  outermostPointerIndex = chunkIndex;
2651  isBlockPointer = true;
2652 
2653  // We don't care about pointer structure in return values here.
2654  goto done;
2655 
2656  case DeclaratorChunk::Array: // suppress if written (id[])?
2659  case DeclaratorChunk::Pipe:
2660  return;
2661  }
2662  }
2663  done:
2664 
2665  // If we have *one* pointer, then we want to throw the qualifier on
2666  // the declaration-specifiers, which means that it needs to be a
2667  // retainable object type.
2668  if (numPointers == 1) {
2669  // If it's not a retainable object type, the rule doesn't apply.
2670  if (!declSpecType->isObjCRetainableType()) return;
2671 
2672  // If it already has lifetime, don't do anything.
2673  if (declSpecType.getObjCLifetime()) return;
2674 
2675  // Otherwise, modify the type in-place.
2676  Qualifiers qs;
2677 
2678  if (declSpecType->isObjCARCImplicitlyUnretainedType())
2680  else
2682  declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2683 
2684  // If we have *two* pointers, then we want to throw the qualifier on
2685  // the outermost pointer.
2686  } else if (numPointers == 2) {
2687  // If we don't have a block pointer, we need to check whether the
2688  // declaration-specifiers gave us something that will turn into a
2689  // retainable object pointer after we slap the first pointer on it.
2690  if (!isBlockPointer && !declSpecType->isObjCObjectType())
2691  return;
2692 
2693  // Look for an explicit lifetime attribute there.
2694  DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2695  if (chunk.Kind != DeclaratorChunk::Pointer &&
2697  return;
2698  for (const ParsedAttr &AL : chunk.getAttrs())
2699  if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2700  return;
2701 
2703  outermostPointerIndex);
2704 
2705  // Any other number of pointers/references does not trigger the rule.
2706  } else return;
2707 
2708  // TODO: mark whether we did this inference?
2709 }
2710 
2711 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2712  SourceLocation FallbackLoc,
2713  SourceLocation ConstQualLoc,
2714  SourceLocation VolatileQualLoc,
2715  SourceLocation RestrictQualLoc,
2716  SourceLocation AtomicQualLoc,
2717  SourceLocation UnalignedQualLoc) {
2718  if (!Quals)
2719  return;
2720 
2721  struct Qual {
2722  const char *Name;
2723  unsigned Mask;
2724  SourceLocation Loc;
2725  } const QualKinds[5] = {
2726  { "const", DeclSpec::TQ_const, ConstQualLoc },
2727  { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2728  { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2729  { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2730  { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2731  };
2732 
2733  SmallString<32> QualStr;
2734  unsigned NumQuals = 0;
2735  SourceLocation Loc;
2736  FixItHint FixIts[5];
2737 
2738  // Build a string naming the redundant qualifiers.
2739  for (auto &E : QualKinds) {
2740  if (Quals & E.Mask) {
2741  if (!QualStr.empty()) QualStr += ' ';
2742  QualStr += E.Name;
2743 
2744  // If we have a location for the qualifier, offer a fixit.
2745  SourceLocation QualLoc = E.Loc;
2746  if (QualLoc.isValid()) {
2747  FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2748  if (Loc.isInvalid() ||
2749  getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2750  Loc = QualLoc;
2751  }
2752 
2753  ++NumQuals;
2754  }
2755  }
2756 
2757  Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2758  << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2759 }
2760 
2761 // Diagnose pointless type qualifiers on the return type of a function.
2763  Declarator &D,
2764  unsigned FunctionChunkIndex) {
2765  if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2766  // FIXME: TypeSourceInfo doesn't preserve location information for
2767  // qualifiers.
2768  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2769  RetTy.getLocalCVRQualifiers(),
2770  D.getIdentifierLoc());
2771  return;
2772  }
2773 
2774  for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2775  End = D.getNumTypeObjects();
2776  OuterChunkIndex != End; ++OuterChunkIndex) {
2777  DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2778  switch (OuterChunk.Kind) {
2780  continue;
2781 
2782  case DeclaratorChunk::Pointer: {
2783  DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2785  diag::warn_qual_return_type,
2786  PTI.TypeQuals,
2787  SourceLocation(),
2793  return;
2794  }
2795 
2801  case DeclaratorChunk::Pipe:
2802  // FIXME: We can't currently provide an accurate source location and a
2803  // fix-it hint for these.
2804  unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2805  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2806  RetTy.getCVRQualifiers() | AtomicQual,
2807  D.getIdentifierLoc());
2808  return;
2809  }
2810 
2811  llvm_unreachable("unknown declarator chunk kind");
2812  }
2813 
2814  // If the qualifiers come from a conversion function type, don't diagnose
2815  // them -- they're not necessarily redundant, since such a conversion
2816  // operator can be explicitly called as "x.operator const int()".
2818  return;
2819 
2820  // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2821  // which are present there.
2822  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2824  D.getIdentifierLoc(),
2830 }
2831 
2832 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2833  TypeSourceInfo *&ReturnTypeInfo) {
2834  Sema &SemaRef = state.getSema();
2835  Declarator &D = state.getDeclarator();
2836  QualType T;
2837  ReturnTypeInfo = nullptr;
2838 
2839  // The TagDecl owned by the DeclSpec.
2840  TagDecl *OwnedTagDecl = nullptr;
2841 
2842  switch (D.getName().getKind()) {
2848  T = ConvertDeclSpecToType(state);
2849 
2850  if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2851  OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2852  // Owned declaration is embedded in declarator.
2853  OwnedTagDecl->setEmbeddedInDeclarator(true);
2854  }
2855  break;
2856 
2860  // Constructors and destructors don't have return types. Use
2861  // "void" instead.
2862  T = SemaRef.Context.VoidTy;
2863  processTypeAttrs(state, T, TAL_DeclSpec,
2865  break;
2866 
2868  // Deduction guides have a trailing return type and no type in their
2869  // decl-specifier sequence. Use a placeholder return type for now.
2870  T = SemaRef.Context.DependentTy;
2871  break;
2872 
2874  // The result type of a conversion function is the type that it
2875  // converts to.
2877  &ReturnTypeInfo);
2878  break;
2879  }
2880 
2881  if (!D.getAttributes().empty())
2883 
2884  // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2885  if (DeducedType *Deduced = T->getContainedDeducedType()) {
2886  AutoType *Auto = dyn_cast<AutoType>(Deduced);
2887  int Error = -1;
2888 
2889  // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
2890  // class template argument deduction)?
2891  bool IsCXXAutoType =
2892  (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
2893  bool IsDeducedReturnType = false;
2894 
2895  switch (D.getContext()) {
2897  // Declared return type of a lambda-declarator is implicit and is always
2898  // 'auto'.
2899  break;
2903  Error = 0;
2904  break;
2906  // In C++14, generic lambdas allow 'auto' in their parameters.
2907  if (!SemaRef.getLangOpts().CPlusPlus14 ||
2908  !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto)
2909  Error = 16;
2910  else {
2911  // If auto is mentioned in a lambda parameter context, convert it to a
2912  // template parameter type.
2913  sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda();
2914  assert(LSI && "No LambdaScopeInfo on the stack!");
2915  const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
2916  const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
2917  const bool IsParameterPack = D.hasEllipsis();
2918 
2919  // Create the TemplateTypeParmDecl here to retrieve the corresponding
2920  // template parameter type. Template parameters are temporarily added
2921  // to the TU until the associated TemplateDecl is created.
2922  TemplateTypeParmDecl *CorrespondingTemplateParam =
2924  SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(),
2925  /*KeyLoc*/ SourceLocation(), /*NameLoc*/ D.getBeginLoc(),
2926  TemplateParameterDepth, AutoParameterPosition,
2927  /*Identifier*/ nullptr, false, IsParameterPack);
2928  LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
2929  // Replace the 'auto' in the function parameter with this invented
2930  // template type parameter.
2931  // FIXME: Retain some type sugar to indicate that this was written
2932  // as 'auto'.
2933  T = SemaRef.ReplaceAutoType(
2934  T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
2935  }
2936  break;
2940  break;
2941  bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2942  switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2943  case TTK_Enum: llvm_unreachable("unhandled tag kind");
2944  case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2945  case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
2946  case TTK_Class: Error = 5; /* Class member */ break;
2947  case TTK_Interface: Error = 6; /* Interface member */ break;
2948  }
2949  if (D.getDeclSpec().isFriendSpecified())
2950  Error = 20; // Friend type
2951  break;
2952  }
2955  Error = 7; // Exception declaration
2956  break;
2958  if (isa<DeducedTemplateSpecializationType>(Deduced))
2959  Error = 19; // Template parameter
2960  else if (!SemaRef.getLangOpts().CPlusPlus17)
2961  Error = 8; // Template parameter (until C++17)
2962  break;
2964  Error = 9; // Block literal
2965  break;
2967  // Within a template argument list, a deduced template specialization
2968  // type will be reinterpreted as a template template argument.
2969  if (isa<DeducedTemplateSpecializationType>(Deduced) &&
2970  !D.getNumTypeObjects() &&
2972  break;
2973  LLVM_FALLTHROUGH;
2975  Error = 10; // Template type argument
2976  break;
2979  Error = 12; // Type alias
2980  break;
2983  if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2984  Error = 13; // Function return type
2985  IsDeducedReturnType = true;
2986  break;
2988  if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2989  Error = 14; // conversion-type-id
2990  IsDeducedReturnType = true;
2991  break;
2993  if (isa<DeducedTemplateSpecializationType>(Deduced))
2994  break;
2995  LLVM_FALLTHROUGH;
2997  Error = 15; // Generic
2998  break;
3004  // FIXME: P0091R3 (erroneously) does not permit class template argument
3005  // deduction in conditions, for-init-statements, and other declarations
3006  // that are not simple-declarations.
3007  break;
3009  // FIXME: P0091R3 does not permit class template argument deduction here,
3010  // but we follow GCC and allow it anyway.
3011  if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3012  Error = 17; // 'new' type
3013  break;
3015  Error = 18; // K&R function parameter
3016  break;
3017  }
3018 
3020  Error = 11;
3021 
3022  // In Objective-C it is an error to use 'auto' on a function declarator
3023  // (and everywhere for '__auto_type').
3024  if (D.isFunctionDeclarator() &&
3025  (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3026  Error = 13;
3027 
3028  bool HaveTrailing = false;
3029 
3030  // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
3031  // contains a trailing return type. That is only legal at the outermost
3032  // level. Check all declarator chunks (outermost first) anyway, to give
3033  // better diagnostics.
3034  // We don't support '__auto_type' with trailing return types.
3035  // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
3036  if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
3037  D.hasTrailingReturnType()) {
3038  HaveTrailing = true;
3039  Error = -1;
3040  }
3041 
3042  SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3044  AutoRange = D.getName().getSourceRange();
3045 
3046  if (Error != -1) {
3047  unsigned Kind;
3048  if (Auto) {
3049  switch (Auto->getKeyword()) {
3050  case AutoTypeKeyword::Auto: Kind = 0; break;
3051  case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3052  case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3053  }
3054  } else {
3055  assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3056  "unknown auto type");
3057  Kind = 3;
3058  }
3059 
3060  auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3061  TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3062 
3063  SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3064  << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3065  << QualType(Deduced, 0) << AutoRange;
3066  if (auto *TD = TN.getAsTemplateDecl())
3067  SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3068 
3069  T = SemaRef.Context.IntTy;
3070  D.setInvalidType(true);
3071  } else if (!HaveTrailing &&
3073  // If there was a trailing return type, we already got
3074  // warn_cxx98_compat_trailing_return_type in the parser.
3075  SemaRef.Diag(AutoRange.getBegin(),
3076  D.getContext() ==
3078  ? diag::warn_cxx11_compat_generic_lambda
3079  : IsDeducedReturnType
3080  ? diag::warn_cxx11_compat_deduced_return_type
3081  : diag::warn_cxx98_compat_auto_type_specifier)
3082  << AutoRange;
3083  }
3084  }
3085 
3086  if (SemaRef.getLangOpts().CPlusPlus &&
3087  OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3088  // Check the contexts where C++ forbids the declaration of a new class
3089  // or enumeration in a type-specifier-seq.
3090  unsigned DiagID = 0;
3091  switch (D.getContext()) {
3094  // Class and enumeration definitions are syntactically not allowed in
3095  // trailing return types.
3096  llvm_unreachable("parser should not have allowed this");
3097  break;
3105  // C++11 [dcl.type]p3:
3106  // A type-specifier-seq shall not define a class or enumeration unless
3107  // it appears in the type-id of an alias-declaration (7.1.3) that is not
3108  // the declaration of a template-declaration.
3110  break;
3112  DiagID = diag::err_type_defined_in_alias_template;
3113  break;
3123  DiagID = diag::err_type_defined_in_type_specifier;
3124  break;
3130  // C++ [dcl.fct]p6:
3131  // Types shall not be defined in return or parameter types.
3132  DiagID = diag::err_type_defined_in_param_type;
3133  break;
3135  // C++ 6.4p2:
3136  // The type-specifier-seq shall not contain typedef and shall not declare
3137  // a new class or enumeration.
3138  DiagID = diag::err_type_defined_in_condition;
3139  break;
3140  }
3141 
3142  if (DiagID != 0) {
3143  SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3144  << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3145  D.setInvalidType(true);
3146  }
3147  }
3148 
3149  assert(!T.isNull() && "This function should not return a null type");
3150  return T;
3151 }
3152 
3153 /// Produce an appropriate diagnostic for an ambiguity between a function
3154 /// declarator and a C++ direct-initializer.
3156  DeclaratorChunk &DeclType, QualType RT) {
3157  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3158  assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3159 
3160  // If the return type is void there is no ambiguity.
3161  if (RT->isVoidType())
3162  return;
3163 
3164  // An initializer for a non-class type can have at most one argument.
3165  if (!RT->isRecordType() && FTI.NumParams > 1)
3166  return;
3167 
3168  // An initializer for a reference must have exactly one argument.
3169  if (RT->isReferenceType() && FTI.NumParams != 1)
3170  return;
3171 
3172  // Only warn if this declarator is declaring a function at block scope, and
3173  // doesn't have a storage class (such as 'extern') specified.
3174  if (!D.isFunctionDeclarator() ||
3179  return;
3180 
3181  // Inside a condition, a direct initializer is not permitted. We allow one to
3182  // be parsed in order to give better diagnostics in condition parsing.
3184  return;
3185 
3186  SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3187 
3188  S.Diag(DeclType.Loc,
3189  FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3190  : diag::warn_empty_parens_are_function_decl)
3191  << ParenRange;
3192 
3193  // If the declaration looks like:
3194  // T var1,
3195  // f();
3196  // and name lookup finds a function named 'f', then the ',' was
3197  // probably intended to be a ';'.
3198  if (!D.isFirstDeclarator() && D.getIdentifier()) {
3201  if (Comma.getFileID() != Name.getFileID() ||
3202  Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3205  if (S.LookupName(Result, S.getCurScope()))
3206  S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3208  << D.getIdentifier();
3209  Result.suppressDiagnostics();
3210  }
3211  }
3212 
3213  if (FTI.NumParams > 0) {
3214  // For a declaration with parameters, eg. "T var(T());", suggest adding
3215  // parens around the first parameter to turn the declaration into a
3216  // variable declaration.
3217  SourceRange Range = FTI.Params[0].Param->getSourceRange();
3218  SourceLocation B = Range.getBegin();
3219  SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3220  // FIXME: Maybe we should suggest adding braces instead of parens
3221  // in C++11 for classes that don't have an initializer_list constructor.
3222  S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3223  << FixItHint::CreateInsertion(B, "(")
3224  << FixItHint::CreateInsertion(E, ")");
3225  } else {
3226  // For a declaration without parameters, eg. "T var();", suggest replacing
3227  // the parens with an initializer to turn the declaration into a variable
3228  // declaration.
3229  const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3230 
3231  // Empty parens mean value-initialization, and no parens mean
3232  // default initialization. These are equivalent if the default
3233  // constructor is user-provided or if zero-initialization is a
3234  // no-op.
3235  if (RD && RD->hasDefinition() &&
3236  (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3237  S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3238  << FixItHint::CreateRemoval(ParenRange);
3239  else {
3240  std::string Init =
3241  S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3242  if (Init.empty() && S.LangOpts.CPlusPlus11)
3243  Init = "{}";
3244  if (!Init.empty())
3245  S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3246  << FixItHint::CreateReplacement(ParenRange, Init);
3247  }
3248  }
3249 }
3250 
3251 /// Produce an appropriate diagnostic for a declarator with top-level
3252 /// parentheses.
3255  assert(Paren.Kind == DeclaratorChunk::Paren &&
3256  "do not have redundant top-level parentheses");
3257 
3258  // This is a syntactic check; we're not interested in cases that arise
3259  // during template instantiation.
3260  if (S.inTemplateInstantiation())
3261  return;
3262 
3263  // Check whether this could be intended to be a construction of a temporary
3264  // object in C++ via a function-style cast.
3265  bool CouldBeTemporaryObject =
3266  S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3267  !D.isInvalidType() && D.getIdentifier() &&
3269  (T->isRecordType() || T->isDependentType()) &&
3271 
3272  bool StartsWithDeclaratorId = true;
3273  for (auto &C : D.type_objects()) {
3274  switch (C.Kind) {
3276  if (&C == &Paren)
3277  continue;
3278  LLVM_FALLTHROUGH;
3280  StartsWithDeclaratorId = false;
3281  continue;
3282 
3284  if (!C.Arr.NumElts)
3285  CouldBeTemporaryObject = false;
3286  continue;
3287 
3289  // FIXME: Suppress the warning here if there is no initializer; we're
3290  // going to give an error anyway.
3291  // We assume that something like 'T (&x) = y;' is highly likely to not
3292  // be intended to be a temporary object.
3293  CouldBeTemporaryObject = false;
3294  StartsWithDeclaratorId = false;
3295  continue;
3296 
3298  // In a new-type-id, function chunks require parentheses.
3300  return;
3301  // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3302  // redundant-parens warning, but we don't know whether the function
3303  // chunk was syntactically valid as an expression here.
3304  CouldBeTemporaryObject = false;
3305  continue;
3306 
3309  case DeclaratorChunk::Pipe:
3310  // These cannot appear in expressions.
3311  CouldBeTemporaryObject = false;
3312  StartsWithDeclaratorId = false;
3313  continue;
3314  }
3315  }
3316 
3317  // FIXME: If there is an initializer, assume that this is not intended to be
3318  // a construction of a temporary object.
3319 
3320  // Check whether the name has already been declared; if not, this is not a
3321  // function-style cast.
3322  if (CouldBeTemporaryObject) {
3325  if (!S.LookupName(Result, S.getCurScope()))
3326  CouldBeTemporaryObject = false;
3327  Result.suppressDiagnostics();
3328  }
3329 
3330  SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3331 
3332  if (!CouldBeTemporaryObject) {
3333  // If we have A (::B), the parentheses affect the meaning of the program.
3334  // Suppress the warning in that case. Don't bother looking at the DeclSpec
3335  // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3336  // formally unambiguous.
3337  if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3338  for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3339  NNS = NNS->getPrefix()) {
3340  if (NNS->getKind() == NestedNameSpecifier::Global)
3341  return;
3342  }
3343  }
3344 
3345  S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3346  << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3347  << FixItHint::CreateRemoval(Paren.EndLoc);
3348  return;
3349  }
3350 
3351  S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3352  << ParenRange << D.getIdentifier();
3353  auto *RD = T->getAsCXXRecordDecl();
3354  if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3355  S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3356  << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3357  << D.getIdentifier();
3358  // FIXME: A cast to void is probably a better suggestion in cases where it's
3359  // valid (when there is no initializer and we're not in a condition).
3360  S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3363  S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3364  << FixItHint::CreateRemoval(Paren.Loc)
3365  << FixItHint::CreateRemoval(Paren.EndLoc);
3366 }
3367 
3368 /// Helper for figuring out the default CC for a function declarator type. If
3369 /// this is the outermost chunk, then we can determine the CC from the
3370 /// declarator context. If not, then this could be either a member function
3371 /// type or normal function type.
3373  Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3374  const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3375  assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3376 
3377  // Check for an explicit CC attribute.
3378  for (const ParsedAttr &AL : AttrList) {
3379  switch (AL.getKind()) {
3381  // Ignore attributes that don't validate or can't apply to the
3382  // function type. We'll diagnose the failure to apply them in
3383  // handleFunctionTypeAttr.
3384  CallingConv CC;
3385  if (!S.CheckCallingConvAttr(AL, CC) &&
3386  (!FTI.isVariadic || supportsVariadicCall(CC))) {
3387  return CC;
3388  }
3389  break;
3390  }
3391 
3392  default:
3393  break;
3394  }
3395  }
3396 
3397  bool IsCXXInstanceMethod = false;
3398 
3399  if (S.getLangOpts().CPlusPlus) {
3400  // Look inwards through parentheses to see if this chunk will form a
3401  // member pointer type or if we're the declarator. Any type attributes
3402  // between here and there will override the CC we choose here.
3403  unsigned I = ChunkIndex;
3404  bool FoundNonParen = false;
3405  while (I && !FoundNonParen) {
3406  --I;
3408  FoundNonParen = true;
3409  }
3410 
3411  if (FoundNonParen) {
3412  // If we're not the declarator, we're a regular function type unless we're
3413  // in a member pointer.
3414  IsCXXInstanceMethod =
3417  // This can only be a call operator for a lambda, which is an instance
3418  // method.
3419  IsCXXInstanceMethod = true;
3420  } else {
3421  // We're the innermost decl chunk, so must be a function declarator.
3422  assert(D.isFunctionDeclarator());
3423 
3424  // If we're inside a record, we're declaring a method, but it could be
3425  // explicitly or implicitly static.
3426  IsCXXInstanceMethod =
3429  !D.isStaticMember();
3430  }
3431  }
3432 
3434  IsCXXInstanceMethod);
3435 
3436  // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3437  // and AMDGPU targets, hence it cannot be treated as a calling
3438  // convention attribute. This is the simplest place to infer
3439  // calling convention for OpenCL kernels.
3440  if (S.getLangOpts().OpenCL) {
3441  for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3442  if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
3443  CC = CC_OpenCLKernel;
3444  break;
3445  }
3446  }
3447  }
3448 
3449  return CC;
3450 }
3451 
3452 namespace {
3453  /// A simple notion of pointer kinds, which matches up with the various
3454  /// pointer declarators.
3455  enum class SimplePointerKind {
3456  Pointer,
3457  BlockPointer,
3458  MemberPointer,
3459  Array,
3460  };
3461 } // end anonymous namespace
3462 
3464  switch (nullability) {
3466  if (!Ident__Nonnull)
3467  Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3468  return Ident__Nonnull;
3469 
3471  if (!Ident__Nullable)
3472  Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3473  return Ident__Nullable;
3474 
3476  if (!Ident__Null_unspecified)
3477  Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3478  return Ident__Null_unspecified;
3479  }
3480  llvm_unreachable("Unknown nullability kind.");
3481 }
3482 
3483 /// Retrieve the identifier "NSError".
3485  if (!Ident_NSError)
3486  Ident_NSError = PP.getIdentifierInfo("NSError");
3487 
3488  return Ident_NSError;
3489 }
3490 
3491 /// Check whether there is a nullability attribute of any kind in the given
3492 /// attribute list.
3493 static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3494  for (const ParsedAttr &AL : attrs) {
3495  if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3496  AL.getKind() == ParsedAttr::AT_TypeNullable ||
3497  AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3498  return true;
3499  }
3500 
3501  return false;
3502 }
3503 
3504 namespace {
3505  /// Describes the kind of a pointer a declarator describes.
3507  // Not a pointer.
3508  NonPointer,
3509  // Single-level pointer.
3510  SingleLevelPointer,
3511  // Multi-level pointer (of any pointer kind).
3512  MultiLevelPointer,
3513  // CFFooRef*
3514  MaybePointerToCFRef,
3515  // CFErrorRef*
3516  CFErrorRefPointer,
3517  // NSError**
3518  NSErrorPointerPointer,
3519  };
3520 
3521  /// Describes a declarator chunk wrapping a pointer that marks inference as
3522  /// unexpected.
3523  // These values must be kept in sync with diagnostics.
3525  /// Pointer is top-level.
3526  None = -1,
3527  /// Pointer is an array element.
3528  Array = 0,
3529  /// Pointer is the referent type of a C++ reference.
3530  Reference = 1
3531  };
3532 } // end anonymous namespace
3533 
3534 /// Classify the given declarator, whose type-specified is \c type, based on
3535 /// what kind of pointer it refers to.
3536 ///
3537 /// This is used to determine the default nullability.
3538 static PointerDeclaratorKind
3540  PointerWrappingDeclaratorKind &wrappingKind) {
3541  unsigned numNormalPointers = 0;
3542 
3543  // For any dependent type, we consider it a non-pointer.
3544  if (type->isDependentType())
3545  return PointerDeclaratorKind::NonPointer;
3546 
3547  // Look through the declarator chunks to identify pointers.
3548  for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3549  DeclaratorChunk &chunk = declarator.getTypeObject(i);
3550  switch (chunk.Kind) {
3552  if (numNormalPointers == 0)
3553  wrappingKind = PointerWrappingDeclaratorKind::Array;
3554  break;
3555 
3557  case DeclaratorChunk::Pipe:
3558  break;
3559 
3562  return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3563  : PointerDeclaratorKind::SingleLevelPointer;
3564 
3566  break;
3567 
3569  if (numNormalPointers == 0)
3570  wrappingKind = PointerWrappingDeclaratorKind::Reference;
3571  break;
3572 
3574  ++numNormalPointers;
3575  if (numNormalPointers > 2)
3576  return PointerDeclaratorKind::MultiLevelPointer;
3577  break;
3578  }
3579  }
3580 
3581  // Then, dig into the type specifier itself.
3582  unsigned numTypeSpecifierPointers = 0;
3583  do {
3584  // Decompose normal pointers.
3585  if (auto ptrType = type->getAs<PointerType>()) {
3586  ++numNormalPointers;
3587 
3588  if (numNormalPointers > 2)
3589  return PointerDeclaratorKind::MultiLevelPointer;
3590 
3591  type = ptrType->getPointeeType();
3592  ++numTypeSpecifierPointers;
3593  continue;
3594  }
3595 
3596  // Decompose block pointers.
3597  if (type->getAs<BlockPointerType>()) {
3598  return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3599  : PointerDeclaratorKind::SingleLevelPointer;
3600  }
3601 
3602  // Decompose member pointers.
3603  if (type->getAs<MemberPointerType>()) {
3604  return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3605  : PointerDeclaratorKind::SingleLevelPointer;
3606  }
3607 
3608  // Look at Objective-C object pointers.
3609  if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3610  ++numNormalPointers;
3611  ++numTypeSpecifierPointers;
3612 
3613  // If this is NSError**, report that.
3614  if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3615  if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3616  numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3617  return PointerDeclaratorKind::NSErrorPointerPointer;
3618  }
3619  }
3620 
3621  break;
3622  }
3623 
3624  // Look at Objective-C class types.
3625  if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3626  if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3627  if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3628  return PointerDeclaratorKind::NSErrorPointerPointer;
3629  }
3630 
3631  break;
3632  }
3633 
3634  // If at this point we haven't seen a pointer, we won't see one.
3635  if (numNormalPointers == 0)
3636  return PointerDeclaratorKind::NonPointer;
3637 
3638  if (auto recordType = type->getAs<RecordType>()) {
3639  RecordDecl *recordDecl = recordType->getDecl();
3640 
3641  bool isCFError = false;
3642  if (S.CFError) {
3643  // If we already know about CFError, test it directly.
3644  isCFError = (S.CFError == recordDecl);
3645  } else {
3646  // Check whether this is CFError, which we identify based on its bridge
3647  // to NSError. CFErrorRef used to be declared with "objc_bridge" but is
3648  // now declared with "objc_bridge_mutable", so look for either one of
3649  // the two attributes.
3650  if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3651  IdentifierInfo *bridgedType = nullptr;
3652  if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>())
3653  bridgedType = bridgeAttr->getBridgedType();
3654  else if (auto bridgeAttr =
3655  recordDecl->getAttr<ObjCBridgeMutableAttr>())
3656  bridgedType = bridgeAttr->getBridgedType();
3657 
3658  if (bridgedType == S.getNSErrorIdent()) {
3659  S.CFError = recordDecl;
3660  isCFError = true;
3661  }
3662  }
3663  }
3664 
3665  // If this is CFErrorRef*, report it as such.
3666  if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3667  return PointerDeclaratorKind::CFErrorRefPointer;
3668  }
3669  break;
3670  }
3671 
3672  break;
3673  } while (true);
3674 
3675  switch (numNormalPointers) {
3676  case 0:
3677  return PointerDeclaratorKind::NonPointer;
3678 
3679  case 1:
3680  return PointerDeclaratorKind::SingleLevelPointer;
3681 
3682  case 2:
3683  return PointerDeclaratorKind::MaybePointerToCFRef;
3684 
3685  default:
3686  return PointerDeclaratorKind::MultiLevelPointer;
3687  }
3688 }
3689 
3691  SourceLocation loc) {
3692  // If we're anywhere in a function, method, or closure context, don't perform
3693  // completeness checks.
3694  for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3695  if (ctx->isFunctionOrMethod())
3696  return FileID();
3697 
3698  if (ctx->isFileContext())
3699  break;
3700  }
3701 
3702  // We only care about the expansion location.
3703  loc = S.SourceMgr.getExpansionLoc(loc);
3704  FileID file = S.SourceMgr.getFileID(loc);
3705  if (file.isInvalid())
3706  return FileID();
3707 
3708  // Retrieve file information.
3709  bool invalid = false;
3710  const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3711  if (invalid || !sloc.isFile())
3712  return FileID();
3713 
3714  // We don't want to perform completeness checks on the main file or in
3715  // system headers.
3716  const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3717  if (fileInfo.getIncludeLoc().isInvalid())
3718  return FileID();
3719  if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3721  return FileID();
3722  }
3723 
3724  return file;
3725 }
3726 
3727 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
3728 /// taking into account whitespace before and after.
3730  SourceLocation PointerLoc,
3732  assert(PointerLoc.isValid());
3733  if (PointerLoc.isMacroID())
3734  return;
3735 
3736  SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
3737  if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
3738  return;
3739 
3740  const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
3741  if (!NextChar)
3742  return;
3743 
3744  SmallString<32> InsertionTextBuf{" "};
3745  InsertionTextBuf += getNullabilitySpelling(Nullability);
3746  InsertionTextBuf += " ";
3747  StringRef InsertionText = InsertionTextBuf.str();
3748 
3749  if (isWhitespace(*NextChar)) {
3750  InsertionText = InsertionText.drop_back();
3751  } else if (NextChar[-1] == '[') {
3752  if (NextChar[0] == ']')
3753  InsertionText = InsertionText.drop_back().drop_front();
3754  else
3755  InsertionText = InsertionText.drop_front();
3756  } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
3757  !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
3758  InsertionText = InsertionText.drop_back().drop_front();
3759  }
3760 
3761  Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
3762 }
3763 
3765  SimplePointerKind PointerKind,
3766  SourceLocation PointerLoc,
3767  SourceLocation PointerEndLoc) {
3768  assert(PointerLoc.isValid());
3769 
3770  if (PointerKind == SimplePointerKind::Array) {
3771  S.Diag(PointerLoc, diag::warn_nullability_missing_array);
3772  } else {
3773  S.Diag(PointerLoc, diag::warn_nullability_missing)
3774  << static_cast<unsigned>(PointerKind);
3775  }
3776 
3777  auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
3778  if (FixItLoc.isMacroID())
3779  return;
3780 
3781  auto addFixIt = [&](NullabilityKind Nullability) {
3782  auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
3783  Diag << static_cast<unsigned>(Nullability);
3784  Diag << static_cast<unsigned>(PointerKind);
3785  fixItNullability(S, Diag, FixItLoc, Nullability);
3786  };
3787  addFixIt(NullabilityKind::Nullable);
3788  addFixIt(NullabilityKind::NonNull);
3789 }
3790 
3791 /// Complains about missing nullability if the file containing \p pointerLoc
3792 /// has other uses of nullability (either the keywords or the \c assume_nonnull
3793 /// pragma).
3794 ///
3795 /// If the file has \e not seen other uses of nullability, this particular
3796 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
3797 static void
3799  SourceLocation pointerLoc,
3800  SourceLocation pointerEndLoc = SourceLocation()) {
3801  // Determine which file we're performing consistency checking for.
3802  FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3803  if (file.isInvalid())
3804  return;
3805 
3806  // If we haven't seen any type nullability in this file, we won't warn now
3807  // about anything.
3808  FileNullability &fileNullability = S.NullabilityMap[file];
3809  if (!fileNullability.SawTypeNullability) {
3810  // If this is the first pointer declarator in the file, and the appropriate
3811  // warning is on, record it in case we need to diagnose it retroactively.
3812  diag::kind diagKind;
3813  if (pointerKind == SimplePointerKind::Array)
3814  diagKind = diag::warn_nullability_missing_array;
3815  else
3816  diagKind = diag::warn_nullability_missing;
3817 
3818  if (fileNullability.PointerLoc.isInvalid() &&
3819  !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
3820  fileNullability.PointerLoc = pointerLoc;
3821  fileNullability.PointerEndLoc = pointerEndLoc;
3822  fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3823  }
3824 
3825  return;
3826  }
3827 
3828  // Complain about missing nullability.
3829  emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
3830 }
3831 
3832 /// Marks that a nullability feature has been used in the file containing
3833 /// \p loc.
3834 ///
3835 /// If this file already had pointer types in it that were missing nullability,
3836 /// the first such instance is retroactively diagnosed.
3837 ///
3838 /// \sa checkNullabilityConsistency
3841  if (file.isInvalid())
3842  return;
3843 
3844  FileNullability &fileNullability = S.NullabilityMap[file];
3845  if (fileNullability.SawTypeNullability)
3846  return;
3847  fileNullability.SawTypeNullability = true;
3848 
3849  // If we haven't seen any type nullability before, now we have. Retroactively
3850  // diagnose the first unannotated pointer, if there was one.
3851  if (fileNullability.PointerLoc.isInvalid())
3852  return;
3853 
3854  auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
3856  fileNullability.PointerEndLoc);
3857 }
3858 
3859 /// Returns true if any of the declarator chunks before \p endIndex include a
3860 /// level of indirection: array, pointer, reference, or pointer-to-member.
3861 ///
3862 /// Because declarator chunks are stored in outer-to-inner order, testing
3863 /// every chunk before \p endIndex is testing all chunks that embed the current
3864 /// chunk as part of their type.
3865 ///
3866 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
3867 /// end index, in which case all chunks are tested.
3868 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
3869  unsigned i = endIndex;
3870  while (i != 0) {
3871  // Walk outwards along the declarator chunks.
3872  --i;
3873  const DeclaratorChunk &DC = D.getTypeObject(i);
3874  switch (DC.Kind) {
3876  break;
3881  return true;
3884  case DeclaratorChunk::Pipe:
3885  // These are invalid anyway, so just ignore.
3886  break;
3887  }
3888  }
3889  return false;
3890 }
3891 
3893  return (Chunk.Kind == DeclaratorChunk::Pointer ||
3894  Chunk.Kind == DeclaratorChunk::Array);
3895 }
3896 
3897 template<typename AttrT>
3899  Attr.setUsedAsTypeAttr();
3900  return ::new (Ctx)
3901  AttrT(Attr.getRange(), Ctx, Attr.getAttributeSpellingListIndex());
3902 }
3903 
3905  NullabilityKind NK) {
3906  switch (NK) {
3908  return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
3909 
3911  return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
3912 
3914  return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
3915  }
3916  llvm_unreachable("unknown NullabilityKind");
3917 }
3918 
3919 static TypeSourceInfo *
3920 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3921  QualType T, TypeSourceInfo *ReturnTypeInfo);
3922 
3923 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3924  QualType declSpecType,
3925  TypeSourceInfo *TInfo) {
3926  // The TypeSourceInfo that this function returns will not be a null type.
3927  // If there is an error, this function will fill in a dummy type as fallback.
3928  QualType T = declSpecType;
3929  Declarator &D = state.getDeclarator();
3930  Sema &S = state.getSema();
3931  ASTContext &Context = S.Context;
3932  const LangOptions &LangOpts = S.getLangOpts();
3933 
3934  // The name we're declaring, if any.
3935  DeclarationName Name;
3936  if (D.getIdentifier())
3937  Name = D.getIdentifier();
3938 
3939  // Does this declaration declare a typedef-name?
3940  bool IsTypedefName =
3944 
3945  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3946  bool IsQualifiedFunction = T->isFunctionProtoType() &&
3947  (!T->castAs<FunctionProtoType>()->getTypeQuals().empty() ||
3948  T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3949 
3950  // If T is 'decltype(auto)', the only declarators we can have are parens
3951  // and at most one function declarator if this is a function declaration.
3952  // If T is a deduced class template specialization type, we can have no
3953  // declarator chunks at all.
3954  if (auto *DT = T->getAs<DeducedType>()) {
3955  const AutoType *AT = T->getAs<AutoType>();
3956  bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
3957  if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
3958  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3959  unsigned Index = E - I - 1;
3960  DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3961  unsigned DiagId = IsClassTemplateDeduction
3962  ? diag::err_deduced_class_template_compound_type
3963  : diag::err_decltype_auto_compound_type;
3964  unsigned DiagKind = 0;
3965  switch (DeclChunk.Kind) {
3967  // FIXME: Rejecting this is a little silly.
3968  if (IsClassTemplateDeduction) {
3969  DiagKind = 4;
3970  break;
3971  }
3972  continue;
3974  if (IsClassTemplateDeduction) {
3975  DiagKind = 3;
3976  break;
3977  }
3978  unsigned FnIndex;
3979  if (D.isFunctionDeclarationContext() &&
3980  D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3981  continue;
3982  DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3983  break;
3984  }
3988  DiagKind = 0;
3989  break;
3991  DiagKind = 1;
3992  break;
3994  DiagKind = 2;
3995  break;
3996  case DeclaratorChunk::Pipe:
3997  break;
3998  }
3999 
4000  S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4001  D.setInvalidType(true);
4002  break;
4003  }
4004  }
4005  }
4006 
4007  // Determine whether we should infer _Nonnull on pointer types.
4008  Optional<NullabilityKind> inferNullability;
4009  bool inferNullabilityCS = false;
4010  bool inferNullabilityInnerOnly = false;
4011  bool inferNullabilityInnerOnlyComplete = false;
4012 
4013  // Are we in an assume-nonnull region?
4014  bool inAssumeNonNullRegion = false;
4015  SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4016  if (assumeNonNullLoc.isValid()) {
4017  inAssumeNonNullRegion = true;
4018  recordNullabilitySeen(S, assumeNonNullLoc);
4019  }
4020 
4021  // Whether to complain about missing nullability specifiers or not.
4022  enum {
4023  /// Never complain.
4024  CAMN_No,
4025  /// Complain on the inner pointers (but not the outermost
4026  /// pointer).
4027  CAMN_InnerPointers,
4028  /// Complain about any pointers that don't have nullability
4029  /// specified or inferred.
4030  CAMN_Yes
4031  } complainAboutMissingNullability = CAMN_No;
4032  unsigned NumPointersRemaining = 0;
4033  auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4034 
4035  if (IsTypedefName) {
4036  // For typedefs, we do not infer any nullability (the default),
4037  // and we only complain about missing nullability specifiers on
4038  // inner pointers.
4039  complainAboutMissingNullability = CAMN_InnerPointers;
4040 
4041  if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4042  !T->getNullability(S.Context)) {
4043  // Note that we allow but don't require nullability on dependent types.
4044  ++NumPointersRemaining;
4045  }
4046 
4047  for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4048  DeclaratorChunk &chunk = D.getTypeObject(i);
4049  switch (chunk.Kind) {
4052  case DeclaratorChunk::Pipe:
4053  break;
4054 
4057  ++NumPointersRemaining;
4058  break;
4059 
4062  continue;
4063 
4065  ++NumPointersRemaining;
4066  continue;
4067  }
4068  }
4069  } else {
4070  bool isFunctionOrMethod = false;
4071  switch (auto context = state.getDeclarator().getContext()) {
4077  isFunctionOrMethod = true;
4078  LLVM_FALLTHROUGH;
4079 
4081  if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4082  complainAboutMissingNullability = CAMN_No;
4083  break;
4084  }
4085 
4086  // Weak properties are inferred to be nullable.
4087  if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
4088  inferNullability = NullabilityKind::Nullable;
4089  break;
4090  }
4091 
4092  LLVM_FALLTHROUGH;
4093 
4096  complainAboutMissingNullability = CAMN_Yes;
4097 
4098  // Nullability inference depends on the type and declarator.
4099  auto wrappingKind = PointerWrappingDeclaratorKind::None;
4100  switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4101  case PointerDeclaratorKind::NonPointer:
4102  case PointerDeclaratorKind::MultiLevelPointer:
4103  // Cannot infer nullability.
4104  break;
4105 
4106  case PointerDeclaratorKind::SingleLevelPointer:
4107  // Infer _Nonnull if we are in an assumes-nonnull region.
4108  if (inAssumeNonNullRegion) {
4109  complainAboutInferringWithinChunk = wrappingKind;
4110  inferNullability = NullabilityKind::NonNull;
4111  inferNullabilityCS =
4114  }
4115  break;
4116 
4117  case PointerDeclaratorKind::CFErrorRefPointer:
4118  case PointerDeclaratorKind::NSErrorPointerPointer:
4119  // Within a function or method signature, infer _Nullable at both
4120  // levels.
4121  if (isFunctionOrMethod && inAssumeNonNullRegion)
4122  inferNullability = NullabilityKind::Nullable;
4123  break;
4124 
4125  case PointerDeclaratorKind::MaybePointerToCFRef:
4126  if (isFunctionOrMethod) {
4127  // On pointer-to-pointer parameters marked cf_returns_retained or
4128  // cf_returns_not_retained, if the outer pointer is explicit then
4129  // infer the inner pointer as _Nullable.
4130  auto hasCFReturnsAttr =
4131  [](const ParsedAttributesView &AttrList) -> bool {
4132  return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4133  AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4134  };
4135  if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4136  if (hasCFReturnsAttr(D.getAttributes()) ||
4137  hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4138  hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4139  inferNullability = NullabilityKind::Nullable;
4140  inferNullabilityInnerOnly = true;
4141  }
4142  }
4143  }
4144  break;
4145  }
4146  break;
4147  }
4148 
4150  complainAboutMissingNullability = CAMN_Yes;
4151  break;
4152 
4170  // Don't infer in these contexts.
4171  break;
4172  }
4173  }
4174 
4175  // Local function that returns true if its argument looks like a va_list.
4176  auto isVaList = [&S](QualType T) -> bool {
4177  auto *typedefTy = T->getAs<TypedefType>();
4178  if (!typedefTy)
4179  return false;
4180  TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4181  do {
4182  if (typedefTy->getDecl() == vaListTypedef)
4183  return true;
4184  if (auto *name = typedefTy->getDecl()->getIdentifier())
4185  if (name->isStr("va_list"))
4186  return true;
4187  typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4188  } while (typedefTy);
4189  return false;
4190  };
4191 
4192  // Local function that checks the nullability for a given pointer declarator.
4193  // Returns true if _Nonnull was inferred.
4194  auto inferPointerNullability =
4195  [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4196  SourceLocation pointerEndLoc,
4197  ParsedAttributesView &attrs) -> ParsedAttr * {
4198  // We've seen a pointer.
4199  if (NumPointersRemaining > 0)
4200  --NumPointersRemaining;
4201 
4202  // If a nullability attribute is present, there's nothing to do.
4203  if (hasNullabilityAttr(attrs))
4204  return nullptr;
4205 
4206  // If we're supposed to infer nullability, do so now.
4207  if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4208  ParsedAttr::Syntax syntax = inferNullabilityCS
4211  ParsedAttr *nullabilityAttr =
4212  state.getDeclarator().getAttributePool().create(
4213  S.getNullabilityKeyword(*inferNullability),
4214  SourceRange(pointerLoc), nullptr, SourceLocation(), nullptr, 0,
4215  syntax);
4216 
4217  attrs.addAtEnd(nullabilityAttr);
4218 
4219  if (inferNullabilityCS) {
4220  state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4221  ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4222  }
4223 
4224  if (pointerLoc.isValid() &&
4225  complainAboutInferringWithinChunk !=
4227  auto Diag =
4228  S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4229  Diag << static_cast<int>(complainAboutInferringWithinChunk);
4231  }
4232 
4233  if (inferNullabilityInnerOnly)
4234  inferNullabilityInnerOnlyComplete = true;
4235  return nullabilityAttr;
4236  }
4237 
4238  // If we're supposed to complain about missing nullability, do so
4239  // now if it's truly missing.
4240  switch (complainAboutMissingNullability) {
4241  case CAMN_No:
4242  break;
4243 
4244  case CAMN_InnerPointers:
4245  if (NumPointersRemaining == 0)
4246  break;
4247  LLVM_FALLTHROUGH;
4248 
4249  case CAMN_Yes:
4250  checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4251  }
4252  return nullptr;
4253  };
4254 
4255  // If the type itself could have nullability but does not, infer pointer
4256  // nullability and perform consistency checking.
4257  if (S.CodeSynthesisContexts.empty()) {
4258  if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4259  !T->getNullability(S.Context)) {
4260  if (isVaList(T)) {
4261  // Record that we've seen a pointer, but do nothing else.
4262  if (NumPointersRemaining > 0)
4263  --NumPointersRemaining;
4264  } else {
4265  SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4266  if (T->isBlockPointerType())
4267  pointerKind = SimplePointerKind::BlockPointer;
4268  else if (T->isMemberPointerType())
4269  pointerKind = SimplePointerKind::MemberPointer;
4270 
4271  if (auto *attr = inferPointerNullability(
4272  pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4273  D.getDeclSpec().getEndLoc(),
4275  T = state.getAttributedType(
4276  createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4277  }
4278  }
4279  }
4280 
4281  if (complainAboutMissingNullability == CAMN_Yes &&
4282  T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4283  D.isPrototypeContext() &&
4285  checkNullabilityConsistency(S, SimplePointerKind::Array,
4287  }
4288  }
4289 
4290  bool ExpectNoDerefChunk =
4291  state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4292 
4293  // Walk the DeclTypeInfo, building the recursive type as we go.
4294  // DeclTypeInfos are ordered from the identifier out, which is
4295  // opposite of what we want :).
4296  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4297  unsigned chunkIndex = e - i - 1;
4298  state.setCurrentChunkIndex(chunkIndex);
4299  DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4300  IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4301  switch (DeclType.Kind) {
4303  if (i == 0)
4304  warnAboutRedundantParens(S, D, T);
4305  T = S.BuildParenType(T);
4306  break;
4308  // If blocks are disabled, emit an error.
4309  if (!LangOpts.Blocks)
4310  S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4311 
4312  // Handle pointer nullability.
4313  inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4314  DeclType.EndLoc, DeclType.getAttrs());
4315 
4316  T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4317  if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4318  // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4319  // qualified with const.
4320  if (LangOpts.OpenCL)
4321  DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4322  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4323  }
4324  break;
4326  // Verify that we're not building a pointer to pointer to function with
4327  // exception specification.
4328  if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4329  S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4330  D.setInvalidType(true);
4331  // Build the type anyway.
4332  }
4333 
4334  // Handle pointer nullability
4335  inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4336  DeclType.EndLoc, DeclType.getAttrs());
4337 
4338  if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4339  T = Context.getObjCObjectPointerType(T);
4340  if (DeclType.Ptr.TypeQuals)
4341  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4342  break;
4343  }
4344 
4345  // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4346  // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4347  // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4348  if (LangOpts.OpenCL) {
4349  if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4350  T->isBlockPointerType()) {
4351  S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4352  D.setInvalidType(true);
4353  }
4354  }
4355 
4356  T = S.BuildPointerType(T, DeclType.Loc, Name);
4357  if (DeclType.Ptr.TypeQuals)
4358  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4359  break;
4361  // Verify that we're not building a reference to pointer to function with
4362  // exception specification.
4363  if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4364  S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4365  D.setInvalidType(true);
4366  // Build the type anyway.
4367  }
4368  T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4369 
4370  if (DeclType.Ref.HasRestrict)
4371  T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4372  break;
4373  }
4374  case DeclaratorChunk::Array: {
4375  // Verify that we're not building an array of pointers to function with
4376  // exception specification.
4377  if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4378  S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4379  D.setInvalidType(true);
4380  // Build the type anyway.
4381  }
4382  DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4383  Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4385  if (ATI.isStar)
4386  ASM = ArrayType::Star;
4387  else if (ATI.hasStatic)
4388  ASM = ArrayType::Static;
4389  else
4390  ASM = ArrayType::Normal;
4391  if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4392  // FIXME: This check isn't quite right: it allows star in prototypes
4393  // for function definitions, and disallows some edge cases detailed
4394  // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4395  S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4396  ASM = ArrayType::Normal;
4397  D.setInvalidType(true);
4398  }
4399 
4400  // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4401  // shall appear only in a declaration of a function parameter with an
4402  // array type, ...
4403  if (ASM == ArrayType::Static || ATI.TypeQuals) {
4404  if (!(D.isPrototypeContext() ||
4406  S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4407  (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4408  // Remove the 'static' and the type qualifiers.
4409  if (ASM == ArrayType::Static)
4410  ASM = ArrayType::Normal;
4411  ATI.TypeQuals = 0;
4412  D.setInvalidType(true);
4413  }
4414 
4415  // C99 6.7.5.2p1: ... and then only in the outermost array type
4416  // derivation.
4417  if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4418  S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4419  (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4420  if (ASM == ArrayType::Static)
4421  ASM = ArrayType::Normal;
4422  ATI.TypeQuals = 0;
4423  D.setInvalidType(true);
4424  }
4425  }
4426  const AutoType *AT = T->getContainedAutoType();
4427  // Allow arrays of auto if we are a generic lambda parameter.
4428  // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4429  if (AT &&
4431  // We've already diagnosed this for decltype(auto).
4432  if (!AT->isDecltypeAuto())
4433  S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4434  << getPrintableNameForEntity(Name) << T;
4435  T = QualType();
4436  break;
4437  }
4438 
4439  // Array parameters can be marked nullable as well, although it's not
4440  // necessary if they're marked 'static'.
4441  if (complainAboutMissingNullability == CAMN_Yes &&
4442  !hasNullabilityAttr(DeclType.getAttrs()) &&
4443  ASM != ArrayType::Static &&
4444  D.isPrototypeContext() &&
4445  !hasOuterPointerLikeChunk(D, chunkIndex)) {
4446  checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4447  }
4448 
4449  T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4450  SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4451  break;
4452  }
4454  // If the function declarator has a prototype (i.e. it is not () and
4455  // does not have a K&R-style identifier list), then the arguments are part
4456  // of the type, otherwise the argument list is ().
4457  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4458  IsQualifiedFunction =
4460 
4461  // Check for auto functions and trailing return type and adjust the
4462  // return type accordingly.
4463  if (!D.isInvalidType()) {
4464  // trailing-return-type is only required if we're declaring a function,
4465  // and not, for instance, a pointer to a function.
4466  if (D.getDeclSpec().hasAutoTypeSpec() &&
4467  !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4468  if (!S.getLangOpts().CPlusPlus14) {
4471  ? diag::err_auto_missing_trailing_return
4472  : diag::err_deduced_return_type);
4473  T = Context.IntTy;
4474  D.setInvalidType(true);
4475  } else {
4477  diag::warn_cxx11_compat_deduced_return_type);
4478  }
4479  } else if (FTI.hasTrailingReturnType()) {
4480  // T must be exactly 'auto' at this point. See CWG issue 681.
4481  if (isa<ParenType>(T)) {
4482  S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4483  << T << D.getSourceRange();
4484  D.setInvalidType(true);
4485  } else if (D.getName().getKind() ==
4487  if (T != Context.DependentTy) {
4488  S.Diag(D.getDeclSpec().getBeginLoc(),
4489  diag::err_deduction_guide_with_complex_decl)
4490  << D.getSourceRange();
4491  D.setInvalidType(true);
4492  }
4494  (T.hasQualifiers() || !isa<AutoType>(T) ||
4495  cast<AutoType>(T)->getKeyword() !=
4498  diag::err_trailing_return_without_auto)
4499  << T << D.getDeclSpec().getSourceRange();
4500  D.setInvalidType(true);
4501  }
4502  T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4503  if (T.isNull()) {
4504  // An error occurred parsing the trailing return type.
4505  T = Context.IntTy;
4506  D.setInvalidType(true);
4507  }
4508  } else {
4509  // This function type is not the type of the entity being declared,
4510  // so checking the 'auto' is not the responsibility of this chunk.
4511  }
4512  }
4513 
4514  // C99 6.7.5.3p1: The return type may not be a function or array type.
4515  // For conversion functions, we'll diagnose this particular error later.
4516  if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4517  (D.getName().getKind() !=
4519  unsigned diagID = diag::err_func_returning_array_function;
4520  // Last processing chunk in block context means this function chunk
4521  // represents the block.
4522  if (chunkIndex == 0 &&
4524  diagID = diag::err_block_returning_array_function;
4525  S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4526  T = Context.IntTy;
4527  D.setInvalidType(true);
4528  }
4529 
4530  // Do not allow returning half FP value.
4531  // FIXME: This really should be in BuildFunctionType.
4532  if (T->isHalfType()) {
4533  if (S.getLangOpts().OpenCL) {
4534  if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4535  S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4536  << T << 0 /*pointer hint*/;
4537  D.setInvalidType(true);
4538  }
4539  } else if (!S.getLangOpts().HalfArgsAndReturns) {
4540  S.Diag(D.getIdentifierLoc(),
4541  diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4542  D.setInvalidType(true);
4543  }
4544  }
4545 
4546  if (LangOpts.OpenCL) {
4547  // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4548  // function.
4549  if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4550  T->isPipeType()) {
4551  S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4552  << T << 1 /*hint off*/;
4553  D.setInvalidType(true);
4554  }
4555  // OpenCL doesn't support variadic functions and blocks
4556  // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4557  // We also allow here any toolchain reserved identifiers.
4558  if (FTI.isVariadic &&
4559  !(D.getIdentifier() &&
4560  ((D.getIdentifier()->getName() == "printf" &&
4561  LangOpts.OpenCLVersion >= 120) ||
4562  D.getIdentifier()->getName().startswith("__")))) {
4563  S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4564  D.setInvalidType(true);
4565  }
4566  }
4567 
4568  // Methods cannot return interface types. All ObjC objects are
4569  // passed by reference.
4570  if (T->isObjCObjectType()) {
4571  SourceLocation DiagLoc, FixitLoc;
4572  if (TInfo) {
4573  DiagLoc = TInfo->getTypeLoc().getBeginLoc();
4574  FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
4575  } else {
4576  DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4577  FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
4578  }
4579  S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4580  << 0 << T
4581  << FixItHint::CreateInsertion(FixitLoc, "*");
4582 
4583  T = Context.getObjCObjectPointerType(T);
4584  if (TInfo) {
4585  TypeLocBuilder TLB;
4586  TLB.pushFullCopy(TInfo->getTypeLoc());
4588  TLoc.setStarLoc(FixitLoc);
4589  TInfo = TLB.getTypeSourceInfo(Context, T);
4590  }
4591 
4592  D.setInvalidType(true);
4593  }
4594 
4595  // cv-qualifiers on return types are pointless except when the type is a
4596  // class type in C++.
4597  if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4598  !(S.getLangOpts().CPlusPlus &&
4599  (T->isDependentType() || T->isRecordType()))) {
4600  if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4602  // [6.9.1/3] qualified void return is invalid on a C
4603  // function definition. Apparently ok on declarations and
4604  // in C++ though (!)
4605  S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4606  } else
4607  diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4608  }
4609 
4610  // Objective-C ARC ownership qualifiers are ignored on the function
4611  // return type (by type canonicalization). Complain if this attribute
4612  // was written here.
4613  if (T.getQualifiers().hasObjCLifetime()) {
4614  SourceLocation AttrLoc;
4615  if (chunkIndex + 1 < D.getNumTypeObjects()) {
4616  DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4617  for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
4618  if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
4619  AttrLoc = AL.getLoc();
4620  break;
4621  }
4622  }
4623  }
4624  if (AttrLoc.isInvalid()) {
4625  for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4626  if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
4627  AttrLoc = AL.getLoc();
4628  break;
4629  }
4630  }
4631  }
4632 
4633  if (AttrLoc.isValid()) {
4634  // The ownership attributes are almost always written via
4635  // the predefined
4636  // __strong/__weak/__autoreleasing/__unsafe_unretained.
4637  if (AttrLoc.isMacroID())
4638  AttrLoc =
4640 
4641  S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4642  << T.getQualifiers().getObjCLifetime();
4643  }
4644  }
4645 
4646  if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4647  // C++ [dcl.fct]p6:
4648  // Types shall not be defined in return or parameter types.
4649  TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4650  S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4651  << Context.getTypeDeclType(Tag);
4652  }
4653 
4654  // Exception specs are not allowed in typedefs. Complain, but add it
4655  // anyway.
4656  if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
4657  S.Diag(FTI.getExceptionSpecLocBeg(),
4658  diag::err_exception_spec_in_typedef)
4661 
4662  // If we see "T var();" or "T var(T());" at block scope, it is probably
4663  // an attempt to initialize a variable, not a function declaration.
4664  if (FTI.isAmbiguous)
4665  warnAboutAmbiguousFunction(S, D, DeclType, T);
4666 
4668  getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
4669 
4670  if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
4671  && !LangOpts.OpenCL) {
4672  // Simple void foo(), where the incoming T is the result type.
4673  T = Context.getFunctionNoProtoType(T, EI);
4674  } else {
4675  // We allow a zero-parameter variadic function in C if the
4676  // function is marked with the "overloadable" attribute. Scan
4677  // for this attribute now.
4678  if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus)
4679  if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable))
4680  S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4681 
4682  if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4683  // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4684  // definition.
4685  S.Diag(FTI.Params[0].IdentLoc,
4686  diag::err_ident_list_in_fn_declaration);
4687  D.setInvalidType(true);
4688  // Recover by creating a K&R-style function type.
4689  T = Context.getFunctionNoProtoType(T, EI);
4690  break;
4691  }
4692 
4694  EPI.ExtInfo = EI;
4695  EPI.Variadic = FTI.isVariadic;
4699  : 0);
4700  EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4702  : RQ_RValue;
4703 
4704  // Otherwise, we have a function with a parameter list that is
4705  // potentially variadic.
4706  SmallVector<QualType, 16> ParamTys;
4707  ParamTys.reserve(FTI.NumParams);
4708 
4710  ExtParameterInfos(FTI.NumParams);
4711  bool HasAnyInterestingExtParameterInfos = false;
4712 
4713  for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4714  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4715  QualType ParamTy = Param->getType();
4716  assert(!ParamTy.isNull() && "Couldn't parse type?");
4717 
4718  // Look for 'void'. void is allowed only as a single parameter to a
4719  // function with no other parameters (C99 6.7.5.3p10). We record
4720  // int(void) as a FunctionProtoType with an empty parameter list.
4721  if (ParamTy->isVoidType()) {
4722  // If this is something like 'float(int, void)', reject it. 'void'
4723  // is an incomplete type (C99 6.2.5p19) and function decls cannot
4724  // have parameters of incomplete type.
4725  if (FTI.NumParams != 1 || FTI.isVariadic) {
4726  S.Diag(DeclType.Loc, diag::err_void_only_param);
4727  ParamTy = Context.IntTy;
4728  Param->setType(ParamTy);
4729  } else if (FTI.Params[i].Ident) {
4730  // Reject, but continue to parse 'int(void abc)'.
4731  S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4732  ParamTy = Context.IntTy;
4733  Param->setType(ParamTy);
4734  } else {
4735  // Reject, but continue to parse 'float(const void)'.
4736  if (ParamTy.hasQualifiers())
4737  S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4738 
4739  // Do not add 'void' to the list.
4740  break;
4741  }
4742  } else if (ParamTy->isHalfType()) {
4743  // Disallow half FP parameters.
4744  // FIXME: This really should be in BuildFunctionType.
4745  if (S.getLangOpts().OpenCL) {
4746  if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4747  S.Diag(Param->getLocation(),
4748  diag::err_opencl_half_param) << ParamTy;
4749  D.setInvalidType();
4750  Param->setInvalidDecl();
4751  }
4752  } else if (!S.getLangOpts().HalfArgsAndReturns) {
4753  S.Diag(Param->getLocation(),
4754  diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4755  D.setInvalidType();
4756  }
4757  } else if (!FTI.hasPrototype) {
4758  if (ParamTy->isPromotableIntegerType()) {
4759  ParamTy = Context.getPromotedIntegerType(ParamTy);
4760  Param->setKNRPromoted(true);
4761  } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4762  if (BTy->getKind() == BuiltinType::Float) {
4763  ParamTy = Context.DoubleTy;
4764  Param->setKNRPromoted(true);
4765  }
4766  }
4767  }
4768 
4769  if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4770  ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4771  HasAnyInterestingExtParameterInfos = true;
4772  }
4773 
4774  if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4775  ExtParameterInfos[i] =
4776  ExtParameterInfos[i].withABI(attr->getABI());
4777  HasAnyInterestingExtParameterInfos = true;
4778  }
4779 
4780  if (Param->hasAttr<PassObjectSizeAttr>()) {
4781  ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
4782  HasAnyInterestingExtParameterInfos = true;
4783  }
4784 
4785  if (Param->hasAttr<NoEscapeAttr>()) {
4786  ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
4787  HasAnyInterestingExtParameterInfos = true;
4788  }
4789 
4790  ParamTys.push_back(ParamTy);
4791  }
4792 
4793  if (HasAnyInterestingExtParameterInfos) {
4794  EPI.ExtParameterInfos = ExtParameterInfos.data();
4795  checkExtParameterInfos(S, ParamTys, EPI,
4796  [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4797  }
4798 
4799  SmallVector<QualType, 4> Exceptions;
4800  SmallVector<ParsedType, 2> DynamicExceptions;
4801  SmallVector<SourceRange, 2> DynamicExceptionRanges;
4802  Expr *NoexceptExpr = nullptr;
4803 
4804  if (FTI.getExceptionSpecType() == EST_Dynamic) {
4805  // FIXME: It's rather inefficient to have to split into two vectors
4806  // here.
4807  unsigned N = FTI.getNumExceptions();
4808  DynamicExceptions.reserve(N);
4809  DynamicExceptionRanges.reserve(N);
4810  for (unsigned I = 0; I != N; ++I) {
4811  DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4812  DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4813  }
4814  } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
4815  NoexceptExpr = FTI.NoexceptExpr;
4816  }
4817 
4819  FTI.getExceptionSpecType(),
4820  DynamicExceptions,
4821  DynamicExceptionRanges,
4822  NoexceptExpr,
4823  Exceptions,
4824  EPI.ExceptionSpec);
4825 
4826  const auto &Spec = D.getCXXScopeSpec();
4827  // OpenCLCPlusPlus: A class member function has an address space.
4828  if (state.getSema().getLangOpts().OpenCLCPlusPlus &&
4829  ((!Spec.isEmpty() &&
4830  Spec.getScopeRep()->getKind() == NestedNameSpecifier::TypeSpec) ||
4831  state.getDeclarator().getContext() ==
4833  LangAS CurAS = EPI.TypeQuals.getAddressSpace();
4834  // If a class member function's address space is not set, set it to
4835  // __generic.
4836  LangAS AS =
4837  (CurAS == LangAS::Default ? LangAS::opencl_generic : CurAS);
4838  EPI.TypeQuals.addAddressSpace(AS);
4839  }
4840  T = Context.getFunctionType(T, ParamTys, EPI);
4841  }
4842  break;
4843  }
4845  // The scope spec must refer to a class, or be dependent.
4846  CXXScopeSpec &SS = DeclType.Mem.Scope();
4847  QualType ClsType;
4848 
4849  // Handle pointer nullability.
4850  inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
4851  DeclType.EndLoc, DeclType.getAttrs());
4852 
4853  if (SS.isInvalid()) {
4854  // Avoid emitting extra errors if we already errored on the scope.
4855  D.setInvalidType(true);
4856  } else if (S.isDependentScopeSpecifier(SS) ||
4857  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4858  NestedNameSpecifier *NNS = SS.getScopeRep();
4859  NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4860  switch (NNS->getKind()) {
4862  ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4863  NNS->getAsIdentifier());
4864  break;
4865 
4870  llvm_unreachable("Nested-name-specifier must name a type");
4871 
4874  ClsType = QualType(NNS->getAsType(), 0);
4875  // Note: if the NNS has a prefix and ClsType is a nondependent
4876  // TemplateSpecializationType, then the NNS prefix is NOT included
4877  // in ClsType; hence we wrap ClsType into an ElaboratedType.
4878  // NOTE: in particular, no wrap occurs if ClsType already is an
4879  // Elaborated, DependentName, or DependentTemplateSpecialization.
4880  if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4881  ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4882  break;
4883  }
4884  } else {
4885  S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4886  diag::err_illegal_decl_mempointer_in_nonclass)
4887  << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4888  << DeclType.Mem.Scope().getRange();
4889  D.setInvalidType(true);
4890  }
4891 
4892  if (!ClsType.isNull())
4893  T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4894  D.getIdentifier());
4895  if (T.isNull()) {
4896  T = Context.IntTy;
4897  D.setInvalidType(true);
4898  } else if (DeclType.Mem.TypeQuals) {
4899  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4900  }
4901  break;
4902  }
4903 
4904  case DeclaratorChunk::Pipe: {
4905  T = S.BuildReadPipeType(T, DeclType.Loc);
4906  processTypeAttrs(state, T, TAL_DeclSpec,
4908  break;
4909  }
4910  }
4911 
4912  if (T.isNull()) {
4913  D.setInvalidType(true);
4914  T = Context.IntTy;
4915  }
4916 
4917  // See if there are any attributes on this declarator chunk.
4918  processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
4919 
4920  if (DeclType.Kind != DeclaratorChunk::Paren) {
4921  if (ExpectNoDerefChunk) {
4922  if (!IsNoDerefableChunk(DeclType))
4923  S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
4924  ExpectNoDerefChunk = false;
4925  }
4926 
4927  ExpectNoDerefChunk = state.didParseNoDeref();
4928  }
4929  }
4930 
4931  if (ExpectNoDerefChunk)
4932  S.Diag(state.getDeclarator().getBeginLoc(),
4933  diag::warn_noderef_on_non_pointer_or_array);
4934 
4935  // GNU warning -Wstrict-prototypes
4936  // Warn if a function declaration is without a prototype.
4937  // This warning is issued for all kinds of unprototyped function
4938  // declarations (i.e. function type typedef, function pointer etc.)
4939  // C99 6.7.5.3p14:
4940  // The empty list in a function declarator that is not part of a definition
4941  // of that function specifies that no information about the number or types
4942  // of the parameters is supplied.
4943  if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) {
4944  bool IsBlock = false;
4945  for (const DeclaratorChunk &DeclType : D.type_objects()) {
4946  switch (DeclType.Kind) {
4948  IsBlock = true;
4949  break;
4951  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4952  if (FTI.NumParams == 0 && !FTI.isVariadic)
4953  S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
4954  << IsBlock
4955  << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
4956  IsBlock = false;
4957  break;
4958  }
4959  default:
4960  break;
4961  }
4962  }
4963  }
4964 
4965  assert(!T.isNull() && "T must not be null after this point");
4966 
4967  if (LangOpts.CPlusPlus && T->isFunctionType()) {
4968  const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4969  assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4970 
4971  // C++ 8.3.5p4:
4972  // A cv-qualifier-seq shall only be part of the function type
4973  // for a nonstatic member function, the function type to which a pointer
4974  // to member refers, or the top-level function type of a function typedef
4975  // declaration.
4976  //
4977  // Core issue 547 also allows cv-qualifiers on function types that are
4978  // top-level template type arguments.
4979  enum { NonMember, Member, DeductionGuide } Kind = NonMember;
4981  Kind = DeductionGuide;
4982  else if (!D.getCXXScopeSpec().isSet()) {
4986  Kind = Member;
4987  } else {
4989  if (!DC || DC->isRecord())
4990  Kind = Member;
4991  }
4992 
4993  // C++11 [dcl.fct]p6 (w/DR1417):
4994  // An attempt to specify a function type with a cv-qualifier-seq or a
4995  // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4996  // - the function type for a non-static member function,
4997  // - the function type to which a pointer to member refers,
4998  // - the top-level function type of a function typedef declaration or
4999  // alias-declaration,
5000  // - the type-id in the default argument of a type-parameter, or
5001  // - the type-id of a template-argument for a type-parameter
5002  //
5003  // FIXME: Checking this here is insufficient. We accept-invalid on:
5004  //
5005  // template<typename T> struct S { void f(T); };
5006  // S<int() const> s;
5007  //
5008  // ... for instance.
5009  if (IsQualifiedFunction &&
5010  !(Kind == Member &&
5012  !IsTypedefName &&
5015  SourceLocation Loc = D.getBeginLoc();
5016  SourceRange RemovalRange;
5017  unsigned I;
5018  if (D.isFunctionDeclarator(I)) {
5019  SmallVector<SourceLocation, 4> RemovalLocs;
5020  const DeclaratorChunk &Chunk = D.getTypeObject(I);
5021  assert(Chunk.Kind == DeclaratorChunk::Function);
5022 
5023  if (Chunk.Fun.hasRefQualifier())
5024  RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5025 
5026  if (Chunk.Fun.hasMethodTypeQualifiers())
5028  [&](DeclSpec::TQ TypeQual, StringRef QualName,
5029  SourceLocation SL) { RemovalLocs.push_back(SL); });
5030 
5031  if (!RemovalLocs.empty()) {
5032  llvm::sort(RemovalLocs,
5034  RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5035  Loc = RemovalLocs.front();
5036  }
5037  }
5038 
5039  S.Diag(Loc, diag::err_invalid_qualified_function_type)
5040  << Kind << D.isFunctionDeclarator() << T
5042  << FixItHint::CreateRemoval(RemovalRange);
5043 
5044  // Strip the cv-qualifiers and ref-qualifiers from the type.
5047  EPI.RefQualifier = RQ_None;
5048 
5049  T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5050  EPI);
5051  // Rebuild any parens around the identifier in the function type.
5052  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5054  break;
5055  T = S.BuildParenType(T);
5056  }
5057  }
5058  }
5059 
5060  // Apply any undistributed attributes from the declarator.
5062 
5063  // Diagnose any ignored type attributes.
5064  state.diagnoseIgnoredTypeAttrs(T);
5065 
5066  // C++0x [dcl.constexpr]p9:
5067  // A constexpr specifier used in an object declaration declares the object
5068  // as const.
5069  if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
5070  T.addConst();
5071  }
5072 
5073  // If there was an ellipsis in the declarator, the declaration declares a
5074  // parameter pack whose type may be a pack expansion type.
5075  if (D.hasEllipsis()) {
5076  // C++0x [dcl.fct]p13:
5077  // A declarator-id or abstract-declarator containing an ellipsis shall
5078  // only be used in a parameter-declaration. Such a parameter-declaration
5079  // is a parameter pack (14.5.3). [...]
5080  switch (D.getContext()) {
5083  // C++0x [dcl.fct]p13:
5084  // [...] When it is part of a parameter-declaration-clause, the
5085  // parameter pack is a function parameter pack (14.5.3). The type T
5086  // of the declarator-id of the function parameter pack shall contain
5087  // a template parameter pack; each template parameter pack in T is
5088  // expanded by the function parameter pack.
5089  //
5090  // We represent function parameter packs as function parameters whose
5091  // type is a pack expansion.
5092  if (!T->containsUnexpandedParameterPack()) {
5093  S.Diag(D.getEllipsisLoc(),
5094  diag::err_function_parameter_pack_without_parameter_packs)
5095  << T << D.getSourceRange();
5097  } else {
5098  T = Context.getPackExpansionType(T, None);
5099  }
5100  break;
5102  // C++0x [temp.param]p15:
5103  // If a template-parameter is a [...] is a parameter-declaration that
5104  // declares a parameter pack (8.3.5), then the template-parameter is a
5105  // template parameter pack (14.5.3).
5106  //
5107  // Note: core issue 778 clarifies that, if there are any unexpanded
5108  // parameter packs in the type of the non-type template parameter, then
5109  // it expands those parameter packs.
5111  T = Context.getPackExpansionType(T, None);
5112  else
5113  S.Diag(D.getEllipsisLoc(),
5114  LangOpts.CPlusPlus11
5115  ? diag::warn_cxx98_compat_variadic_templates
5116  : diag::ext_variadic_templates);
5117  break;
5118 
5121  case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic
5122  // here?
5123  case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic
5124  // here?
5144  // FIXME: We may want to allow parameter packs in block-literal contexts
5145  // in the future.
5146  S.Diag(D.getEllipsisLoc(),
5147  diag::err_ellipsis_in_declarator_not_parameter);
5149  break;
5150  }
5151  }
5152 
5153  assert(!T.isNull() && "T must not be null at the end of this function");
5154  if (D.isInvalidType())
5155  return Context.getTrivialTypeSourceInfo(T);
5156 
5157  return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5158 }
5159 
5160 /// GetTypeForDeclarator - Convert the type for the specified
5161 /// declarator to Type instances.
5162 ///
5163 /// The result of this call will never be null, but the associated
5164 /// type may be a null type if there's an unrecoverable error.
5166  // Determine the type of the declarator. Not all forms of declarator
5167  // have a type.
5168 
5169  TypeProcessingState state(*this, D);
5170 
5171  TypeSourceInfo *ReturnTypeInfo = nullptr;
5172  QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5173  if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5174  inferARCWriteback(state, T);
5175 
5176  return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5177 }
5178 
5180  QualType &declSpecTy,
5181  Qualifiers::ObjCLifetime ownership) {
5182  if (declSpecTy->isObjCRetainableType() &&
5183  declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5184  Qualifiers qs;
5185  qs.addObjCLifetime(ownership);
5186  declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5187  }
5188 }
5189 
5190 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5191  Qualifiers::ObjCLifetime ownership,
5192  unsigned chunkIndex) {
5193  Sema &S = state.getSema();
5194  Declarator &D = state.getDeclarator();
5195 
5196  // Look for an explicit lifetime attribute.
5197  DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5198  if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5199  return;
5200 
5201  const char *attrStr = nullptr;
5202  switch (ownership) {
5203  case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5204  case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5205  case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5206  case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5207  case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5208  }
5209 
5210  IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5211  Arg->Ident = &S.Context.Idents.get(attrStr);
5212  Arg->Loc = SourceLocation();
5213 
5214  ArgsUnion Args(Arg);
5215 
5216  // If there wasn't one, add one (with an invalid source location
5217  // so that we don't make an AttributedType for it).
5218  ParsedAttr *attr = D.getAttributePool().create(
5219  &S.Context.Idents.get("objc_ownership"), SourceLocation(),
5220  /*scope*/ nullptr, SourceLocation(),
5221  /*args*/ &Args, 1, ParsedAttr::AS_GNU);
5222  chunk.getAttrs().addAtEnd(attr);
5223  // TODO: mark whether we did this inference?
5224 }
5225 
5226 /// Used for transferring ownership in casts resulting in l-values.
5227 static void transferARCOwnership(TypeProcessingState &state,
5228  QualType &declSpecTy,
5229  Qualifiers::ObjCLifetime ownership) {
5230  Sema &S = state.getSema();
5231  Declarator &D = state.getDeclarator();
5232 
5233  int inner = -1;
5234  bool hasIndirection = false;
5235  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5236  DeclaratorChunk &chunk = D.getTypeObject(i);
5237  switch (chunk.Kind) {
5239  // Ignore parens.
5240  break;
5241 
5245  if (inner != -1)
5246  hasIndirection = true;
5247  inner = i;
5248  break;
5249 
5251  if (inner != -1)
5252  transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5253  return;
5254 
5257  case DeclaratorChunk::Pipe:
5258  return;
5259  }
5260  }
5261 
5262  if (inner == -1)
5263  return;
5264 
5265  DeclaratorChunk &chunk = D.getTypeObject(inner);
5266  if (chunk.Kind == DeclaratorChunk::Pointer) {
5267  if (declSpecTy->isObjCRetainableType())
5268  return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5269  if (declSpecTy->isObjCObjectType() && hasIndirection)
5270  return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5271  } else {
5272  assert(chunk.Kind == DeclaratorChunk::Array ||
5273  chunk.Kind == DeclaratorChunk::Reference);
5274  return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5275  }
5276 }
5277 
5279  TypeProcessingState state(*this, D);
5280 
5281  TypeSourceInfo *ReturnTypeInfo = nullptr;
5282  QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5283 
5284  if (getLangOpts().ObjC) {
5285  Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5286  if (ownership != Qualifiers::OCL_None)
5287  transferARCOwnership(state, declSpecTy, ownership);
5288  }
5289 
5290  return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5291 }
5292 
5294  TypeProcessingState &State) {
5295  TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5296 }
5297 
5298 namespace {
5299  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5300  ASTContext &Context;
5301  TypeProcessingState &State;
5302  const DeclSpec &DS;
5303 
5304  public:
5305  TypeSpecLocFiller(ASTContext &Context, TypeProcessingState &State,
5306  const DeclSpec &DS)
5307  : Context(Context), State(State), DS(DS) {}
5308 
5309  void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5310  Visit(TL.getModifiedLoc());
5311  fillAttributedTypeLoc(TL, State);
5312  }
5313  void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5314  Visit(TL.getUnqualifiedLoc());
5315  }
5316  void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5317  TL.setNameLoc(DS.getTypeSpecTypeLoc());
5318  }
5319  void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5320  TL.setNameLoc(DS.getTypeSpecTypeLoc());
5321  // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5322  // addition field. What we have is good enough for dispay of location
5323  // of 'fixit' on interface name.
5324  TL.setNameEndLoc(DS.getEndLoc());
5325  }
5326  void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5327  TypeSourceInfo *RepTInfo = nullptr;
5328  Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5329  TL.copy(RepTInfo->getTypeLoc());
5330  }
5331  void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5332  TypeSourceInfo *RepTInfo = nullptr;
5333  Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5334  TL.copy(RepTInfo->getTypeLoc());
5335  }
5336  void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5337  TypeSourceInfo *TInfo = nullptr;
5338  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5339 
5340  // If we got no declarator info from previous Sema routines,
5341  // just fill with the typespec loc.
5342  if (!TInfo) {
5343  TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5344  return;
5345  }
5346 
5347  TypeLoc OldTL = TInfo->getTypeLoc();
5348  if (TInfo->getType()->getAs<ElaboratedType>()) {
5349  ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5352  TL.copy(NamedTL);
5353  } else {
5355  assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
5356  }
5357 
5358  }
5359  void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5360  assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
5363  }
5364  void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5365  assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
5368  assert(DS.getRepAsType());
5369  TypeSourceInfo *TInfo = nullptr;
5370  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5371  TL.setUnderlyingTInfo(TInfo);
5372  }
5373  void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5374  // FIXME: This holds only because we only have one unary transform.
5376  TL.setKWLoc(DS.getTypeSpecTypeLoc());
5378  assert(DS.getRepAsType());
5379  TypeSourceInfo *TInfo = nullptr;
5380  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5381  TL.setUnderlyingTInfo(TInfo);
5382  }
5383  void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5384  // By default, use the source location of the type specifier.
5386  if (TL.needsExtraLocalData()) {
5387  // Set info for the written builtin specifiers.
5389  // Try to have a meaningful source location.
5390  if (TL.getWrittenSignSpec() != TSS_unspecified)
5394  }
5395  }
5396  void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5397  ElaboratedTypeKeyword Keyword
5399  if (DS.getTypeSpecType() == TST_typename) {
5400  TypeSourceInfo *TInfo = nullptr;
5401  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5402  if (TInfo) {
5403  TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5404  return;
5405  }
5406  }
5407  TL.setElaboratedKeywordLoc(Keyword != ETK_None
5408  ? DS.getTypeSpecTypeLoc()
5409  : SourceLocation());
5410  const CXXScopeSpec& SS = DS.getTypeSpecScope();
5411  TL.setQualifierLoc(SS.getWithLocInContext(Context));
5412  Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5413  }
5414  void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5415  assert(DS.getTypeSpecType() == TST_typename);
5416  TypeSourceInfo *TInfo = nullptr;
5417  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5418  assert(TInfo);
5419  TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
5420  }
5421  void VisitDependentTemplateSpecializationTypeLoc(
5423  assert(DS.getTypeSpecType() == TST_typename);
5424  TypeSourceInfo *TInfo = nullptr;
5425  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5426  assert(TInfo);
5427  TL.copy(
5428  TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
5429  }
5430  void VisitTagTypeLoc(TagTypeLoc TL) {
5432  }
5433  void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5434  // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
5435  // or an _Atomic qualifier.
5436  if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
5437  TL.setKWLoc(DS.getTypeSpecTypeLoc());
5439 
5440  TypeSourceInfo *TInfo = nullptr;
5441  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5442  assert(TInfo);
5443  TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5444  } else {
5445  TL.setKWLoc(DS.getAtomicSpecLoc());
5446  // No parens, to indicate this was spelled as an _Atomic qualifier.
5448  Visit(TL.getValueLoc());
5449  }
5450  }
5451 
5452  void VisitPipeTypeLoc(PipeTypeLoc TL) {
5453  TL.setKWLoc(DS.getTypeSpecTypeLoc());
5454 
5455  TypeSourceInfo *TInfo = nullptr;
5456  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5457  TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5458  }
5459 
5460  void VisitTypeLoc(TypeLoc TL) {
5461  // FIXME: add other typespec types and change this to an assert.
5462  TL.initialize(Context, DS.getTypeSpecTypeLoc());
5463  }
5464  };
5465 
5466  class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
5467  ASTContext &Context;
5468  TypeProcessingState &State;
5469  const DeclaratorChunk &Chunk;
5470 
5471  public:
5472  DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
5473  const DeclaratorChunk &Chunk)
5474  : Context(Context), State(State), Chunk(Chunk) {}
5475 
5476  void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5477  llvm_unreachable("qualified type locs not expected here!");
5478  }
5479  void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5480  llvm_unreachable("decayed type locs not expected here!");
5481  }
5482 
5483  void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5484  fillAttributedTypeLoc(TL, State);
5485  }
5486  void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5487  // nothing
5488  }
5489  void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5490  assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
5491  TL.setCaretLoc(Chunk.Loc);
5492  }
5493  void VisitPointerTypeLoc(PointerTypeLoc TL) {
5494  assert(Chunk.Kind == DeclaratorChunk::Pointer);
5495  TL.setStarLoc(Chunk.Loc);
5496  }
5497  void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5498  assert(Chunk.Kind == DeclaratorChunk::Pointer);
5499  TL.setStarLoc(Chunk.Loc);
5500  }
5501  void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5502  assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
5503  const CXXScopeSpec& SS = Chunk.Mem.Scope();
5504  NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
5505 
5506  const Type* ClsTy = TL.getClass();
5507  QualType ClsQT = QualType(ClsTy, 0);
5508  TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5509  // Now copy source location info into the type loc component.
5510  TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5511  switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5513  assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
5514  {
5517  DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5518  DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5519  }
5520  break;
5521 
5524  if (isa<ElaboratedType>(ClsTy)) {
5525  ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5527  ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5528  TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5529  NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5530  } else {
5531  ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
5532  }
5533  break;
5534 
5539  llvm_unreachable("Nested-name-specifier must name a type");
5540  }
5541 
5542  // Finally fill in MemberPointerLocInfo fields.
5543  TL.setStarLoc(Chunk.Loc);
5544  TL.setClassTInfo(ClsTInfo);
5545  }
5546  void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5547  assert(Chunk.Kind == DeclaratorChunk::Reference);
5548  // 'Amp' is misleading: this might have been originally
5549  /// spelled with AmpAmp.
5550  TL.setAmpLoc(Chunk.Loc);
5551  }
5552  void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5553  assert(Chunk.Kind == DeclaratorChunk::Reference);
5554  assert(!Chunk.Ref.LValueRef);
5555  TL.setAmpAmpLoc(Chunk.Loc);
5556  }
5557  void VisitArrayTypeLoc(ArrayTypeLoc TL) {
5558  assert(Chunk.Kind == DeclaratorChunk::Array);
5559  TL.setLBracketLoc(Chunk.Loc);
5560  TL.setRBracketLoc(Chunk.EndLoc);
5561  TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
5562  }
5563  void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5564  assert(Chunk.Kind == DeclaratorChunk::Function);
5565  TL.setLocalRangeBegin(Chunk.Loc);
5566  TL.setLocalRangeEnd(Chunk.EndLoc);
5567 
5568  const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
5569  TL.setLParenLoc(FTI.getLParenLoc());
5570  TL.setRParenLoc(FTI.getRParenLoc());
5571  for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
5572  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5573  TL.setParam(tpi++, Param);
5574  }
5576  }
5577  void VisitParenTypeLoc(ParenTypeLoc TL) {
5578  assert(Chunk.Kind == DeclaratorChunk::Paren);
5579  TL.setLParenLoc(Chunk.Loc);
5580  TL.setRParenLoc(Chunk.EndLoc);
5581  }
5582  void VisitPipeTypeLoc(PipeTypeLoc TL) {
5583  assert(Chunk.Kind == DeclaratorChunk::Pipe);
5584  TL.setKWLoc(Chunk.Loc);
5585  }
5586 
5587  void VisitTypeLoc(TypeLoc TL) {
5588  llvm_unreachable("unsupported TypeLoc kind in declarator!");
5589  }
5590  };
5591 } // end anonymous namespace
5592 
5593 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5594  SourceLocation Loc;
5595  switch (Chunk.Kind) {
5599  case DeclaratorChunk::Pipe:
5600  llvm_unreachable("cannot be _Atomic qualified");
5601 
5604  break;
5605 
5609  // FIXME: Provide a source location for the _Atomic keyword.
5610  break;
5611  }
5612 
5613  ATL.setKWLoc(Loc);
5614  ATL.setParensRange(SourceRange());
5615 }
5616 
5617 static void
5619  const ParsedAttributesView &Attrs) {
5620  for (const ParsedAttr &AL : Attrs) {
5621  if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
5622  DASTL.setAttrNameLoc(AL.getLoc());
5623  DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
5625  return;
5626  }
5627  }
5628 
5629  llvm_unreachable(
5630  "no address_space attribute found at the expected location!");
5631 }
5632 
5633 /// Create and instantiate a TypeSourceInfo with type source information.
5634 ///
5635 /// \param T QualType referring to the type as written in source code.
5636 ///
5637 /// \param ReturnTypeInfo For declarators whose return type does not show
5638 /// up in the normal place in the declaration specifiers (such as a C++
5639 /// conversion function), this pointer will refer to a type source information
5640 /// for that return type.
5641 static TypeSourceInfo *
5642 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
5643  QualType T, TypeSourceInfo *ReturnTypeInfo) {
5644  Sema &S = State.getSema();
5645  Declarator &D = State.getDeclarator();
5646 
5648  UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
5649 
5650  // Handle parameter packs whose type is a pack expansion.
5651  if (isa<PackExpansionType>(T)) {
5652  CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
5653  CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5654  }
5655 
5656  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5657  // An AtomicTypeLoc might be produced by an atomic qualifier in this
5658  // declarator chunk.
5659  if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
5660  fillAtomicQualLoc(ATL, D.getTypeObject(i));
5661  CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
5662  }
5663 
5664  while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
5665  fillAttributedTypeLoc(TL, State);
5666  CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5667  }
5668 
5669  while (DependentAddressSpaceTypeLoc TL =
5670  CurrTL.getAs<DependentAddressSpaceTypeLoc>()) {
5672  CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
5673  }
5674 
5675  // FIXME: Ordering here?
5676  while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
5677  CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5678 
5679  DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
5680  CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5681  }
5682 
5683  // If we have different source information for the return type, use
5684  // that. This really only applies to C++ conversion functions.
5685  if (ReturnTypeInfo) {
5686  TypeLoc TL = ReturnTypeInfo->getTypeLoc();
5687  assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
5688  memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
5689  } else {
5690  TypeSpecLocFiller(S.Context, State, D.getDeclSpec()).Visit(CurrTL);
5691  }
5692 
5693  return TInfo;
5694 }
5695 
5696 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
5698  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
5699  // and Sema during declaration parsing. Try deallocating/caching them when
5700  // it's appropriate, instead of allocating them and keeping them around.
5701  LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
5702  TypeAlignment);
5703  new (LocT) LocInfoType(T, TInfo);
5704  assert(LocT->getTypeClass() != T->getTypeClass() &&
5705  "LocInfoType's TypeClass conflicts with an existing Type class");
5706  return ParsedType::make(QualType(LocT, 0));
5707 }
5708 
5709 void LocInfoType::getAsStringInternal(std::string &Str,
5710  const PrintingPolicy &Policy) const {
5711  llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
5712  " was used directly instead of getting the QualType through"
5713  " GetTypeFromParser");
5714 }
5715 
5717  // C99 6.7.6: Type names have no identifier. This is already validated by
5718  // the parser.
5719  assert(D.getIdentifier() == nullptr &&
5720  "Type name should have no identifier!");
5721 
5722  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5723  QualType T = TInfo->getType();
5724  if (D.isInvalidType())
5725  return true;
5726 
5727  // Make sure there are no unused decl attributes on the declarator.
5728  // We don't want to do this for ObjC parameters because we're going
5729  // to apply them to the actual parameter declaration.
5730  // Likewise, we don't want to do this for alias declarations, because
5731  // we are actually going to build a declaration from this eventually.
5735  checkUnusedDeclAttributes(D);
5736 
5737  if (getLangOpts().CPlusPlus) {
5738  // Check that there are no default arguments (C++ only).
5739  CheckExtraCXXDefaultArguments(D);
5740  }
5741 
5742  return CreateParsedType(T, TInfo);
5743 }
5744 
5746  QualType T = Context.getObjCInstanceType();
5747  TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
5748  return CreateParsedType(T, TInfo);
5749 }
5750 
5751 //===----------------------------------------------------------------------===//
5752 // Type Attribute Processing
5753 //===----------------------------------------------------------------------===//
5754 
5755 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
5756 /// is uninstantiated. If instantiated it will apply the appropriate address space
5757 /// to the type. This function allows dependent template variables to be used in
5758 /// conjunction with the address_space attribute
5760  SourceLocation AttrLoc) {
5761  if (!AddrSpace->isValueDependent()) {
5762 
5763  llvm::APSInt addrSpace(32);
5764  if (!AddrSpace->isIntegerConstantExpr(addrSpace, Context)) {
5765  Diag(AttrLoc, diag::err_attribute_argument_type)
5766  << "'address_space'" << AANT_ArgumentIntegerConstant
5767  << AddrSpace->getSourceRange();
5768  return QualType();
5769  }
5770 
5771  // Bounds checking.
5772  if (addrSpace.isSigned()) {
5773  if (addrSpace.isNegative()) {
5774  Diag(AttrLoc, diag::err_attribute_address_space_negative)
5775  << AddrSpace->getSourceRange();
5776  return QualType();
5777  }
5778  addrSpace.setIsSigned(false);
5779  }
5780 
5781  llvm::APSInt max(addrSpace.getBitWidth());
5782  max =
5784  if (addrSpace > max) {
5785  Diag(AttrLoc, diag::err_attribute_address_space_too_high)
5786  << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
5787  return QualType();
5788  }
5789 
5790  LangAS ASIdx =
5791  getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
5792 
5793  // If this type is already address space qualified with a different
5794  // address space, reject it.
5795  // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
5796  // by qualifiers for two or more different address spaces."
5797  if (T.getAddressSpace() != LangAS::Default) {
5798  if (T.getAddressSpace() != ASIdx) {
5799  Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
5800  return QualType();
5801  } else
5802  // Emit a warning if they are identical; it's likely unintended.
5803  Diag(AttrLoc,
5804  diag::warn_attribute_address_multiple_identical_qualifiers);
5805  }
5806 
5807  return Context.getAddrSpaceQualType(T, ASIdx);
5808  }
5809 
5810  // A check with similar intentions as checking if a type already has an
5811  // address space except for on a dependent types, basically if the
5812  // current type is already a DependentAddressSpaceType then its already
5813  // lined up to have another address space on it and we can't have
5814  // multiple address spaces on the one pointer indirection
5815  if (T->getAs<DependentAddressSpaceType>()) {
5816  Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
5817  return QualType();
5818  }
5819 
5820  return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
5821 }
5822 
5823 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5824 /// specified type. The attribute contains 1 argument, the id of the address
5825 /// space for the type.
5827  const ParsedAttr &Attr,
5828  TypeProcessingState &State) {
5829  Sema &S = State.getSema();
5830 
5831  // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5832  // qualified by an address-space qualifier."
5833  if (Type->isFunctionType()) {
5834  S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5835  Attr.setInvalid();
5836  return;
5837  }
5838 
5839  LangAS ASIdx;
5840  if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
5841 
5842  // Check the attribute arguments.
5843  if (Attr.getNumArgs() != 1) {
5844  S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
5845  << 1;
5846  Attr.setInvalid();
5847  return;
5848  }
5849 
5850  Expr *ASArgExpr;
5851  if (Attr.isArgIdent(0)) {
5852  // Special case where the argument is a template id.
5853  CXXScopeSpec SS;
5854  SourceLocation TemplateKWLoc;
5855  UnqualifiedId id;
5856  id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
5857 
5858  ExprResult AddrSpace = S.ActOnIdExpression(
5859  S.getCurScope(), SS, TemplateKWLoc, id, false, false);
5860  if (AddrSpace.isInvalid())
5861  return;
5862 
5863  ASArgExpr = static_cast<Expr *>(AddrSpace.get());
5864  } else {
5865  ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5866  }
5867 
5868  // Create the DependentAddressSpaceType or append an address space onto
5869  // the type.
5870  QualType T = S.BuildAddressSpaceAttr(Type, ASArgExpr, Attr.getLoc());
5871 
5872  if (!T.isNull()) {
5873  ASTContext &Ctx = S.Context;
5874  auto *ASAttr = ::new (Ctx) AddressSpaceAttr(
5875  Attr.getRange(), Ctx, Attr.getAttributeSpellingListIndex(),
5876  static_cast<unsigned>(T.getQualifiers().getAddressSpace()));
5877  Type = State.getAttributedType(ASAttr, T, T);
5878  } else {
5879  Attr.setInvalid();
5880  }
5881  } else {
5882  // The keyword-based type attributes imply which address space to use.
5883  switch (Attr.getKind()) {
5884  case ParsedAttr::AT_OpenCLGlobalAddressSpace:
5885  ASIdx = LangAS::opencl_global; break;
5886  case ParsedAttr::AT_OpenCLLocalAddressSpace:
5887  ASIdx = LangAS::opencl_local; break;
5888  case ParsedAttr::AT_OpenCLConstantAddressSpace:
5889  ASIdx = LangAS::opencl_constant; break;
5890  case ParsedAttr::AT_OpenCLGenericAddressSpace:
5891  ASIdx = LangAS::opencl_generic; break;
5892  case ParsedAttr::AT_OpenCLPrivateAddressSpace:
5893  ASIdx = LangAS::opencl_private; break;
5894  default:
5895  llvm_unreachable("Invalid address space");
5896  }
5897 
5898  // If this type is already address space qualified with a different
5899  // address space, reject it.
5900  // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5901  // qualifiers for two or more different address spaces."
5902  if (Type.getAddressSpace() != LangAS::Default) {
5903  if (Type.getAddressSpace() != ASIdx) {
5904  S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5905  Attr.setInvalid();
5906  return;
5907  } else
5908  // Emit a warning if they are identical; it's likely unintended.
5909  S.Diag(Attr.getLoc(),
5910  diag::warn_attribute_address_multiple_identical_qualifiers);
5911  }
5912 
5913  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5914  }
5915 }
5916 
5917 /// Does this type have a "direct" ownership qualifier? That is,
5918 /// is it written like "__strong id", as opposed to something like
5919 /// "typeof(foo)", where that happens to be strong?
5921  // Fast path: no qualifier at all.
5922  assert(type.getQualifiers().hasObjCLifetime());
5923 
5924  while (true) {
5925  // __strong id
5926  if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5927  if (attr->getAttrKind() == attr::ObjCOwnership)
5928  return true;
5929 
5930  type = attr->getModifiedType();
5931 
5932  // X *__strong (...)
5933  } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5934  type = paren->getInnerType();
5935 
5936  // That's it for things we want to complain about. In particular,
5937  // we do not want to look through typedefs, typeof(expr),
5938  // typeof(type), or any other way that the type is somehow
5939  // abstracted.
5940  } else {
5941 
5942  return false;
5943  }
5944  }
5945 }
5946 
5947 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5948 /// attribute on the specified type.
5949 ///
5950 /// Returns 'true' if the attribute was handled.
5951 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5952  ParsedAttr &attr, QualType &type) {
5953  bool NonObjCPointer = false;
5954 
5955  if (!type->isDependentType() && !type->isUndeducedType()) {
5956  if (const PointerType *ptr = type->getAs<PointerType>()) {
5957  QualType pointee = ptr->getPointeeType();
5958  if (pointee->isObjCRetainableType() || pointee->isPointerType())
5959  return false;
5960  // It is important not to lose the source info that there was an attribute
5961  // applied to non-objc pointer. We will create an attributed type but
5962  // its type will be the same as the original type.
5963  NonObjCPointer = true;
5964  } else if (!type->isObjCRetainableType()) {
5965  return false;
5966  }
5967 
5968  // Don't accept an ownership attribute in the declspec if it would
5969  // just be the return type of a block pointer.
5970  if (state.isProcessingDeclSpec()) {
5971  Declarator &D = state.getDeclarator();
5973  /*onlyBlockPointers=*/true))
5974  return false;
5975  }
5976  }
5977 
5978  Sema &S = state.getSema();
5979  SourceLocation AttrLoc = attr.getLoc();
5980  if (AttrLoc.isMacroID())
5981  AttrLoc =
5983 
5984  if (!attr.isArgIdent(0)) {
5985  S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
5987  attr.setInvalid();
5988  return true;
5989  }
5990 
5991  IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5992  Qualifiers::ObjCLifetime lifetime;
5993  if (II->isStr("none"))
5994  lifetime = Qualifiers::OCL_ExplicitNone;
5995  else if (II->isStr("strong"))
5996  lifetime = Qualifiers::OCL_Strong;
5997  else if (II->isStr("weak"))
5998  lifetime = Qualifiers::OCL_Weak;
5999  else if (II->isStr("autoreleasing"))
6000  lifetime = Qualifiers::OCL_Autoreleasing;
6001  else {
6002  S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
6003  << attr.getName() << II;
6004  attr.setInvalid();
6005  return true;
6006  }
6007 
6008  // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6009  // outside of ARC mode.
6010  if (!S.getLangOpts().ObjCAutoRefCount &&
6011  lifetime != Qualifiers::OCL_Weak &&
6012  lifetime != Qualifiers::OCL_ExplicitNone) {
6013  return true;
6014  }
6015 
6016  SplitQualType underlyingType = type.split();
6017 
6018  // Check for redundant/conflicting ownership qualifiers.
6019  if (Qualifiers::ObjCLifetime previousLifetime
6020  = type.getQualifiers().getObjCLifetime()) {
6021  // If it's written directly, that's an error.
6022  if (hasDirectOwnershipQualifier(type)) {
6023  S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6024  << type;
6025  return true;
6026  }
6027 
6028  // Otherwise, if the qualifiers actually conflict, pull sugar off
6029  // and remove the ObjCLifetime qualifiers.
6030  if (previousLifetime != lifetime) {
6031  // It's possible to have multiple local ObjCLifetime qualifiers. We
6032  // can't stop after we reach a type that is directly qualified.
6033  const Type *prevTy = nullptr;
6034  while (!prevTy || prevTy != underlyingType.Ty) {
6035  prevTy = underlyingType.Ty;
6036  underlyingType = underlyingType.getSingleStepDesugaredType();
6037  }
6038  underlyingType.Quals.removeObjCLifetime();
6039  }
6040  }
6041 
6042  underlyingType.Quals.addObjCLifetime(lifetime);
6043 
6044  if (NonObjCPointer) {
6045  StringRef name = attr.getName()->getName();
6046  switch (lifetime) {
6047  case Qualifiers::OCL_None:
6049  break;
6050  case Qualifiers::OCL_Strong: name = "__strong"; break;
6051  case Qualifiers::OCL_Weak: name = "__weak"; break;
6052  case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6053  }
6054  S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6055  << TDS_ObjCObjOrBlock << type;
6056  }
6057 
6058  // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6059  // because having both 'T' and '__unsafe_unretained T' exist in the type
6060  // system causes unfortunate widespread consistency problems. (For example,
6061  // they're not considered compatible types, and we mangle them identicially
6062  // as template arguments.) These problems are all individually fixable,
6063  // but it's easier to just not add the qualifier and instead sniff it out
6064  // in specific places using isObjCInertUnsafeUnretainedType().
6065  //
6066  // Doing this does means we miss some trivial consistency checks that
6067  // would've triggered in ARC, but that's better than trying to solve all
6068  // the coexistence problems with __unsafe_unretained.
6069  if (!S.getLangOpts().ObjCAutoRefCount &&
6070  lifetime == Qualifiers::OCL_ExplicitNone) {
6071  type = state.getAttributedType(
6072  createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
6073  type, type);
6074  return true;
6075  }
6076 
6077  QualType origType = type;
6078  if (!NonObjCPointer)
6079  type = S.Context.getQualifiedType(underlyingType);
6080 
6081  // If we have a valid source location for the attribute, use an
6082  // AttributedType instead.
6083  if (AttrLoc.isValid()) {
6084  type = state.getAttributedType(::new (S.Context) ObjCOwnershipAttr(
6085  attr.getRange(), S.Context, II,
6087  origType, type);
6088  }
6089 
6090  auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6091  unsigned diagnostic, QualType type) {
6096  diagnostic, type, /*ignored*/ 0));
6097  } else {
6098  S.Diag(loc, diagnostic);
6099  }
6100  };
6101 
6102  // Sometimes, __weak isn't allowed.
6103  if (lifetime == Qualifiers::OCL_Weak &&
6104  !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6105 
6106  // Use a specialized diagnostic if the runtime just doesn't support them.
6107  unsigned diagnostic =
6108  (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6109  : diag::err_arc_weak_no_runtime);
6110 
6111  // In any case, delay the diagnostic until we know what we're parsing.
6112  diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6113 
6114  attr.setInvalid();
6115  return true;
6116  }
6117 
6118  // Forbid __weak for class objects marked as
6119  // objc_arc_weak_reference_unavailable
6120  if (lifetime == Qualifiers::OCL_Weak) {
6121  if (const ObjCObjectPointerType *ObjT =
6122  type->getAs<ObjCObjectPointerType>()) {
6123  if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6124  if (Class->isArcWeakrefUnavailable()) {
6125  S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6126  S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6127  diag::note_class_declared);
6128  }
6129  }
6130  }
6131  }
6132 
6133  return true;
6134 }
6135 
6136 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6137 /// attribute on the specified type. Returns true to indicate that
6138 /// the attribute was handled, false to indicate that the type does
6139 /// not permit the attribute.
6140 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6141  QualType &type) {
6142  Sema &S = state.getSema();
6143 
6144  // Delay if this isn't some kind of pointer.
6145  if (!type->isPointerType() &&
6146  !type->isObjCObjectPointerType() &&
6147  !type->isBlockPointerType())
6148  return false;
6149 
6150  if (type.getObjCGCAttr() != Qualifiers::GCNone) {
6151  S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
6152  attr.setInvalid();
6153  return true;
6154  }
6155 
6156  // Check the attribute arguments.
6157  if (!attr.isArgIdent(0)) {
6158  S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
6159  << attr << AANT_ArgumentString;
6160  attr.setInvalid();
6161  return true;
6162  }
6163  Qualifiers::GC GCAttr;
6164  if (attr.getNumArgs() > 1) {
6165  S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
6166  << 1;
6167  attr.setInvalid();
6168  return true;
6169  }
6170 
6171  IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6172  if (II->isStr("weak"))
6173  GCAttr = Qualifiers::Weak;
6174  else if (II->isStr("strong"))
6175  GCAttr = Qualifiers::Strong;
6176  else {
6177  S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
6178  << attr.getName() << II;
6179  attr.setInvalid();
6180  return true;
6181  }
6182 
6183  QualType origType = type;
6184  type = S.Context.getObjCGCQualType(origType, GCAttr);
6185 
6186  // Make an attributed type to preserve the source information.
6187  if (attr.getLoc().isValid())
6188  type = state.getAttributedType(
6189  ::new (S.Context) ObjCGCAttr(attr.getRange(), S.Context, II,
6191  origType, type);
6192 
6193  return true;
6194 }
6195 
6196 namespace {
6197  /// A helper class to unwrap a type down to a function for the
6198  /// purposes of applying attributes there.
6199  ///
6200  /// Use:
6201  /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
6202  /// if (unwrapped.isFunctionType()) {
6203  /// const FunctionType *fn = unwrapped.get();
6204  /// // change fn somehow
6205  /// T = unwrapped.wrap(fn);
6206  /// }
6207  struct FunctionTypeUnwrapper {
6208  enum WrapKind {
6209  Desugar,
6210  Attributed,
6211  Parens,
6212  Pointer,
6213  BlockPointer,
6214  Reference,
6215  MemberPointer
6216  };
6217 
6218  QualType Original;
6219  const FunctionType *Fn;
6220  SmallVector<unsigned char /*WrapKind*/, 8> Stack;
6221 
6222  FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
6223  while (true) {
6224  const Type *Ty = T.getTypePtr();
6225  if (isa<FunctionType>(Ty)) {
6226  Fn = cast<FunctionType>(Ty);
6227  return;
6228  } else if (isa<ParenType>(Ty)) {
6229  T = cast<ParenType>(Ty)->getInnerType();
6230  Stack.push_back(Parens);
6231  } else if (isa<PointerType>(Ty)) {
6232  T = cast<PointerType>(Ty)->getPointeeType();
6233  Stack.push_back(Pointer);
6234  } else if (isa<BlockPointerType>(Ty)) {
6235  T = cast<BlockPointerType>(Ty)->getPointeeType();
6236  Stack.push_back(BlockPointer);
6237  } else if (isa<MemberPointerType>(Ty)) {
6238  T = cast<MemberPointerType>(Ty)->getPointeeType();
6239  Stack.push_back(MemberPointer);
6240  } else if (isa<ReferenceType>(Ty)) {
6241  T = cast<ReferenceType>(Ty)->getPointeeType();
6242  Stack.push_back(Reference);
6243  } else if (isa<AttributedType>(Ty)) {
6244  T = cast<AttributedType>(Ty)->getEquivalentType();
6245  Stack.push_back(Attributed);
6246  } else {
6247  const Type *DTy = Ty->getUnqualifiedDesugaredType();
6248  if (Ty == DTy) {
6249  Fn = nullptr;
6250  return;
6251  }
6252 
6253  T = QualType(DTy, 0);
6254  Stack.push_back(Desugar);
6255  }
6256  }
6257  }
6258 
6259  bool isFunctionType() const { return (Fn != nullptr); }
6260  const FunctionType *get() const { return Fn; }
6261 
6262  QualType wrap(Sema &S, const FunctionType *New) {
6263  // If T wasn't modified from the unwrapped type, do nothing.
6264  if (New == get()) return Original;
6265 
6266  Fn = New;
6267  return wrap(S.Context, Original, 0);
6268  }
6269 
6270  private:
6271  QualType wrap(ASTContext &C, QualType Old, unsigned I) {
6272  if (I == Stack.size())
6273  return C.getQualifiedType(Fn, Old.getQualifiers());
6274 
6275  // Build up the inner type, applying the qualifiers from the old
6276  // type to the new type.
6277  SplitQualType SplitOld = Old.split();
6278 
6279  // As a special case, tail-recurse if there are no qualifiers.
6280  if (SplitOld.Quals.empty())
6281  return wrap(C, SplitOld.Ty, I);
6282  return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
6283  }
6284 
6285  QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
6286  if (I == Stack.size()) return QualType(Fn, 0);
6287 
6288  switch (static_cast<WrapKind>(Stack[I++])) {
6289  case Desugar:
6290  // This is the point at which we potentially lose source
6291  // information.
6292  return wrap(C, Old->getUnqualifiedDesugaredType(), I);
6293 
6294  case Attributed:
6295  return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
6296 
6297  case Parens: {
6298  QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
6299  return C.getParenType(New);
6300  }
6301 
6302  case Pointer: {
6303  QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
6304  return C.getPointerType(New);
6305  }
6306 
6307  case BlockPointer: {
6308  QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
6309  return C.getBlockPointerType(New);
6310  }
6311 
6312  case MemberPointer: {
6313  const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
6314  QualType New = wrap(C, OldMPT->getPointeeType(), I);
6315  return C.getMemberPointerType(New, OldMPT->getClass());
6316  }
6317 
6318  case Reference: {
6319  const ReferenceType *OldRef = cast<ReferenceType>(Old);
6320  QualType New = wrap(C, OldRef->getPointeeType(), I);
6321  if (isa<LValueReferenceType>(OldRef))
6322  return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
6323  else
6324  return C.getRValueReferenceType(New);
6325  }
6326  }
6327 
6328  llvm_unreachable("unknown wrapping kind");
6329  }
6330  };
6331 } // end anonymous namespace
6332 
6333 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
6334  ParsedAttr &PAttr, QualType &Type) {
6335  Sema &S = State.getSema();
6336 
6337  Attr *A;
6338  switch (PAttr.getKind()) {
6339  default: llvm_unreachable("Unknown attribute kind");
6340  case ParsedAttr::AT_Ptr32:
6341  A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
6342  break;
6343  case ParsedAttr::AT_Ptr64:
6344  A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
6345  break;
6346  case ParsedAttr::AT_SPtr:
6347  A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
6348  break;
6349  case ParsedAttr::AT_UPtr:
6350  A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
6351  break;
6352  }
6353 
6354  attr::Kind NewAttrKind = A->getKind();
6355  QualType Desugared = Type;
6356  const AttributedType *AT = dyn_cast<AttributedType>(Type);
6357  while (AT) {
6358  attr::Kind CurAttrKind = AT->getAttrKind();
6359 
6360  // You cannot specify duplicate type attributes, so if the attribute has
6361  // already been applied, flag it.
6362  if (NewAttrKind == CurAttrKind) {
6363  S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact)
6364  << PAttr.getName();
6365  return true;
6366  }
6367 
6368  // You cannot have both __sptr and __uptr on the same type, nor can you
6369  // have __ptr32 and __ptr64.
6370  if ((CurAttrKind == attr::Ptr32 && NewAttrKind == attr::Ptr64) ||
6371  (CurAttrKind == attr::Ptr64 && NewAttrKind == attr::Ptr32)) {
6372  S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
6373  << "'__ptr32'" << "'__ptr64'";
6374  return true;
6375  } else if ((CurAttrKind == attr::SPtr && NewAttrKind == attr::UPtr) ||
6376  (CurAttrKind == attr::UPtr && NewAttrKind == attr::SPtr)) {
6377  S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
6378  << "'__sptr'" << "'__uptr'";
6379  return true;
6380  }
6381 
6382  Desugared = AT->getEquivalentType();
6383  AT = dyn_cast<AttributedType>(Desugared);
6384  }
6385 
6386  // Pointer type qualifiers can only operate on pointer types, but not
6387  // pointer-to-member types.
6388  //
6389  // FIXME: Should we really be disallowing this attribute if there is any
6390  // type sugar between it and the pointer (other than attributes)? Eg, this
6391  // disallows the attribute on a parenthesized pointer.
6392  // And if so, should we really allow *any* type attribute?
6393  if (!isa<PointerType>(Desugared)) {
6394  if (Type->isMemberPointerType())
6395  S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
6396  else
6397  S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
6398  return true;
6399  }
6400 
6401  Type = State.getAttributedType(A, Type, Type);
6402  return false;
6403 }
6404 
6405 /// Map a nullability attribute kind to a nullability kind.
6407  switch (kind) {
6408  case ParsedAttr::AT_TypeNonNull:
6409  return NullabilityKind::NonNull;
6410 
6411  case ParsedAttr::AT_TypeNullable:
6413 
6414  case ParsedAttr::AT_TypeNullUnspecified:
6416 
6417  default:
6418  llvm_unreachable("not a nullability attribute kind");
6419  }
6420 }
6421 
6422 /// Applies a nullability type specifier to the given type, if possible.
6423 ///
6424 /// \param state The type processing state.
6425 ///
6426 /// \param type The type to which the nullability specifier will be
6427 /// added. On success, this type will be updated appropriately.
6428 ///
6429 /// \param attr The attribute as written on the type.
6430 ///
6431 /// \param allowOnArrayType Whether to accept nullability specifiers on an
6432 /// array type (e.g., because it will decay to a pointer).
6433 ///
6434 /// \returns true if a problem has been diagnosed, false on success.
6435 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
6436  QualType &type,
6437  ParsedAttr &attr,
6438  bool allowOnArrayType) {
6439  Sema &S = state.getSema();
6440 
6441  NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
6442  SourceLocation nullabilityLoc = attr.getLoc();
6443  bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
6444 
6445  recordNullabilitySeen(S, nullabilityLoc);
6446 
6447  // Check for existing nullability attributes on the type.
6448  QualType desugared = type;
6449  while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
6450  // Check whether there is already a null
6451  if (auto existingNullability = attributed->getImmediateNullability()) {
6452  // Duplicated nullability.
6453  if (nullability == *existingNullability) {
6454  S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
6455  << DiagNullabilityKind(nullability, isContextSensitive)
6456  << FixItHint::CreateRemoval(nullabilityLoc);
6457 
6458  break;
6459  }
6460 
6461  // Conflicting nullability.
6462  S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
6463  << DiagNullabilityKind(nullability, isContextSensitive)
6464  << DiagNullabilityKind(*existingNullability, false);
6465  return true;
6466  }
6467 
6468  desugared = attributed->getModifiedType();
6469  }
6470 
6471  // If there is already a different nullability specifier, complain.
6472  // This (unlike the code above) looks through typedefs that might
6473  // have nullability specifiers on them, which means we cannot
6474  // provide a useful Fix-It.
6475  if (auto existingNullability = desugared->getNullability(S.Context)) {
6476  if (nullability != *existingNullability) {
6477  S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
6478  << DiagNullabilityKind(nullability, isContextSensitive)
6479  << DiagNullabilityKind(*existingNullability, false);
6480 
6481  // Try to find the typedef with the existing nullability specifier.
6482  if (auto typedefType = desugared->getAs<TypedefType>()) {
6483  TypedefNameDecl *typedefDecl = typedefType->getDecl();
6484  QualType underlyingType = typedefDecl->getUnderlyingType();
6485  if (auto typedefNullability
6486  = AttributedType::stripOuterNullability(underlyingType)) {
6487  if (*typedefNullability == *existingNullability) {
6488  S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
6489  << DiagNullabilityKind(*existingNullability, false);
6490  }
6491  }
6492  }
6493 
6494  return true;
6495  }
6496  }
6497 
6498  // If this definitely isn't a pointer type, reject the specifier.
6499  if (!desugared->canHaveNullability() &&
6500  !(allowOnArrayType && desugared->isArrayType())) {
6501  S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
6502  << DiagNullabilityKind(nullability, isContextSensitive) << type;
6503  return true;
6504  }
6505 
6506  // For the context-sensitive keywords/Objective-C property
6507  // attributes, require that the type be a single-level pointer.
6508  if (isContextSensitive) {
6509  // Make sure that the pointee isn't itself a pointer type.
6510  const Type *pointeeType;
6511  if (desugared->isArrayType())
6512  pointeeType = desugared->getArrayElementTypeNoTypeQual();
6513  else
6514  pointeeType = desugared->getPointeeType().getTypePtr();
6515 
6516  if (pointeeType->isAnyPointerType() ||
6517  pointeeType->isObjCObjectPointerType() ||
6518  pointeeType->isMemberPointerType()) {
6519  S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
6520  << DiagNullabilityKind(nullability, true)
6521  << type;
6522  S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
6523  << DiagNullabilityKind(nullability, false)
6524  << type
6525  << FixItHint::CreateReplacement(nullabilityLoc,
6526  getNullabilitySpelling(nullability));
6527  return true;
6528  }
6529  }
6530 
6531  // Form the attributed type.
6532  type = state.getAttributedType(
6533  createNullabilityAttr(S.Context, attr, nullability), type, type);
6534  return false;
6535 }
6536 
6537 /// Check the application of the Objective-C '__kindof' qualifier to
6538 /// the given type.
6539 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
6540  ParsedAttr &attr) {
6541  Sema &S = state.getSema();
6542 
6543  if (isa<ObjCTypeParamType>(type)) {
6544  // Build the attributed type to record where __kindof occurred.
6545  type = state.getAttributedType(
6546  createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
6547  return false;
6548  }
6549 
6550  // Find out if it's an Objective-C object or object pointer type;
6551  const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
6552  const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
6553  : type->getAs<ObjCObjectType>();
6554 
6555  // If not, we can't apply __kindof.
6556  if (!objType) {
6557  // FIXME: Handle dependent types that aren't yet object types.
6558  S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
6559  << type;
6560  return true;
6561  }
6562 
6563  // Rebuild the "equivalent" type, which pushes __kindof down into
6564  // the object type.
6565  // There is no need to apply kindof on an unqualified id type.
6566  QualType equivType = S.Context.getObjCObjectType(
6567  objType->getBaseType(), objType->getTypeArgsAsWritten(),
6568  objType->getProtocols(),
6569  /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
6570 
6571  // If we started with an object pointer type, rebuild it.
6572  if (ptrType) {
6573  equivType = S.Context.getObjCObjectPointerType(equivType);
6574  if (auto nullability = type->getNullability(S.Context)) {
6575  // We create a nullability attribute from the __kindof attribute.
6576  // Make sure that will make sense.
6577  assert(attr.getAttributeSpellingListIndex() == 0 &&
6578  "multiple spellings for __kindof?");
6579  Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
6580  A->setImplicit(true);
6581  equivType = state.getAttributedType(A, equivType, equivType);
6582  }
6583  }
6584 
6585  // Build the attributed type to record where __kindof occurred.
6586  type = state.getAttributedType(
6587  createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
6588  return false;
6589 }
6590 
6591 /// Distribute a nullability type attribute that cannot be applied to
6592 /// the type specifier to a pointer, block pointer, or member pointer
6593 /// declarator, complaining if necessary.
6594 ///
6595 /// \returns true if the nullability annotation was distributed, false
6596 /// otherwise.
6597 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
6598  QualType type, ParsedAttr &attr) {
6599  Declarator &declarator = state.getDeclarator();
6600 
6601  /// Attempt to move the attribute to the specified chunk.
6602  auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
6603  // If there is already a nullability attribute there, don't add
6604  // one.
6605  if (hasNullabilityAttr(chunk.getAttrs()))
6606  return false;
6607 
6608  // Complain about the nullability qualifier being in the wrong
6609  // place.
6610  enum {
6611  PK_Pointer,
6612  PK_BlockPointer,
6613  PK_MemberPointer,
6614  PK_FunctionPointer,
6615  PK_MemberFunctionPointer,
6616  } pointerKind
6617  = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
6618  : PK_Pointer)
6619  : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
6620  : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
6621 
6622  auto diag = state.getSema().Diag(attr.getLoc(),
6623  diag::warn_nullability_declspec)
6626  << type
6627  << static_cast<unsigned>(pointerKind);
6628 
6629  // FIXME: MemberPointer chunks don't carry the location of the *.
6630  if (chunk.Kind != DeclaratorChunk::MemberPointer) {
6631  diag << FixItHint::CreateRemoval(attr.getLoc())
6633  state.getSema().getPreprocessor()
6634  .getLocForEndOfToken(chunk.Loc),
6635  " " + attr.getName()->getName().str() + " ");
6636  }
6637 
6638  moveAttrFromListToList(attr, state.getCurrentAttributes(),
6639  chunk.getAttrs());
6640  return true;
6641  };
6642 
6643  // Move it to the outermost pointer, member pointer, or block
6644  // pointer declarator.
6645  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
6646  DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6647  switch (chunk.Kind) {
6651  return moveToChunk(chunk, false);
6652 
6655  continue;
6656 
6658  // Try to move past the return type to a function/block/member
6659  // function pointer.
6661  declarator, i,
6662  /*onlyBlockPointers=*/false)) {
6663  return moveToChunk(*dest, true);
6664  }
6665 
6666  return false;
6667 
6668  // Don't walk through these.
6670  case DeclaratorChunk::Pipe:
6671  return false;
6672  }
6673  }
6674 
6675  return false;
6676 }
6677 
6679  assert(!Attr.isInvalid());
6680  switch (Attr.getKind()) {
6681  default:
6682  llvm_unreachable("not a calling convention attribute");
6683  case ParsedAttr::AT_CDecl:
6684  return createSimpleAttr<CDeclAttr>(Ctx, Attr);
6685  case ParsedAttr::AT_FastCall:
6686  return createSimpleAttr<FastCallAttr>(Ctx, Attr);
6687  case ParsedAttr::AT_StdCall:
6688  return createSimpleAttr<StdCallAttr>(Ctx, Attr);
6689  case ParsedAttr::AT_ThisCall:
6690  return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
6691  case ParsedAttr::AT_RegCall:
6692  return createSimpleAttr<RegCallAttr>(Ctx, Attr);
6693  case ParsedAttr::AT_Pascal:
6694  return createSimpleAttr<PascalAttr>(Ctx, Attr);
6695  case ParsedAttr::AT_SwiftCall:
6696  return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
6697  case ParsedAttr::AT_VectorCall:
6698  return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
6699  case ParsedAttr::AT_AArch64VectorPcs:
6700  return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
6701  case ParsedAttr::AT_Pcs: {
6702  // The attribute may have had a fixit applied where we treated an
6703  // identifier as a string literal. The contents of the string are valid,
6704  // but the form may not be.
6705  StringRef Str;
6706  if (Attr.isArgExpr(0))
6707  Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6708  else
6709  Str = Attr.getArgAsIdent(0)->Ident->getName();
6710  PcsAttr::PCSType Type;
6711  if (!PcsAttr::ConvertStrToPCSType(Str, Type))
6712  llvm_unreachable("already validated the attribute");
6713  return ::new (Ctx) PcsAttr(Attr.getRange(), Ctx, Type,
6715  }
6716  case ParsedAttr::AT_IntelOclBicc:
6717  return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
6718  case ParsedAttr::AT_MSABI:
6719  return createSimpleAttr<MSABIAttr>(Ctx, Attr);
6720  case ParsedAttr::AT_SysVABI:
6721  return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
6722  case ParsedAttr::AT_PreserveMost:
6723  return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
6724  case ParsedAttr::AT_PreserveAll:
6725  return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
6726  }
6727  llvm_unreachable("unexpected attribute kind!");
6728 }
6729 
6730 /// Process an individual function attribute. Returns true to
6731 /// indicate that the attribute was handled, false if it wasn't.
6732 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6733  QualType &type) {
6734  Sema &S = state.getSema();
6735 
6736  FunctionTypeUnwrapper unwrapped(S, type);
6737 
6738  if (attr.getKind() == ParsedAttr::AT_NoReturn) {
6739  if (S.CheckAttrNoArgs(attr))
6740  return true;
6741 
6742  // Delay if this is not a function type.
6743  if (!unwrapped.isFunctionType())
6744  return false;
6745 
6746  // Otherwise we can process right away.
6747  FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6748  type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6749  return true;
6750  }
6751 
6752  // ns_returns_retained is not always a type attribute, but if we got
6753  // here, we're treating it as one right now.
6754  if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
6755  if (attr.getNumArgs()) return true;
6756 
6757  // Delay if this is not a function type.
6758  if (!unwrapped.isFunctionType())
6759  return false;
6760 
6761  // Check whether the return type is reasonable.
6763  unwrapped.get()->getReturnType()))
6764  return true;
6765 
6766  // Only actually change the underlying type in ARC builds.
6767  QualType origType = type;
6768  if (state.getSema().getLangOpts().ObjCAutoRefCount) {
6770  = unwrapped.get()->getExtInfo().withProducesResult(true);
6771  type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6772  }
6773  type = state.getAttributedType(
6774  createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
6775  origType, type);
6776  return true;
6777  }
6778 
6779  if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
6780  if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
6781  return true;
6782 
6783  // Delay if this is not a function type.
6784  if (!unwrapped.isFunctionType())
6785  return false;
6786 
6788  unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
6789  type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6790  return true;
6791  }
6792 
6793  if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
6794  if (!S.getLangOpts().CFProtectionBranch) {
6795  S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
6796  attr.setInvalid();
6797  return true;
6798  }
6799 
6800  if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
6801  return true;
6802 
6803  // If this is not a function type, warning will be asserted by subject
6804  // check.
6805  if (!unwrapped.isFunctionType())
6806  return true;
6807 
6809  unwrapped.get()->getExtInfo().withNoCfCheck(true);
6810  type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6811  return true;
6812  }
6813 
6814  if (attr.getKind() == ParsedAttr::AT_Regparm) {
6815  unsigned value;
6816  if (S.CheckRegparmAttr(attr, value))
6817  return true;
6818 
6819  // Delay if this is not a function type.
6820  if (!unwrapped.isFunctionType())
6821  return false;
6822 
6823  // Diagnose regparm with fastcall.
6824  const FunctionType *fn = unwrapped.get();
6825  CallingConv CC = fn->getCallConv();
6826  if (CC == CC_X86FastCall) {
6827  S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6829  << "regparm";
6830  attr.setInvalid();
6831  return true;
6832  }
6833 
6835  unwrapped.get()->getExtInfo().withRegParm(value);
6836  type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6837  return true;
6838  }
6839 
6840  // Delay if the type didn't work out to a function.
6841  if (!unwrapped.isFunctionType()) return false;
6842 
6843  // Otherwise, a calling convention.
6844  CallingConv CC;
6845  if (S.CheckCallingConvAttr(attr, CC))
6846  return true;
6847 
6848  const FunctionType *fn = unwrapped.get();
6849  CallingConv CCOld = fn->getCallConv();
6850  Attr *CCAttr = getCCTypeAttr(S.Context, attr);
6851 
6852  if (CCOld != CC) {
6853  // Error out on when there's already an attribute on the type
6854  // and the CCs don't match.
6855  if (S.getCallingConvAttributedType(type)) {
6856  S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6859  attr.setInvalid();
6860  return true;
6861  }
6862  }
6863 
6864  // Diagnose use of variadic functions with calling conventions that
6865  // don't support them (e.g. because they're callee-cleanup).
6866  // We delay warning about this on unprototyped function declarations
6867  // until after redeclaration checking, just in case we pick up a
6868  // prototype that way. And apparently we also "delay" warning about
6869  // unprototyped function types in general, despite not necessarily having
6870  // much ability to diagnose it later.
6871  if (!supportsVariadicCall(CC)) {
6872  const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6873  if (FnP && FnP->isVariadic()) {
6874  unsigned DiagID = diag::err_cconv_varargs;
6875 
6876  // stdcall and fastcall are ignored with a warning for GCC and MS
6877  // compatibility.
6878  bool IsInvalid = true;
6879  if (CC == CC_X86StdCall || CC == CC_X86FastCall) {
6880  DiagID = diag::warn_cconv_varargs;
6881  IsInvalid = false;
6882  }
6883 
6884  S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
6885  if (IsInvalid) attr.setInvalid();
6886  return true;
6887  }
6888  }
6889 
6890  // Also diagnose fastcall with regparm.
6891  if (CC == CC_X86FastCall && fn->getHasRegParm()) {
6892  S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6894  attr.setInvalid();
6895  return true;
6896  }
6897 
6898  // Modify the CC from the wrapped function type, wrap it all back, and then
6899  // wrap the whole thing in an AttributedType as written. The modified type
6900  // might have a different CC if we ignored the attribute.
6902  if (CCOld == CC) {
6903  Equivalent = type;
6904  } else {
6905  auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
6906  Equivalent =
6907  unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6908  }
6909  type = state.getAttributedType(CCAttr, type, Equivalent);
6910  return true;
6911 }
6912 
6914  QualType R = T.IgnoreParens();
6915  while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
6916  if (AT->isCallingConv())
6917  return true;
6918  R = AT->getModifiedType().IgnoreParens();
6919  }
6920  return false;
6921 }
6922 
6923 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
6924  SourceLocation Loc) {
6925  FunctionTypeUnwrapper Unwrapped(*this, T);
6926  const FunctionType *FT = Unwrapped.get();
6927  bool IsVariadic = (isa<FunctionProtoType>(FT) &&
6928  cast<FunctionProtoType>(FT)->isVariadic());
6929  CallingConv CurCC = FT->getCallConv();
6930  CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
6931 
6932  if (CurCC == ToCC)
6933  return;
6934 
6935  // MS compiler ignores explicit calling convention attributes on structors. We
6936  // should do the same.
6937  if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
6938  // Issue a warning on ignored calling convention -- except of __stdcall.
6939  // Again, this is what MS compiler does.
6940  if (CurCC != CC_X86StdCall)
6941  Diag(Loc, diag::warn_cconv_structors)
6943  // Default adjustment.
6944  } else {
6945  // Only adjust types with the default convention. For example, on Windows
6946  // we should adjust a __cdecl type to __thiscall for instance methods, and a
6947  // __thiscall type to __cdecl for static methods.
6948  CallingConv DefaultCC =
6949  Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6950 
6951  if (CurCC != DefaultCC || DefaultCC == ToCC)
6952  return;
6953 
6954  if (hasExplicitCallingConv(T))
6955  return;
6956  }
6957 
6958  FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6959  QualType Wrapped = Unwrapped.wrap(*this, FT);
6960  T = Context.getAdjustedType(T, Wrapped);
6961 }
6962 
6963 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6964 /// and float scalars, although arrays, pointers, and function return values are
6965 /// allowed in conjunction with this construct. Aggregates with this attribute
6966 /// are invalid, even if they are of the same size as a corresponding scalar.
6967 /// The raw attribute should contain precisely 1 argument, the vector size for
6968 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6969 /// this routine will return a new vector type.
6970 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
6971  Sema &S) {
6972  // Check the attribute arguments.
6973  if (Attr.getNumArgs() != 1) {
6974  S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6975  << 1;
6976  Attr.setInvalid();
6977  return;
6978  }
6979 
6980  Expr *SizeExpr;
6981  // Special case where the argument is a template id.
6982  if (Attr.isArgIdent(0)) {
6983  CXXScopeSpec SS;
6984  SourceLocation TemplateKWLoc;
6985  UnqualifiedId Id;
6986  Id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6987 
6988  ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6989  Id, false, false);
6990 
6991  if (Size.isInvalid())
6992  return;
6993  SizeExpr = Size.get();
6994  } else {
6995  SizeExpr = Attr.getArgAsExpr(0);
6996  }
6997 
6998  QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
6999  if (!T.isNull())
7000  CurType = T;
7001  else
7002  Attr.setInvalid();
7003 }
7004 
7005 /// Process the OpenCL-like ext_vector_type attribute when it occurs on
7006 /// a type.
7007 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7008  Sema &S) {
7009  // check the attribute arguments.
7010  if (Attr.getNumArgs() != 1) {
7011  S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7012  << 1;
7013  return;
7014  }
7015 
7016  Expr *sizeExpr;
7017 
7018  // Special case where the argument is a template id.
7019  if (Attr.isArgIdent(0)) {
7020  CXXScopeSpec SS;
7021  SourceLocation TemplateKWLoc;
7022  UnqualifiedId id;
7023  id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
7024 
7025  ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
7026  id, false, false);
7027  if (Size.isInvalid())
7028  return;
7029 
7030  sizeExpr = Size.get();
7031  } else {
7032  sizeExpr = Attr.getArgAsExpr(0);
7033  }
7034 
7035  // Create the vector type.
7036  QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
7037  if (!T.isNull())
7038  CurType = T;
7039 }
7040 
7042  VectorType::VectorKind VecKind, Sema &S) {
7043  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
7044  if (!BTy)
7045  return false;
7046 
7047  llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
7048 
7049  // Signed poly is mathematically wrong, but has been baked into some ABIs by
7050  // now.
7051  bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
7052  Triple.getArch() == llvm::Triple::aarch64_be;
7053  if (VecKind == VectorType::NeonPolyVector) {
7054  if (IsPolyUnsigned) {
7055  // AArch64 polynomial vectors are unsigned and support poly64.
7056  return BTy->getKind() == BuiltinType::UChar ||
7057  BTy->getKind() == BuiltinType::UShort ||
7058  BTy->getKind() == BuiltinType::ULong ||
7059  BTy->getKind() == BuiltinType::ULongLong;
7060  } else {
7061  // AArch32 polynomial vector are signed.
7062  return BTy->getKind() == BuiltinType::SChar ||
7063  BTy->getKind() == BuiltinType::Short;
7064  }
7065  }
7066 
7067  // Non-polynomial vector types: the usual suspects are allowed, as well as
7068  // float64_t on AArch64.
7069  bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
7070  Triple.getArch() == llvm::Triple::aarch64_be;
7071 
7072  if (Is64Bit && BTy->getKind() == BuiltinType::Double)
7073  return true;
7074 
7075  return BTy->getKind() == BuiltinType::SChar ||
7076  BTy->getKind() == BuiltinType::UChar ||
7077  BTy->getKind() == BuiltinType::Short ||
7078  BTy->getKind() == BuiltinType::UShort ||
7079  BTy->getKind() == BuiltinType::Int ||
7080  BTy->getKind() == BuiltinType::UInt ||
7081  BTy->getKind() == BuiltinType::Long ||
7082  BTy->getKind() == BuiltinType::ULong ||
7083  BTy->getKind() == BuiltinType::LongLong ||
7084  BTy->getKind() == BuiltinType::ULongLong ||
7085  BTy->getKind() == BuiltinType::Float ||
7086  BTy->getKind() == BuiltinType::Half;
7087 }
7088 
7089 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
7090 /// "neon_polyvector_type" attributes are used to create vector types that
7091 /// are mangled according to ARM's ABI. Otherwise, these types are identical
7092 /// to those created with the "vector_size" attribute. Unlike "vector_size"
7093 /// the argument to these Neon attributes is the number of vector elements,
7094 /// not the vector size in bytes. The vector width and element type must
7095 /// match one of the standard Neon vector types.
7096 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7097  Sema &S, VectorType::VectorKind VecKind) {
7098  // Target must have NEON
7099  if (!S.Context.getTargetInfo().hasFeature("neon")) {
7100  S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr;
7101  Attr.setInvalid();
7102  return;
7103  }
7104  // Check the attribute arguments.
7105  if (Attr.getNumArgs() != 1) {
7106  S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7107  << 1;
7108  Attr.setInvalid();
7109  return;
7110  }
7111  // The number of elements must be an ICE.
7112  Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
7113  llvm::APSInt numEltsInt(32);
7114  if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
7115  !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
7116  S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
7117  << Attr << AANT_ArgumentIntegerConstant
7118  << numEltsExpr->getSourceRange();
7119  Attr.setInvalid();
7120  return;
7121  }
7122  // Only certain element types are supported for Neon vectors.
7123  if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
7124  S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
7125  Attr.setInvalid();
7126  return;
7127  }
7128 
7129  // The total size of the vector must be 64 or 128 bits.
7130  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
7131  unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
7132  unsigned vecSize = typeSize * numElts;
7133  if (vecSize != 64 && vecSize != 128) {
7134  S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
7135  Attr.setInvalid();
7136  return;
7137  }
7138 
7139  CurType = S.Context.getVectorType(CurType, numElts, VecKind);
7140 }
7141 
7142 /// Handle OpenCL Access Qualifier Attribute.
7143 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
7144  Sema &S) {
7145  // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
7146  if (!(CurType->isImageType() || CurType->isPipeType())) {
7147  S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
7148  Attr.setInvalid();
7149  return;
7150  }
7151 
7152  if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
7153  QualType BaseTy = TypedefTy->desugar();
7154 
7155  std::string PrevAccessQual;
7156  if (BaseTy->isPipeType()) {
7157  if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
7158  OpenCLAccessAttr *Attr =
7159  TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
7160  PrevAccessQual = Attr->getSpelling();
7161  } else {
7162  PrevAccessQual = "read_only";
7163  }
7164  } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
7165 
7166  switch (ImgType->getKind()) {
7167  #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7168  case BuiltinType::Id: \
7169  PrevAccessQual = #Access; \
7170  break;
7171  #include "clang/Basic/OpenCLImageTypes.def"
7172  default:
7173  llvm_unreachable("Unable to find corresponding image type.");
7174  }
7175  } else {
7176  llvm_unreachable("unexpected type");
7177  }
7178  StringRef AttrName = Attr.getName()->getName();
7179  if (PrevAccessQual == AttrName.ltrim("_")) {
7180  // Duplicated qualifiers
7181  S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
7182  << AttrName << Attr.getRange();
7183  } else {
7184  // Contradicting qualifiers
7185  S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
7186  }
7187 
7188  S.Diag(TypedefTy->getDecl()->getBeginLoc(),
7189  diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
7190  } else if (CurType->isPipeType()) {
7191  if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
7192  QualType ElemType = CurType->getAs<PipeType>()->getElementType();
7193  CurType = S.Context.getWritePipeType(ElemType);
7194  }
7195  }
7196 }
7197 
7198 static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State,
7199  QualType &T, TypeAttrLocation TAL) {
7200  Declarator &D = State.getDeclarator();
7201 
7202  // Handle the cases where address space should not be deduced.
7203  //
7204  // The pointee type of a pointer type is always deduced since a pointer always
7205  // points to some memory location which should has an address space.
7206  //
7207  // There are situations that at the point of certain declarations, the address
7208  // space may be unknown and better to be left as default. For example, when
7209  // defining a typedef or struct type, they are not associated with any
7210  // specific address space. Later on, they may be used with any address space
7211  // to declare a variable.
7212  //
7213  // The return value of a function is r-value, therefore should not have
7214  // address space.
7215  //
7216  // The void type does not occupy memory, therefore should not have address
7217  // space, except when it is used as a pointee type.
7218  //
7219  // Since LLVM assumes function type is in default address space, it should not
7220  // have address space.
7221  auto ChunkIndex = State.getCurrentChunkIndex();
7222  bool IsPointee =
7223  ChunkIndex > 0 &&
7224  (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer ||
7225  D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer ||
7226  D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Reference);
7227  bool IsFuncReturnType =
7228  ChunkIndex > 0 &&
7229  D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function;
7230  bool IsFuncType =
7231  ChunkIndex < D.getNumTypeObjects() &&
7232  D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function;
7233  if ( // Do not deduce addr space for function return type and function type,
7234  // otherwise it will fail some sema check.
7235  IsFuncReturnType || IsFuncType ||
7236  // Do not deduce addr space for member types of struct, except the pointee
7237  // type of a pointer member type.
7238  (D.getContext() == DeclaratorContext::MemberContext && !IsPointee) ||
7239  // Do not deduce addr space for types used to define a typedef and the
7240  // typedef itself, except the pointee type of a pointer type which is used
7241  // to define the typedef.
7243  !IsPointee) ||
7244  // Do not deduce addr space of the void type, e.g. in f(void), otherwise
7245  // it will fail some sema check.
7246  (T->isVoidType() && !IsPointee) ||
7247  // Do not deduce address spaces for dependent types because they might end
7248  // up instantiating to a type with an explicit address space qualifier.
7249  T->isDependentType())
7250  return;
7251 
7252  LangAS ImpAddr = LangAS::Default;
7253  // Put OpenCL automatic variable in private address space.
7254  // OpenCL v1.2 s6.5:
7255  // The default address space name for arguments to a function in a
7256  // program, or local variables of a function is __private. All function
7257  // arguments shall be in the __private address space.
7258  if (State.getSema().getLangOpts().OpenCLVersion <= 120 &&
7259  !State.getSema().getLangOpts().OpenCLCPlusPlus) {
7260  ImpAddr = LangAS::opencl_private;
7261  } else {
7262  // If address space is not set, OpenCL 2.0 defines non private default
7263  // address spaces for some cases:
7264  // OpenCL 2.0, section 6.5:
7265  // The address space for a variable at program scope or a static variable
7266  // inside a function can either be __global or __constant, but defaults to
7267  // __global if not specified.
7268  // (...)
7269  // Pointers that are declared without pointing to a named address space
7270  // point to the generic address space.
7271  if (IsPointee) {
7272  ImpAddr = LangAS::opencl_generic;
7273  } else {
7275  // Do not deduce address space for non-pointee type in template arg.
7276  } else if (D.getContext() == DeclaratorContext::FileContext) {
7277  ImpAddr = LangAS::opencl_global;
7278  } else {
7281  ImpAddr = LangAS::opencl_global;
7282  } else {
7283  ImpAddr = LangAS::opencl_private;
7284  }
7285  }
7286  }
7287  }
7288  T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr);
7289 }
7290 
7291 static void HandleLifetimeBoundAttr(TypeProcessingState &State,
7292  QualType &CurType,
7293  ParsedAttr &Attr) {
7294  if (State.getDeclarator().isDeclarationOfFunction()) {
7295  CurType = State.getAttributedType(
7296  createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
7297  CurType, CurType);
7298  } else {
7299  Attr.diagnoseAppertainsTo(State.getSema(), nullptr);
7300  }
7301 }
7302 
7303 
7304 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
7305  TypeAttrLocation TAL,
7306  ParsedAttributesView &attrs) {
7307  // Scan through and apply attributes to this type where it makes sense. Some
7308  // attributes (such as __address_space__, __vector_size__, etc) apply to the
7309  // type, but others can be present in the type specifiers even though they
7310  // apply to the decl. Here we apply type attributes and ignore the rest.
7311 
7312  // This loop modifies the list pretty frequently, but we still need to make
7313  // sure we visit every element once. Copy the attributes list, and iterate
7314  // over that.
7315  ParsedAttributesView AttrsCopy{attrs};
7316 
7317  state.setParsedNoDeref(false);
7318 
7319  for (ParsedAttr &attr : AttrsCopy) {
7320 
7321  // Skip attributes that were marked to be invalid.
7322  if (attr.isInvalid())
7323  continue;
7324 
7325  if (attr.isCXX11Attribute()) {
7326  // [[gnu::...]] attributes are treated as declaration attributes, so may
7327  // not appertain to a DeclaratorChunk. If we handle them as type
7328  // attributes, accept them in that position and diagnose the GCC
7329  // incompatibility.
7330  if (attr.isGNUScope()) {
7331  bool IsTypeAttr = attr.isTypeAttr();
7332  if (TAL == TAL_DeclChunk) {
7333  state.getSema().Diag(attr.getLoc(),
7334  IsTypeAttr
7335  ? diag::warn_gcc_ignores_type_attr
7336  : diag::warn_cxx11_gnu_attribute_on_type)
7337  << attr.getName();
7338  if (!IsTypeAttr)
7339  continue;
7340  }
7341  } else if (TAL != TAL_DeclChunk) {
7342  // Otherwise, only consider type processing for a C++11 attribute if
7343  // it's actually been applied to a type.
7344  continue;
7345  }
7346  }
7347 
7348  // If this is an attribute we can handle, do so now,
7349  // otherwise, add it to the FnAttrs list for rechaining.
7350  switch (attr.getKind()) {
7351  default:
7352  // A C++11 attribute on a declarator chunk must appertain to a type.
7353  if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
7354  state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
7355  << attr;
7356  attr.setUsedAsTypeAttr();
7357  }
7358  break;
7359 
7361  if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
7362  state.getSema().Diag(attr.getLoc(),
7363  diag::warn_unknown_attribute_ignored)
7364  << attr.getName();
7365  break;
7366 
7368  break;
7369 
7370  case ParsedAttr::AT_MayAlias:
7371  // FIXME: This attribute needs to actually be handled, but if we ignore
7372  // it it breaks large amounts of Linux software.
7373  attr.setUsedAsTypeAttr();
7374  break;
7375  case ParsedAttr::AT_OpenCLPrivateAddressSpace:
7376  case ParsedAttr::AT_OpenCLGlobalAddressSpace:
7377  case ParsedAttr::AT_OpenCLLocalAddressSpace:
7378  case ParsedAttr::AT_OpenCLConstantAddressSpace:
7379  case ParsedAttr::AT_OpenCLGenericAddressSpace:
7380  case ParsedAttr::AT_AddressSpace:
7381  HandleAddressSpaceTypeAttribute(type, attr, state);
7382  attr.setUsedAsTypeAttr();
7383  break;
7385  if (!handleObjCPointerTypeAttr(state, attr, type))
7386  distributeObjCPointerTypeAttr(state, attr, type);
7387  attr.setUsedAsTypeAttr();
7388  break;
7389  case ParsedAttr::AT_VectorSize:
7390  HandleVectorSizeAttr(type, attr, state.getSema());
7391  attr.setUsedAsTypeAttr();
7392  break;
7393  case ParsedAttr::AT_ExtVectorType:
7394  HandleExtVectorTypeAttr(type, attr, state.getSema());
7395  attr.setUsedAsTypeAttr();
7396  break;
7397  case ParsedAttr::AT_NeonVectorType:
7398  HandleNeonVectorTypeAttr(type, attr, state.getSema(),
7400  attr.setUsedAsTypeAttr();
7401  break;
7402  case ParsedAttr::AT_NeonPolyVectorType:
7403  HandleNeonVectorTypeAttr(type, attr, state.getSema(),
7405  attr.setUsedAsTypeAttr();
7406  break;
7407  case ParsedAttr::AT_OpenCLAccess:
7408  HandleOpenCLAccessAttr(type, attr, state.getSema());
7409  attr.setUsedAsTypeAttr();
7410  break;
7411  case ParsedAttr::AT_LifetimeBound:
7412  if (TAL == TAL_DeclChunk)
7413  HandleLifetimeBoundAttr(state, type, attr);
7414  break;
7415 
7416  case ParsedAttr::AT_NoDeref: {
7417  ASTContext &Ctx = state.getSema().Context;
7418  type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
7419  type, type);
7420  attr.setUsedAsTypeAttr();
7421  state.setParsedNoDeref(true);
7422  break;
7423  }
7424 
7426  if (!handleMSPointerTypeQualifierAttr(state, attr, type))
7427  attr.setUsedAsTypeAttr();
7428  break;
7429 
7430 
7432  // Either add nullability here or try to distribute it. We
7433  // don't want to distribute the nullability specifier past any
7434  // dependent type, because that complicates the user model.
7435  if (type->canHaveNullability() || type->isDependentType() ||
7436  type->isArrayType() ||
7437  !distributeNullabilityTypeAttr(state, type, attr)) {
7438  unsigned endIndex;
7439  if (TAL == TAL_DeclChunk)
7440  endIndex = state.getCurrentChunkIndex();
7441  else
7442  endIndex = state.getDeclarator().getNumTypeObjects();
7443  bool allowOnArrayType =
7444  state.getDeclarator().isPrototypeContext() &&
7445  !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
7447  state,
7448  type,
7449  attr,
7450  allowOnArrayType)) {
7451  attr.setInvalid();
7452  }
7453 
7454  attr.setUsedAsTypeAttr();
7455  }
7456  break;
7457 
7458  case ParsedAttr::AT_ObjCKindOf:
7459  // '__kindof' must be part of the decl-specifiers.
7460  switch (TAL) {
7461  case TAL_DeclSpec:
7462  break;
7463 
7464  case TAL_DeclChunk:
7465  case TAL_DeclName:
7466  state.getSema().Diag(attr.getLoc(),
7467  diag::err_objc_kindof_wrong_position)
7468  << FixItHint::CreateRemoval(attr.getLoc())
7470  state.getDeclarator().getDeclSpec().getBeginLoc(),
7471  "__kindof ");
7472  break;
7473  }
7474 
7475  // Apply it regardless.
7476  if (checkObjCKindOfType(state, type, attr))
7477  attr.setInvalid();
7478  break;
7479 
7481  attr.setUsedAsTypeAttr();
7482 
7483  // Never process function type attributes as part of the
7484  // declaration-specifiers.
7485  if (TAL == TAL_DeclSpec)
7486  distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
7487 
7488  // Otherwise, handle the possible delays.
7489  else if (!handleFunctionTypeAttr(state, attr, type))
7490  distributeFunctionTypeAttr(state, attr, type);
7491  break;
7492  }
7493  }
7494 
7495  if (!state.getSema().getLangOpts().OpenCL ||
7496  type.getAddressSpace() != LangAS::Default)
7497  return;
7498 
7499  deduceOpenCLImplicitAddrSpace(state, type, TAL);
7500 }
7501 
7503  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7504  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7505  if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
7506  auto *Def = Var->getDefinition();
7507  if (!Def) {
7508  SourceLocation PointOfInstantiation = E->getExprLoc();
7509  InstantiateVariableDefinition(PointOfInstantiation, Var);
7510  Def = Var->getDefinition();
7511 
7512  // If we don't already have a point of instantiation, and we managed
7513  // to instantiate a definition, this is the point of instantiation.
7514  // Otherwise, we don't request an end-of-TU instantiation, so this is
7515  // not a point of instantiation.
7516  // FIXME: Is this really the right behavior?
7517  if (Var->getPointOfInstantiation().isInvalid() && Def) {
7518  assert(Var->getTemplateSpecializationKind() ==
7520  "explicit instantiation with no point of instantiation");
7521  Var->setTemplateSpecializationKind(
7522  Var->getTemplateSpecializationKind(), PointOfInstantiation);
7523  }
7524  }
7525 
7526  // Update the type to the definition's type both here and within the
7527  // expression.
7528  if (Def) {
7529  DRE->setDecl(Def);
7530  QualType T = Def->getType();
7531  DRE->setType(T);
7532  // FIXME: Update the type on all intervening expressions.
7533  E->setType(T);
7534  }
7535 
7536  // We still go on to try to complete the type independently, as it
7537  // may also require instantiations or diagnostics if it remains
7538  // incomplete.
7539  }
7540  }
7541  }
7542 }
7543 
7544 /// Ensure that the type of the given expression is complete.
7545 ///
7546 /// This routine checks whether the expression \p E has a complete type. If the
7547 /// expression refers to an instantiable construct, that instantiation is
7548 /// performed as needed to complete its type. Furthermore
7549 /// Sema::RequireCompleteType is called for the expression's type (or in the
7550 /// case of a reference type, the referred-to type).
7551 ///
7552 /// \param E The expression whose type is required to be complete.
7553 /// \param Diagnoser The object that will emit a diagnostic if the type is
7554 /// incomplete.
7555 ///
7556 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
7557 /// otherwise.
7559  QualType T = E->getType();
7560 
7561  // Incomplete array types may be completed by the initializer attached to
7562  // their definitions. For static data members of class templates and for
7563  // variable templates, we need to instantiate the definition to get this
7564  // initializer and complete the type.
7565  if (T->isIncompleteArrayType()) {
7566  completeExprArrayBound(E);
7567  T = E->getType();
7568  }
7569 
7570  // FIXME: Are there other cases which require instantiating something other
7571  // than the type to complete the type of an expression?
7572 
7573  return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
7574 }
7575 
7576 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
7577  BoundTypeDiagnoser<> Diagnoser(DiagID);
7578  return RequireCompleteExprType(E, Diagnoser);
7579 }
7580 
7581 /// Ensure that the type T is a complete type.
7582 ///
7583 /// This routine checks whether the type @p T is complete in any
7584 /// context where a complete type is required. If @p T is a complete
7585 /// type, returns false. If @p T is a class template specialization,
7586 /// this routine then attempts to perform class template
7587 /// instantiation. If instantiation fails, or if @p T is incomplete
7588 /// and cannot be completed, issues the diagnostic @p diag (giving it
7589 /// the type @p T) and returns true.
7590 ///
7591 /// @param Loc The location in the source that the incomplete type
7592 /// diagnostic should refer to.
7593 ///
7594 /// @param T The type that this routine is examining for completeness.
7595 ///
7596 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
7597 /// @c false otherwise.
7599  TypeDiagnoser &Diagnoser) {
7600  if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
7601  return true;
7602  if (const TagType *Tag = T->getAs<TagType>()) {
7603  if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
7604  Tag->getDecl()->setCompleteDefinitionRequired();
7605  Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
7606  }
7607  }
7608  return false;
7609 }
7610 
7612  llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
7613  if (!Suggested)
7614  return false;
7615 
7616  // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
7617  // and isolate from other C++ specific checks.
7619  D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
7621  false /*StrictTypeSpelling*/, true /*Complain*/,
7622  true /*ErrorOnTagTypeMismatch*/);
7623  return Ctx.IsEquivalent(D, Suggested);
7624 }
7625 
7626 /// Determine whether there is any declaration of \p D that was ever a
7627 /// definition (perhaps before module merging) and is currently visible.
7628 /// \param D The definition of the entity.
7629 /// \param Suggested Filled in with the declaration that should be made visible
7630 /// in order to provide a definition of this entity.
7631 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
7632 /// not defined. This only matters for enums with a fixed underlying
7633 /// type, since in all other cases, a type is complete if and only if it
7634 /// is defined.
7636  bool OnlyNeedComplete) {
7637  // Easy case: if we don't have modules, all declarations are visible.
7638  if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
7639  return true;
7640 
7641  // If this definition was instantiated from a template, map back to the
7642  // pattern from which it was instantiated.
7643  if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
7644  // We're in the middle of defining it; this definition should be treated
7645  // as visible.
7646  return true;
7647  } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
7648  if (auto *Pattern = RD->getTemplateInstantiationPattern())
7649  RD = Pattern;
7650  D = RD->getDefinition();
7651  } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
7652  if (auto *Pattern = ED->getTemplateInstantiationPattern())
7653  ED = Pattern;
7654  if (OnlyNeedComplete && ED->isFixed()) {
7655  // If the enum has a fixed underlying type, and we're only looking for a
7656  // complete type (not a definition), any visible declaration of it will
7657  // do.
7658  *Suggested = nullptr;
7659  for (auto *Redecl : ED->redecls()) {
7660  if (isVisible(Redecl))
7661  return true;
7662  if (Redecl->isThisDeclarationADefinition() ||
7663  (Redecl->isCanonicalDecl() && !*Suggested))
7664  *Suggested = Redecl;
7665  }
7666  return false;
7667  }
7668  D = ED->getDefinition();
7669  } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7670  if (auto *Pattern = FD->getTemplateInstantiationPattern())
7671  FD = Pattern;
7672  D = FD->getDefinition();
7673  } else if (auto *VD = dyn_cast<VarDecl>(D)) {
7674  if (auto *Pattern = VD->getTemplateInstantiationPattern())
7675  VD = Pattern;
7676  D = VD->getDefinition();
7677  }
7678  assert(D && "missing definition for pattern of instantiated definition");
7679 
7680  *Suggested = D;
7681 
7682  auto DefinitionIsVisible = [&] {
7683  // The (primary) definition might be in a visible module.
7684  if (isVisible(D))
7685  return true;
7686 
7687  // A visible module might have a merged definition instead.
7688  if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D)
7689  : hasVisibleMergedDefinition(D)) {
7690  if (CodeSynthesisContexts.empty() &&
7691  !getLangOpts().ModulesLocalVisibility) {
7692  // Cache the fact that this definition is implicitly visible because
7693  // there is a visible merged definition.
7695  }
7696  return true;
7697  }
7698 
7699  return false;
7700  };
7701 
7702  if (DefinitionIsVisible())
7703  return true;
7704 
7705  // The external source may have additional definitions of this entity that are
7706  // visible, so complete the redeclaration chain now and ask again.
7707  if (auto *Source = Context.getExternalSource()) {
7708  Source->CompleteRedeclChain(D);
7709  return DefinitionIsVisible();
7710  }
7711 
7712  return false;
7713 }
7714 
7715 /// Locks in the inheritance model for the given class and all of its bases.
7717  RD = RD->getMostRecentNonInjectedDecl();
7718  if (!RD->hasAttr<MSInheritanceAttr>()) {
7719  MSInheritanceAttr::Spelling IM;
7720 
7723  IM = RD->calculateInheritanceModel();
7724  break;
7726  IM = MSInheritanceAttr::Keyword_single_inheritance;
7727  break;
7729  IM = MSInheritanceAttr::Keyword_multiple_inheritance;
7730  break;
7732  IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
7733  break;
7734  }
7735 
7736  RD->addAttr(MSInheritanceAttr::CreateImplicit(
7737  S.getASTContext(), IM,
7738  /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
7742  : RD->getSourceRange()));
7744  }
7745 }
7746 
7747 /// The implementation of RequireCompleteType
7748 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
7749  TypeDiagnoser *Diagnoser) {
7750  // FIXME: Add this assertion to make sure we always get instantiation points.
7751  // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
7752  // FIXME: Add this assertion to help us flush out problems with
7753  // checking for dependent types and type-dependent expressions.
7754  //
7755  // assert(!T->isDependentType() &&
7756  // "Can't ask whether a dependent type is complete");
7757 
7758  if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
7759  if (!MPTy->getClass()->isDependentType()) {
7760  if (getLangOpts().CompleteMemberPointers &&
7761  !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
7762  RequireCompleteType(Loc, QualType(MPTy->getClass(), 0),
7763  diag::err_memptr_incomplete))
7764  return true;
7765 
7766  // We lock in the inheritance model once somebody has asked us to ensure
7767  // that a pointer-to-member type is complete.
7768  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7769  (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
7770  assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
7771  }
7772  }
7773  }
7774 
7775  NamedDecl *Def = nullptr;
7776  bool Incomplete = T->isIncompleteType(&Def);
7777 
7778  // Check that any necessary explicit specializations are visible. For an
7779  // enum, we just need the declaration, so don't check this.
7780  if (Def && !isa<EnumDecl>(Def))
7781  checkSpecializationVisibility(Loc, Def);
7782 
7783  // If we have a complete type, we're done.
7784  if (!Incomplete) {
7785  // If we know about the definition but it is not visible, complain.
7786  NamedDecl *SuggestedDef = nullptr;
7787  if (Def &&
7788  !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
7789  // If the user is going to see an error here, recover by making the
7790  // definition visible.
7791  bool TreatAsComplete = Diagnoser && !isSFINAEContext();
7792  if (Diagnoser && SuggestedDef)
7793  diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
7794  /*Recover*/TreatAsComplete);
7795  return !TreatAsComplete;
7796  } else if (Def && !TemplateInstCallbacks.empty()) {
7797  CodeSynthesisContext TempInst;
7798  TempInst.Kind = CodeSynthesisContext::Memoization;
7799  TempInst.Template = Def;
7800  TempInst.Entity = Def;
7801  TempInst.PointOfInstantiation = Loc;
7802  atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
7803  atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
7804  }
7805 
7806  return false;
7807  }
7808 
7809  TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
7810  ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
7811 
7812  // Give the external source a chance to provide a definition of the type.
7813  // This is kept separate from completing the redeclaration chain so that
7814  // external sources such as LLDB can avoid synthesizing a type definition
7815  // unless it's actually needed.
7816  if (Tag || IFace) {
7817  // Avoid diagnosing invalid decls as incomplete.
7818  if (Def->isInvalidDecl())
7819  return true;
7820 
7821  // Give the external AST source a chance to complete the type.
7822  if (auto *Source = Context.getExternalSource()) {
7823  if (Tag && Tag->hasExternalLexicalStorage())
7824  Source->CompleteType(Tag);
7825  if (IFace && IFace->hasExternalLexicalStorage())
7826  Source->CompleteType(IFace);
7827  // If the external source completed the type, go through the motions
7828  // again to ensure we're allowed to use the completed type.
7829  if (!T->isIncompleteType())
7830  return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7831  }
7832  }
7833 
7834  // If we have a class template specialization or a class member of a
7835  // class template specialization, or an array with known size of such,
7836  // try to instantiate it.
7837  if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
7838  bool Instantiated = false;
7839  bool Diagnosed = false;
7840  if (RD->isDependentContext()) {
7841  // Don't try to instantiate a dependent class (eg, a member template of
7842  // an instantiated class template specialization).
7843  // FIXME: Can this ever happen?
7844  } else if (auto *ClassTemplateSpec =
7845  dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
7846  if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
7847  Diagnosed = InstantiateClassTemplateSpecialization(
7848  Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
7849  /*Complain=*/Diagnoser);
7850  Instantiated = true;
7851  }
7852  } else {
7854  if (!RD->isBeingDefined() && Pattern) {
7855  MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
7856  assert(MSI && "Missing member specialization information?");
7857  // This record was instantiated from a class within a template.
7858  if (MSI->getTemplateSpecializationKind() !=
7860  Diagnosed = InstantiateClass(Loc, RD, Pattern,
7861  getTemplateInstantiationArgs(RD),
7863  /*Complain=*/Diagnoser);
7864  Instantiated = true;
7865  }
7866  }
7867  }
7868 
7869  if (Instantiated) {
7870  // Instantiate* might have already complained that the template is not
7871  // defined, if we asked it to.
7872  if (Diagnoser && Diagnosed)
7873  return true;
7874  // If we instantiated a definition, check that it's usable, even if
7875  // instantiation produced an error, so that repeated calls to this
7876  // function give consistent answers.
7877  if (!T->isIncompleteType())
7878  return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7879  }
7880  }
7881 
7882  // FIXME: If we didn't instantiate a definition because of an explicit
7883  // specialization declaration, check that it's visible.
7884 
7885  if (!Diagnoser)
7886  return true;
7887 
7888  Diagnoser->diagnose(*this, Loc, T);
7889 
7890  // If the type was a forward declaration of a class/struct/union
7891  // type, produce a note.
7892  if (Tag && !Tag->isInvalidDecl())
7893  Diag(Tag->getLocation(),
7894  Tag->isBeingDefined() ? diag::note_type_being_defined
7895  : diag::note_forward_declaration)
7896  << Context.getTagDeclType(Tag);
7897 
7898  // If the Objective-C class was a forward declaration, produce a note.
7899  if (IFace && !IFace->isInvalidDecl())
7900  Diag(IFace->getLocation(), diag::note_forward_class);
7901 
7902  // If we have external information that we can use to suggest a fix,
7903  // produce a note.
7904  if (ExternalSource)
7905  ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
7906 
7907  return true;
7908 }
7909 
7911  unsigned DiagID) {
7912  BoundTypeDiagnoser<> Diagnoser(DiagID);
7913  return RequireCompleteType(Loc, T, Diagnoser);
7914 }
7915 
7916 /// Get diagnostic %select index for tag kind for
7917 /// literal type diagnostic message.
7918 /// WARNING: Indexes apply to particular diagnostics only!
7919 ///
7920 /// \returns diagnostic %select index.
7922  switch (Tag) {
7923  case TTK_Struct: return 0;
7924  case TTK_Interface: return 1;
7925  case TTK_Class: return 2;
7926  default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
7927  }
7928 }
7929 
7930 /// Ensure that the type T is a literal type.
7931 ///
7932 /// This routine checks whether the type @p T is a literal type. If @p T is an
7933 /// incomplete type, an attempt is made to complete it. If @p T is a literal
7934 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
7935 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
7936 /// it the type @p T), along with notes explaining why the type is not a
7937 /// literal type, and returns true.
7938 ///
7939 /// @param Loc The location in the source that the non-literal type
7940 /// diagnostic should refer to.
7941 ///
7942 /// @param T The type that this routine is examining for literalness.
7943 ///
7944 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
7945 ///
7946 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
7947 /// @c false otherwise.
7949  TypeDiagnoser &Diagnoser) {
7950  assert(!T->isDependentType() && "type should not be dependent");
7951 
7952  QualType ElemType = Context.getBaseElementType(T);
7953  if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
7954  T->isLiteralType(Context))
7955  return false;
7956 
7957  Diagnoser.diagnose(*this, Loc, T);
7958 
7959  if (T->isVariableArrayType())
7960  return true;
7961 
7962  const RecordType *RT = ElemType->getAs<RecordType>();
7963  if (!RT)
7964  return true;
7965 
7966  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7967 
7968  // A partially-defined class type can't be a literal type, because a literal
7969  // class type must have a trivial destructor (which can't be checked until
7970  // the class definition is complete).
7971  if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
7972  return true;
7973 
7974  // [expr.prim.lambda]p3:
7975  // This class type is [not] a literal type.
7976  if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
7977  Diag(RD->getLocation(), diag::note_non_literal_lambda);
7978  return true;
7979  }
7980 
7981  // If the class has virtual base classes, then it's not an aggregate, and
7982  // cannot have any constexpr constructors or a trivial default constructor,
7983  // so is non-literal. This is better to diagnose than the resulting absence
7984  // of constexpr constructors.
7985  if (RD->getNumVBases()) {
7986  Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
7988  for (const auto &I : RD->vbases())
7989  Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
7990  << I.getSourceRange();
7991  } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
7993  Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
7994  } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
7995  for (const auto &I : RD->bases()) {
7996  if (!I.getType()->isLiteralType(Context)) {
7997  Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
7998  << RD << I.getType() << I.getSourceRange();
7999  return true;
8000  }
8001  }
8002  for (const auto *I : RD->fields()) {
8003  if (!I->getType()->isLiteralType(Context) ||
8004  I->getType().isVolatileQualified()) {
8005  Diag(I->getLocation(), diag::note_non_literal_field)
8006  << RD << I << I->getType()
8007  << I->getType().isVolatileQualified();
8008  return true;
8009  }
8010  }
8011  } else if (!RD->hasTrivialDestructor()) {
8012  // All fields and bases are of literal types, so have trivial destructors.
8013  // If this class's destructor is non-trivial it must be user-declared.
8014  CXXDestructorDecl *Dtor = RD->getDestructor();
8015  assert(Dtor && "class has literal fields and bases but no dtor?");
8016  if (!Dtor)
8017  return true;
8018 
8019  Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
8020  diag::note_non_literal_user_provided_dtor :
8021  diag::note_non_literal_nontrivial_dtor) << RD;
8022  if (!Dtor->isUserProvided())
8023  SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
8024  /*Diagnose*/true);
8025  }
8026 
8027  return true;
8028 }
8029 
8030 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
8031  BoundTypeDiagnoser<> Diagnoser(DiagID);
8032  return RequireLiteralType(Loc, T, Diagnoser);
8033 }
8034 
8035 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
8036 /// by the nested-name-specifier contained in SS, and that is (re)declared by
8037 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
8039  const CXXScopeSpec &SS, QualType T,
8040  TagDecl *OwnedTagDecl) {
8041  if (T.isNull())
8042  return T;
8043  NestedNameSpecifier *NNS;
8044  if (SS.isValid())
8045  NNS = SS.getScopeRep();
8046  else {
8047  if (Keyword == ETK_None)
8048  return T;
8049  NNS = nullptr;
8050  }
8051  return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl);
8052 }
8053 
8055  assert(!E->hasPlaceholderType() && "unexpected placeholder");
8056 
8057  if (!getLangOpts().CPlusPlus && E->refersToBitField())
8058  Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
8059 
8060  if (!E->isTypeDependent()) {
8061  QualType T = E->getType();
8062  if (const TagType *TT = T->getAs<TagType>())
8063  DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
8064  }
8065  return Context.getTypeOfExprType(E);
8066 }
8067 
8068 /// getDecltypeForExpr - Given an expr, will return the decltype for
8069 /// that expression, according to the rules in C++11
8070 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
8072  if (E->isTypeDependent())
8073  return S.Context.DependentTy;
8074 
8075  // C++11 [dcl.type.simple]p4:
8076  // The type denoted by decltype(e) is defined as follows:
8077  //
8078  // - if e is an unparenthesized id-expression or an unparenthesized class
8079  // member access (5.2.5), decltype(e) is the type of the entity named
8080  // by e. If there is no such entity, or if e names a set of overloaded
8081  // functions, the program is ill-formed;
8082  //
8083  // We apply the same rules for Objective-C ivar and property references.
8084  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8085  const ValueDecl *VD = DRE->getDecl();
8086  return VD->getType();
8087  } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8088  if (const ValueDecl *VD = ME->getMemberDecl())
8089  if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
8090  return VD->getType();
8091  } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
8092  return IR->getDecl()->getType();
8093  } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
8094  if (PR->isExplicitProperty())
8095  return PR->getExplicitProperty()->getType();
8096  } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
8097  return PE->getType();
8098  }
8099 
8100  // C++11 [expr.lambda.prim]p18:
8101  // Every occurrence of decltype((x)) where x is a possibly
8102  // parenthesized id-expression that names an entity of automatic
8103  // storage duration is treated as if x were transformed into an
8104  // access to a corresponding data member of the closure type that
8105  // would have been declared if x were an odr-use of the denoted
8106  // entity.
8107  using namespace sema;
8108  if (S.getCurLambda()) {
8109  if (isa<ParenExpr>(E)) {
8110  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8111  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8112  QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
8113  if (!T.isNull())
8114  return S.Context.getLValueReferenceType(T);
8115  }
8116  }
8117  }
8118  }
8119 
8120 
8121  // C++11 [dcl.type.simple]p4:
8122  // [...]
8123  QualType T = E->getType();
8124  switch (E->getValueKind()) {
8125  // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
8126  // type of e;
8127  case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
8128  // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
8129  // type of e;
8130  case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
8131  // - otherwise, decltype(e) is the type of e.
8132  case VK_RValue: break;
8133  }
8134 
8135  return T;
8136 }
8137 
8139  bool AsUnevaluated) {
8140  assert(!E->hasPlaceholderType() && "unexpected placeholder");
8141 
8142  if (AsUnevaluated && CodeSynthesisContexts.empty() &&
8143  E->HasSideEffects(Context, false)) {
8144  // The expression operand for decltype is in an unevaluated expression
8145  // context, so side effects could result in unintended consequences.
8146  Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8147  }
8148 
8149  return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
8150 }
8151 
8154  SourceLocation Loc) {
8155  switch (UKind) {
8157  if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
8158  Diag(Loc, diag::err_only_enums_have_underlying_types);
8159  return QualType();
8160  } else {
8161  QualType Underlying = BaseType;
8162  if (!BaseType->isDependentType()) {
8163  // The enum could be incomplete if we're parsing its definition or
8164  // recovering from an error.
8165  NamedDecl *FwdDecl = nullptr;
8166  if (BaseType->isIncompleteType(&FwdDecl)) {
8167  Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
8168  Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
8169  return QualType();
8170  }
8171 
8172  EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
8173  assert(ED && "EnumType has no EnumDecl");
8174 
8175  DiagnoseUseOfDecl(ED, Loc);
8176 
8177  Underlying = ED->getIntegerType();
8178  assert(!Underlying.isNull());
8179  }
8180  return Context.getUnaryTransformType(BaseType, Underlying,
8182  }
8183  }
8184  llvm_unreachable("unknown unary transform type");
8185 }
8186 
8188  if (!T->isDependentType()) {
8189  // FIXME: It isn't entirely clear whether incomplete atomic types
8190  // are allowed or not; for simplicity, ban them for the moment.
8191  if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
8192  return QualType();
8193 
8194  int DisallowedKind = -1;
8195  if (T->isArrayType())
8196  DisallowedKind = 1;
8197  else if (T->isFunctionType())
8198  DisallowedKind = 2;
8199  else if (T->isReferenceType())
8200  DisallowedKind = 3;
8201  else if (T->isAtomicType())
8202  DisallowedKind = 4;
8203  else if (T.hasQualifiers())
8204  DisallowedKind = 5;
8205  else if (!T.isTriviallyCopyableType(Context))
8206  // Some other non-trivially-copyable type (probably a C++ class)
8207  DisallowedKind = 6;
8208 
8209  if (DisallowedKind != -1) {
8210  Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
8211  return QualType();
8212  }
8213 
8214  // FIXME: Do we need any handling for ARC here?
8215  }
8216 
8217  // Build the pointer type.
8218  return Context.getAtomicType(T);
8219 }
FileNullabilityMap NullabilityMap
A mapping that describes the nullability we&#39;ve seen in each header file.
Definition: Sema.h:489
Abstract class used to diagnose incomplete types.
Definition: Sema.h:1510
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition: DeclSpec.h:1480
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:577
static void checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, SourceLocation pointerLoc, SourceLocation pointerEndLoc=SourceLocation())
Complains about missing nullability if the file containing pointerLoc has other uses of nullability (...
Definition: SemaType.cpp:3798
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
AttributePool & getAttributePool() const
Definition: DeclSpec.h:1863
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Defines the clang::ASTContext interface.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
bool IsStatic
Definition: Format.cpp:1640
Represents a type that was referred to using an elaborated type keyword, e.g., struct S...
Definition: Type.h:5129
TypeLoc getValueLoc() const
Definition: TypeLoc.h:2208
unsigned UnalignedQualLoc
The location of the __unaligned-qualifier, if any.
Definition: DeclSpec.h:1183
const Type * Ty
The locally-unqualified type.
Definition: Type.h:579
bool diagnoseAppertainsTo(class Sema &S, const Decl *D) const
Definition: ParsedAttr.cpp:208
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
CanQualType LongLongTy
Definition: ASTContext.h:1025
static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for literal type diagnostic message.
Definition: SemaType.cpp:7921
const internal::VariadicDynCastAllOfMatcher< Decl, TypedefDecl > typedefDecl
Matches typedef declarations.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:5697
QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef< ObjCProtocolDecl *> Protocols, ArrayRef< SourceLocation > ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError=false)
Build an Objective-C type parameter type.
Definition: SemaType.cpp:1008
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2268
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition: DeclSpec.h:1265
static bool isOmittedBlockReturnType(const Declarator &D)
isOmittedBlockReturnType - Return true if this declarator is missing a return type because this is a ...
Definition: SemaType.cpp:50
CanQualType AccumTy
Definition: ASTContext.h:1029
no exception specification
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:2477
This is a discriminated union of FileInfo and ExpansionInfo.
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
PtrTy get() const
Definition: Ownership.h:81
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2537
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: Type.h:4023
QualType BuildWritePipeType(QualType T, SourceLocation Loc)
Build a Write-only Pipe type.
Definition: SemaType.cpp:2044
A (possibly-)qualified type.
Definition: Type.h:638
ASTConsumer & Consumer
Definition: Sema.h:325
bool isBlockPointerType() const
Definition: Type.h:6304
base_class_range bases()
Definition: DeclCXX.h:823
bool isArrayType() const
Definition: Type.h:6345
bool isMemberPointerType() const
Definition: Type.h:6327
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1278
Wrapper for source info for tag types.
Definition: TypeLoc.h:701
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1134
static const TSS TSS_unsigned
Definition: DeclSpec.h:268
static bool hasNullabilityAttr(const ParsedAttributesView &attrs)
Check whether there is a nullability attribute of any kind in the given attribute list...
Definition: SemaType.cpp:3493
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:403
QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc)
Definition: SemaType.cpp:8152
__auto_type (GNU extension)
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2179
CanQualType FractTy
Definition: ASTContext.h:1032
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:3055
void setNameEndLoc(SourceLocation Loc)
Definition: TypeLoc.h:1074
static const TST TST_wchar
Definition: DeclSpec.h:275
llvm::PointerUnion< Expr *, IdentifierLoc * > ArgsUnion
A union of the various pointer types that can be passed to an ParsedAttr as an argument.
Definition: ParsedAttr.h:105
CanQualType Char32Ty
Definition: ASTContext.h:1024
#define CALLING_CONV_ATTRS_CASELIST
Definition: SemaType.cpp:110
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2272
The attribute is immediately after the declaration&#39;s name.
Definition: SemaType.cpp:324
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1374
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition: TypeLoc.h:168
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1209
const internal::VariadicDynCastAllOfMatcher< Decl, RecordDecl > recordDecl
Matches class, struct, and union declarations.
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:286
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1388
Kind getKind() const
Definition: Type.h:2418
QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef< TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef< ObjCProtocolDecl *> Protocols, ArrayRef< SourceLocation > ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError=false)
Build an Objective-C object pointer type.
Definition: SemaType.cpp:1031
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3355
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:949
TypeLoc getValueLoc() const
Definition: TypeLoc.h:2267
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1937
void setEmbeddedInDeclarator(bool isInDeclarator)
True if this tag declaration is "embedded" (i.e., defined or declared for the very first time) in the...
Definition: Decl.h:3199
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:838
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:472
Represents the declaration of a typedef-name via the &#39;typedef&#39; type specifier.
Definition: Decl.h:3018
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:807
Microsoft&#39;s &#39;__super&#39; specifier, stored as a CXXRecordDecl* of the class it appeared in...
bool isRecordType() const
Definition: Type.h:6369
bool isDecltypeAuto() const
Definition: Type.h:4760
static const TST TST_typeofExpr
Definition: DeclSpec.h:299
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1933
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type &#39;T&#39; that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:8038
const Type * getTypeForDecl() const
Definition: Decl.h:2898
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1308
static const TST TST_char16
Definition: DeclSpec.h:277
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, QualType type)
diagnoseBadTypeAttribute - Diagnoses a type attribute which doesn&#39;t apply to the given type...
Definition: SemaType.cpp:67
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4002
WrittenBuiltinSpecs & getWrittenBuiltinSpecs()
Definition: TypeLoc.h:569
void setType(QualType t)
Definition: Expr.h:129
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
Defines the C++ template declaration subclasses.
Represents a C++11 auto or C++14 decltype(auto) type.
Definition: Type.h:4749
IdentifierInfo * Ident
Definition: ParsedAttr.h:97
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:7286
QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity)
Build an array type.
Definition: SemaType.cpp:2085
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition: DeclObjC.cpp:308
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer...
A constructor named via a template-id.
Expr * getArgAsExpr(unsigned Arg) const
Definition: ParsedAttr.h:460
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorType::VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type...
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
SourceLocation getLParenLoc() const
Definition: DeclSpec.h:1391
The base class of the type hierarchy.
Definition: Type.h:1407
bool hasTrailingReturnType() const
Determine whether a trailing return type was written (at any level) within this declarator.
Definition: DeclSpec.h:2385
CanQualType LongTy
Definition: ASTContext.h:1025
DiagnosticsEngine & getDiagnostics() const
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1890
One instance of this struct is used for each type in a declarator that is parsed. ...
Definition: DeclSpec.h:1148
QualType getCorrespondingUnsignedType(QualType T) const
SourceLocation EndLoc
EndLoc - If valid, the place where this chunck ends.
Definition: DeclSpec.h:1156
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2237
Wrapper for source info for typedefs.
Definition: TypeLoc.h:664
static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk)
Definition: SemaType.cpp:5593
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:521
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:1891
void setUsedAsTypeAttr()
Definition: ParsedAttr.h:438
bool isTypeSpecSat() const
Definition: DeclSpec.h:490
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:690
The attribute is part of a DeclaratorChunk.
Definition: SemaType.cpp:322
A container of type source information.
Definition: Decl.h:87
bool getHasRegParm() const
Definition: Type.h:3615
bool hasConstexprNonCopyMoveConstructor() const
Determine whether this class has at least one constexpr constructor other than the copy or move const...
Definition: DeclCXX.h:1378
static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, unsigned &TypeQuals, QualType TypeSoFar, unsigned RemoveTQs, unsigned DiagID)
Definition: SemaType.cpp:744
static void fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, const ParsedAttributesView &Attrs)
Definition: SemaType.cpp:5618
static void transferARCOwnership(TypeProcessingState &state, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership)
Used for transferring ownership in casts resulting in l-values.
Definition: SemaType.cpp:5227
An overloaded operator name, e.g., operator+.
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:626
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1163
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:9977
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:1395
SourceLocation getLocalBeginLoc() const
Retrieve the location of the beginning of this component of the nested-name-specifier.
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:227
#define NULLABILITY_TYPE_ATTRS_CASELIST
Definition: SemaType.cpp:144
CanQualType HalfTy
Definition: ASTContext.h:1040
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2409
unsigned RestrictQualLoc
The location of the restrict-qualifier, if any.
Definition: DeclSpec.h:1177
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:840
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:2857
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3169
void setParensRange(SourceRange range)
Definition: TypeLoc.h:1804
An identifier, stored as an IdentifierInfo*.
QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc)
BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression is uninstantiated.
Definition: SemaType.cpp:5759
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition: DeclSpec.h:2291
Represents a variable declaration or definition.
Definition: Decl.h:813
static bool handleObjCPointerTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
Definition: SemaType.cpp:342
static OpenCLAccessAttr::Spelling getImageAccess(const ParsedAttributesView &Attrs)
Definition: SemaType.cpp:1217
unsigned isStar
True if this dimension was [*]. In this case, NumElts is null.
Definition: DeclSpec.h:1207
static DeclaratorChunk * maybeMovePastReturnType(Declarator &declarator, unsigned i, bool onlyBlockPointers)
Given the index of a declarator chunk, check whether that chunk directly specifies the return type of...
Definition: SemaType.cpp:359
static const TST TST_underlyingType
Definition: DeclSpec.h:302
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1765
void removeObjCLifetime()
Definition: Type.h:332
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:67
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location. ...
Definition: TypeLoc.h:190
DiagnosticsEngine & Diags
Definition: Sema.h:326
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1232
bool isEnumeralType() const
Definition: Type.h:6373
Wrapper of type source information for a type with non-trivial direct qualifiers. ...
Definition: TypeLoc.h:271
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6748
CanQualType Float128Ty
Definition: ASTContext.h:1028
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
The "union" keyword.
Definition: Type.h:5039
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition: DeclSpec.cpp:437
Extra information about a function prototype.
Definition: Type.h:3767
CanQualType ShortAccumTy
Definition: ASTContext.h:1029
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:26
Represents a C++17 deduced template specialization type.
Definition: Type.h:4785
The "__interface" keyword.
Definition: Type.h:5036
attribute((...))
Definition: ParsedAttr.h:142
bool isCXX11Attribute() const
Definition: ParsedAttr.h:406
static const TST TST_interface
Definition: DeclSpec.h:295
static const TST TST_char
Definition: DeclSpec.h:274
A namespace, stored as a NamespaceDecl*.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1363
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:1972
bool isInvalidDecl() const
Definition: DeclBase.h:542
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:1690
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:609
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
CanQualType ShortFractTy
Definition: ASTContext.h:1032
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition: DeclSpec.h:1452
bool hasDefinition() const
Definition: DeclCXX.h:776
unsigned getNumExceptions() const
Get the number of dynamic exception specifications.
Definition: DeclSpec.h:1463
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:630
Represents a parameter to a function.
Definition: Decl.h:1550
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1232
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1952
SourceLocation Loc
Definition: ParsedAttr.h:96
The collection of all-type qualifiers we support.
Definition: Type.h:141
bool isVariableArrayType() const
Definition: Type.h:6357
PipeType - OpenCL20.
Definition: Type.h:6002
bool needsExtraLocalData() const
Definition: TypeLoc.h:576
SourceRange getTypeSpecWidthRange() const
Definition: DeclSpec.h:512
void setParensRange(SourceRange Range)
Definition: TypeLoc.h:2244
static const TST TST_unknown_anytype
Definition: DeclSpec.h:305
bool canHaveNullability(bool ResultIfUnknown=true) const
Determine whether the given type can have a nullability specifier applied to it, i.e., if it is any kind of pointer type.
Definition: Type.cpp:3709
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:57
MSInheritanceAttr::Spelling calculateInheritanceModel() const
Calculate what the inheritance model would be for this class.
QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity)
Build a member pointer type T Class::*.
Definition: SemaType.cpp:2526
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
Represents a struct/union/class.
Definition: Decl.h:3593
static AttrT * createSimpleAttr(ASTContext &Ctx, ParsedAttr &Attr)
Definition: SemaType.cpp:3898
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1327
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:298
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
Expr * NoexceptExpr
Pointer to the expression in the noexcept-specifier of this function, if it has one.
Definition: DeclSpec.h:1329
TypeSpecifierSign getWrittenSignSpec() const
Definition: TypeLoc.h:596
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3768
One of these records is kept for each identifier that is lexed.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1018
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1358
static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, QualifiedFunctionKind QFK)
Check whether the type T is a qualified function type, and if it is, diagnose that it cannot be conta...
Definition: SemaType.cpp:1909
static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex)
Returns true if any of the declarator chunks before endIndex include a level of indirection: array...
Definition: SemaType.cpp:3868
unsigned getAttributeSpellingListIndex() const
Get an index into the attribute spelling list defined in Attr.td.
Definition: ParsedAttr.cpp:157
SourceLocation getExceptionSpecLocBeg() const
Definition: DeclSpec.h:1403
const WrittenBuiltinSpecs & getWrittenBuiltinSpecs() const
Definition: DeclSpec.h:774
SourceLocation getBegin() const
static const TST TST_decimal32
Definition: DeclSpec.h:289
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
QualType IgnoreParens() const
Returns the specified type after dropping any outer-level parentheses.
Definition: Type.h:957
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition: DeclSpec.h:970
void removeRestrict()
Definition: Type.h:270
Represents a class type in Objective C.
Definition: Type.h:5538
static const TST TST_char8
Definition: DeclSpec.h:276
static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State, QualType &T, TypeAttrLocation TAL)
Definition: SemaType.cpp:7198
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:155
A C++ nested-name-specifier augmented with source location information.
is ARM Neon vector
Definition: Type.h:3184
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:7520
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3895
LineState State
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:515
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3941
QualType BuildParenType(QualType T)
Build a paren type including T.
Definition: SemaType.cpp:1814
void setBuiltinLoc(SourceLocation Loc)
Definition: TypeLoc.h:553
QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc)
Definition: SemaType.cpp:2294
bool isSpelledAsLValue() const
Definition: Type.h:2689
field_range fields() const
Definition: Decl.h:3784
void setRBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1477
static SourceLocation getFromRawEncoding(unsigned Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
HandleVectorSizeAttribute - this attribute is only applicable to integral and float scalars...
Definition: SemaType.cpp:6970
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:288
static const TST TST_class
Definition: DeclSpec.h:296
NameKind getNameKind() const
Determine what kind of name this is.
static void fillAttributedTypeLoc(AttributedTypeLoc TL, TypeProcessingState &State)
Definition: SemaType.cpp:5293
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
void removeConst()
Definition: Type.h:260
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible...
Definition: DeclBase.h:773
static const TST TST_double
Definition: DeclSpec.h:283
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:527
CanQualType LongAccumTy
Definition: ASTContext.h:1029
bool isReferenceType() const
Definition: Type.h:6308
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2002
static bool IsNoDerefableChunk(DeclaratorChunk Chunk)
Definition: SemaType.cpp:3892
static std::string getPrintableNameForEntity(DeclarationName Entity)
Definition: SemaType.cpp:1715
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:406
ParsedType ActOnObjCInstanceType(SourceLocation Loc)
The parser has parsed the context-sensitive type &#39;instancetype&#39; in an Objective-C message declaration...
Definition: SemaType.cpp:5745
static const TST TST_error
Definition: DeclSpec.h:310
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6...
Definition: SemaType.cpp:7611
static const TST TST_enum
Definition: DeclSpec.h:292
static void maybeSynthesizeBlockSignature(TypeProcessingState &state, QualType declSpecType)
Add a synthetic &#39;()&#39; to a block-literal declarator if it is required, given the return type...
Definition: SemaType.cpp:688
TypeLoc getNextTypeLoc() const
Definition: TypeLoc.h:399
static const TSW TSW_unspecified
Definition: DeclSpec.h:253
void copy(DependentTemplateSpecializationTypeLoc Loc)
Definition: TypeLoc.h:2146
bool hasTagDefinition() const
Definition: DeclSpec.cpp:428
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition: TypeLoc.h:1885
TSC getTypeSpecComplex() const
Definition: DeclSpec.h:481
Wrapper of type source information for a type with no direct qualifiers.
Definition: TypeLoc.h:245
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
const AstTypeMatcher< TypedefType > typedefType
Matches typedef types.
i32 captured_struct **param SharedsTy A type which contains references the shared variables *param Shareds Context with the list of shared variables from the p *TaskFunction *param Data Additional data for task generation like final * state
static const TST TST_accum
Definition: DeclSpec.h:285
A user-defined literal name, e.g., operator "" _i.
IdentifierTable & Idents
Definition: ASTContext.h:566
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition: ParsedAttr.h:448
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:110
bool isInvalidType() const
Definition: DeclSpec.h:2443
Values of this type can be null.
static void inferARCWriteback(TypeProcessingState &state, QualType &declSpecType)
Given that this is the declaration of a parameter under ARC, attempt to infer attributes and such for...
Definition: SemaType.cpp:2615
CanQualType LongFractTy
Definition: ASTContext.h:1032
bool getProducesResult() const
Definition: Type.h:3513
static void HandleLifetimeBoundAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &Attr)
Definition: SemaType.cpp:7291
PointerTypeInfo Ptr
Definition: DeclSpec.h:1517
bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value)
void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn&#39;t specified explicitly...
Definition: SemaType.cpp:6923
bool isInvalid() const
TypeSpecifierWidth getWrittenWidthSpec() const
Definition: TypeLoc.h:612
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment...
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:934
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:1332
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
bool hasNonLiteralTypeFieldsOrBases() const
Determine whether this class has a non-literal or/ volatile type non-static data member or base class...
Definition: DeclCXX.h:1520
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:521
void setAttr(const Attr *A)
Definition: TypeLoc.h:874
static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, TypeSourceInfo *&ReturnTypeInfo)
Definition: SemaType.cpp:2832
Represents the results of name lookup.
Definition: Lookup.h:47
PtrTy get() const
Definition: Ownership.h:174
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1363
unsigned ConstQualLoc
The location of the const-qualifier, if any.
Definition: DeclSpec.h:1171
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:437
static void fixItNullability(Sema &S, DiagnosticBuilder &Diag, SourceLocation PointerLoc, NullabilityKind Nullability)
Creates a fix-it to insert a C-style nullability keyword at pointerLoc, taking into account whitespac...
Definition: SemaType.cpp:3729
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: &#39; &#39;, &#39;\t&#39;, &#39;\f&#39;, &#39;\v&#39;, &#39;\n&#39;, &#39;\r&#39;.
Definition: CharInfo.h:88
void setCaretLoc(SourceLocation Loc)
Definition: TypeLoc.h:1222
TagKind getTagKind() const
Definition: Decl.h:3243
static PointerDeclaratorKind classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, PointerWrappingDeclaratorKind &wrappingKind)
Classify the given declarator, whose type-specified is type, based on what kind of pointer it refers ...
Definition: SemaType.cpp:3539
const FileInfo & getFile() const
bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T)
Check if type T corresponding to declaration specifier DS is disabled due to required OpenCL extensio...
Definition: Sema.cpp:1981
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD=nullptr)
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2205
bool isTypeSpecPipe() const
Definition: DeclSpec.h:489
const Type * getClass() const
Definition: TypeLoc.h:1244
Wrapper for source info for functions.
Definition: TypeLoc.h:1327
static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
Definition: Type.cpp:2514
ArrayTypeInfo Arr
Definition: DeclSpec.h:1519
static bool hasDirectOwnershipQualifier(QualType type)
Does this type have a "direct" ownership qualifier? That is, is it written like "__strong id"...
Definition: SemaType.cpp:5920
Whether values of this type can be null is (explicitly) unspecified.
An x-value expression is a reference to an object with independent storage but which can be "moved"...
Definition: Specifiers.h:119
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:405
static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, QualType &declSpecType)
Given that there are attributes written on the declarator itself, try to distribute any type attribut...
Definition: SemaType.cpp:645
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2175
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:654
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1831
void addCVRQualifiers(unsigned mask)
Definition: Type.h:288
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack)
LangAS getAddressSpace() const
Definition: Type.h:352
void AddInnermostTypeInfo(const DeclaratorChunk &TI)
Add a new innermost chunk to this declarator.
Definition: DeclSpec.h:2170
const Type * getClass() const
Definition: Type.h:2790
void expandBuiltinRange(SourceRange Range)
Definition: TypeLoc.h:557
TSS getTypeSpecSign() const
Definition: DeclSpec.h:482
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1196
CanQualType LongDoubleTy
Definition: ASTContext.h:1028
Values of this type can never be null.
QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope...
Definition: SemaExpr.cpp:15490
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
Wrapper for source info for ObjC interfaces.
Definition: TypeLoc.h:1049
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6072
QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc)
Build an ext-vector type.
Definition: SemaType.cpp:2349
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:111
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2064
#define MS_TYPE_ATTRS_CASELIST
Definition: SemaType.cpp:137
void setUnaligned(bool flag)
Definition: Type.h:298
static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType)
A function type attribute was written on the declarator.
Definition: SemaType.cpp:620
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:3844
static FileID getNullabilityCompletenessCheckFileID(Sema &S, SourceLocation loc)
Definition: SemaType.cpp:3690
Preprocessor & PP
Definition: Sema.h:323
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1478
const LangOptions & getLangOpts() const
Definition: Sema.h:1231
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:548
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:167
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:1869
void addCVRUQualifiers(unsigned mask)
Definition: Type.h:292
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1697
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1350
void addAtEnd(ParsedAttr *newAttr)
Definition: ParsedAttr.h:770
static void transferARCOwnershipToDeclSpec(Sema &S, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership)
Definition: SemaType.cpp:5179
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5...
Definition: Sema.h:7549
Represents an ObjC class declaration.
Definition: DeclObjC.h:1172
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs, typeofs, etc., as well as any qualifiers.
Definition: Type.cpp:419
void copy(ElaboratedTypeLoc Loc)
Definition: TypeLoc.h:1980
SourceLocation getIncludeLoc() const
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:507
static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
handleObjCGCTypeAttr - Process the attribute((objc_gc)) type attribute on the specified type...
Definition: SemaType.cpp:6140
is ARM Neon polynomial vector
Definition: Type.h:3187
static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind)
Map a nullability attribute kind to a nullability kind.
Definition: SemaType.cpp:6406
SmallVector< TemplateTypeParmDecl *, 4 > AutoTemplateParams
Store the list of the auto parameters for a generic lambda.
Definition: ScopeInfo.h:825
void removeVolatile()
Definition: Type.h:265
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:143
Qualifiers getTypeQuals() const
Definition: Type.h:4015
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2127
CanQualType UnsignedCharTy
Definition: ASTContext.h:1026
void setAttrNameLoc(SourceLocation loc)
Definition: TypeLoc.h:1669
const LangOptions & LangOpts
Definition: Sema.h:322
static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy)
Definition: SemaType.cpp:1870
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:1873
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
uint8_t PointerKind
Which kind of pointer declarator we saw.
Definition: Sema.h:241
This object can be modified without requiring retains or releases.
Definition: Type.h:162
static const TST TST_float
Definition: DeclSpec.h:282
CXXRecordDecl * getMostRecentNonInjectedDecl()
Definition: DeclCXX.h:754
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void setInvalid(bool b=true) const
Definition: ParsedAttr.h:423
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
Definition: SemaType.cpp:5709
bool isExpressionContext() const
Determine whether this declaration appears in a context where an expression could appear...
Definition: DeclSpec.h:2331
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:3571
void * getOpaqueData() const
Get the pointer where source information is stored.
Definition: TypeLoc.h:140
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1772
bool isHalfType() const
Definition: Type.h:6550
QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a block pointer type.
Definition: SemaType.cpp:2577
TypeResult actOnObjCTypeArgsAndProtocolQualifiers(Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef< ParsedType > TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef< Decl *> Protocols, ArrayRef< SourceLocation > ProtocolLocs, SourceLocation ProtocolRAngleLoc)
Build a specialized and/or protocol-qualified Objective-C type.
Definition: SemaType.cpp:1106
llvm::StringRef getParameterABISpelling(ParameterABI kind)
bool hasAttr() const
Definition: DeclBase.h:531
bool hasUserProvidedDefaultConstructor() const
Whether this class has a user-provided default constructor per C++11.
Definition: DeclCXX.h:989
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:1861
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
QualType getCorrespondingSaturatedType(QualType Ty) const
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:278
static const TSW TSW_long
Definition: DeclSpec.h:255
enum clang::DeclaratorChunk::@215 Kind
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl *> DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:152
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1043
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1613
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:552
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3687
void setParensRange(SourceRange Range)
Definition: TypeLoc.h:1897
Holds a QualType and a TypeSourceInfo* that came out of a declarator parsing.
Definition: LocInfoType.h:29
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl *> protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
static void checkExtParameterInfos(Sema &S, ArrayRef< QualType > paramTypes, const FunctionProtoType::ExtProtoInfo &EPI, llvm::function_ref< SourceLocation(unsigned)> getParamLoc)
Check the extended parameter information.
Definition: SemaType.cpp:2424
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition: DeclSpec.h:1316
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1288
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: Type.h:2818
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1541
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6147
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/unaligned/atomic.
Definition: DeclSpec.h:1168
void addObjCLifetime(ObjCLifetime type)
Definition: Type.h:333
static QualType ConvertDeclSpecToType(TypeProcessingState &state)
Convert the specified declspec to the appropriate type object.
Definition: SemaType.cpp:1230
bool isEnabled(llvm::StringRef Ext) const
Definition: OpenCLOptions.h:39
void setSizeExpr(Expr *Size)
Definition: TypeLoc.h:1489
A conversion function name, e.g., operator int.
SourceRange getRange() const
Definition: DeclSpec.h:68
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
TST getTypeSpecType() const
Definition: DeclSpec.h:483
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
Scope * getCurScope() const
Retrieve the parser&#39;s current scope.
Definition: Sema.h:10729
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3101
unsigned hasStatic
True if this dimension included the &#39;static&#39; keyword.
Definition: DeclSpec.h:1204
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:190
Type source information for an attributed type.
Definition: TypeLoc.h:849
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:637
This represents one expression.
Definition: Expr.h:106
QualType getPointeeType() const
Definition: Type.h:2694
SourceLocation End
int Id
Definition: ASTDiff.cpp:191
Kind getKind() const
Definition: ParsedAttr.h:443
Declaration of a template type parameter.
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition: Type.cpp:3883
unsigned VolatileQualLoc
The location of the volatile-qualifier, if any.
Definition: DeclSpec.h:1174
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition: TypeLoc.h:320
This file defines the classes used to store parsed information about declaration-specifiers and decla...
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6811
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:5050
TypeResult ActOnTypeName(Scope *S, Declarator &D)
Definition: SemaType.cpp:5716
bool isObjCRetainableType() const
Definition: Type.cpp:3921
QualType getTypeOfExprType(Expr *e) const
GCC extension.
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:87
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2706
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:6193
QualType getParenType(QualType NamedType) const
static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
Process the OpenCL-like ext_vector_type attribute when it occurs on a type.
Definition: SemaType.cpp:7007
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
std::string getAsString() const
Retrieve the human-readable string for this name.
TypeResult actOnObjCProtocolQualifierType(SourceLocation lAngleLoc, ArrayRef< Decl *> protocols, ArrayRef< SourceLocation > protocolLocs, SourceLocation rAngleLoc)
Build a an Objective-C protocol-qualified &#39;id&#39; type where no base type was specified.
Definition: SemaType.cpp:1067
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:550
QualType BuildAtomicType(QualType T, SourceLocation Loc)
Definition: SemaType.cpp:8187
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:556
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
Defines the clang::Preprocessor interface.
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold=true)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:14233
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
void completeExprArrayBound(Expr *E)
Definition: SemaType.cpp:7502
ObjCLifetime getObjCLifetime() const
Definition: Type.h:326
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:259
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
bool isConstexprSpecified() const
Definition: DeclSpec.h:727
bool hasEllipsis() const
Definition: DeclSpec.h:2454
CanQualType ShortTy
Definition: ASTContext.h:1025
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
internal::Matcher< T > id(StringRef ID, const internal::BindableMatcher< T > &InnerMatcher)
If the provided matcher matches a node, binds the node to ID.
Definition: ASTMatchers.h:137
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:108
Represents a C++ template name within the type system.
Definition: TemplateName.h:179
static const TST TST_decimal64
Definition: DeclSpec.h:290
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7598
Defines the clang::TypeLoc interface and its subclasses.
static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T)
Produce an appropriate diagnostic for a declarator with top-level parentheses.
Definition: SemaType.cpp:3253
A namespace alias, stored as a NamespaceAliasDecl*.
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1016
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.h:2180
static QualType getDecltypeForExpr(Sema &S, Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
Definition: SemaType.cpp:8071
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1027
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:577
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1062
TypeDiagSelector
Definition: SemaType.cpp:42
QualType getType() const
Definition: Expr.h:128
bool isFunctionOrMethod() const
Definition: DeclBase.h:1800
static Optional< NullabilityKind > stripOuterNullability(QualType &T)
Strip off the top-level nullability annotation on the given type, if it&#39;s there.
Definition: Type.cpp:3833
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
bool LValueRef
True if this is an lvalue reference, false if it&#39;s an rvalue reference.
Definition: DeclSpec.h:1193
SourceLocation Loc
Loc - The place where this type was defined.
Definition: DeclSpec.h:1154
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
Qualifiers Quals
The local qualifiers.
Definition: Type.h:582
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1752
ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for protocol qualifiers are stored aft...
Definition: TypeLoc.h:746
static const TST TST_int
Definition: DeclSpec.h:279
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition: TypeLoc.h:1007
void setEllipsisLoc(SourceLocation EL)
Definition: DeclSpec.h:2456
static QualType inferARCLifetimeForPointee(Sema &S, QualType type, SourceLocation loc, bool isReference)
Given that we&#39;re building a pointer or reference to the given.
Definition: SemaType.cpp:1819
bool isInvalid() const
Definition: Ownership.h:170
SourceLocation getEnd() const
Compare two source locations.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1380
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:7948
static const TST TST_half
Definition: DeclSpec.h:281
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2720
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type...
bool isFriendSpecified() const
Definition: DeclSpec.h:721
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:4709
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:95
static void moveAttrFromListToList(ParsedAttr &attr, ParsedAttributesView &fromList, ParsedAttributesView &toList)
Definition: SemaType.cpp:310
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1396
static QualType Desugar(ASTContext &Context, QualType QT, bool &ShouldAKA)
The result type of a method or function.
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:152
SourceLocation getCommaLoc() const
Definition: DeclSpec.h:2451
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2011
bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
Definition: SemaType.cpp:7558
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:703
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
static const TSW TSW_short
Definition: DeclSpec.h:254
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:281
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:170
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:236
SourceLocation PointerLoc
The first pointer declarator (of any pointer kind) in the file that does not have a corresponding nul...
Definition: Sema.h:234
CanQualType SignedCharTy
Definition: ASTContext.h:1025
bool isFirstDeclarator() const
Definition: DeclSpec.h:2450
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:5278
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:6105
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType)
TypeAndRange * Exceptions
Pointer to a new[]&#39;d array of TypeAndRange objects that contain the types in the function&#39;s dynamic e...
Definition: DeclSpec.h:1325
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition: DeclSpec.h:1416
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6131
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent) const
C++11 deduced auto type.
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:6080
unsigned getSemanticSpelling() const
If the parsed attribute has a semantic equivalent, and it would have a semantic Spelling enumeration ...
Definition: ParsedAttr.cpp:246
RecordDecl * getDecl() const
Definition: Type.h:4380
static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, QualType Result)
Return true if this is omitted block return type.
Definition: SemaType.cpp:772
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1240
static const TST TST_char32
Definition: DeclSpec.h:278
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:76
QualType getPackExpansionType(QualType Pattern, Optional< unsigned > NumExpansions)
static const TST TST_fract
Definition: DeclSpec.h:286
void setTypeofLoc(SourceLocation Loc)
Definition: TypeLoc.h:1780
static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
handleObjCOwnershipTypeAttr - Process an objc_ownership attribute on the specified type...
Definition: SemaType.cpp:5951
bool SawTypeNullability
Whether we saw any type nullability annotations in the given file.
Definition: Sema.h:244
static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, Declarator &D, unsigned FunctionChunkIndex)
Definition: SemaType.cpp:2762
A parameter attribute which changes the argument-passing ABI rule for the parameter.
Definition: Attr.h:184
Wrapper for source info for arrays.
Definition: TypeLoc.h:1460
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
CanQualType OverloadTy
Definition: ASTContext.h:1045
There is no lifetime qualification on this type.
Definition: Type.h:158
Information about a FileID, basically just the logical file that it represents and include stack info...
is AltiVec &#39;vector Pixel&#39;
Definition: Type.h:3178
#define false
Definition: stdbool.h:33
static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type, ArrayRef< TypeSourceInfo *> typeArgs, SourceRange typeArgsRange, bool failOnError=false)
Apply Objective-C type arguments to the given type.
Definition: SemaType.cpp:802
The "struct" keyword.
Definition: Type.h:5033
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:169
Kind
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:6365
not a target-specific vector type
Definition: Type.h:3172
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:157
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
The attribute is in the decl-specifier-seq.
Definition: SemaType.cpp:320
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3899
SCS getStorageClassSpec() const
Definition: DeclSpec.h:451
void setKNRPromoted(bool promoted)
Definition: Decl.h:1627
ASTContext & getASTContext() const
Definition: Sema.h:1238
SourceLocation getRParenLoc() const
Definition: DeclSpec.h:1399
static bool isPermittedNeonBaseType(QualType &Ty, VectorType::VectorKind VecKind, Sema &S)
Definition: SemaType.cpp:7041
static const TST TST_float16
Definition: DeclSpec.h:284
static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
Process an individual function attribute.
Definition: SemaType.cpp:6732
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:3774
static void distributeObjCPointerTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType type)
Given that an objc_gc attribute was written somewhere on a declaration other than on the declarator i...
Definition: SemaType.cpp:427
Encodes a location in the source.
bool isTypeSpecOwned() const
Definition: DeclSpec.h:487
Sugar for parentheses used when specifying types.
Definition: Type.h:2507
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
QualType getReturnType() const
Definition: Type.h:3613
static const TST TST_auto_type
Definition: DeclSpec.h:304
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4396
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
bool CheckDistantExceptionSpec(QualType T)
CheckDistantExceptionSpec - Check if the given type is a pointer or pointer to member to a function w...
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6188
ReferenceTypeInfo Ref
Definition: DeclSpec.h:1518
static void distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType)
Distribute an objc_gc type attribute that was written on the declarator.
Definition: SemaType.cpp:483
PointerDeclaratorKind
Describes the kind of a pointer a declarator describes.
Definition: SemaType.cpp:3506
CanQualType Int128Ty
Definition: ASTContext.h:1025
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5738
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition: DeclSpec.h:2466
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2095
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword...
Definition: Diagnostic.h:1290
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:1873
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2287
Syntax
The style used to specify an attribute.
Definition: ParsedAttr.h:140
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: Type.h:3394
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3064
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, Qualifiers::ObjCLifetime ownership, unsigned chunkIndex)
Definition: SemaType.cpp:5190
static void distributeFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType type)
A function type attribute was written somewhere in a declaration other than on the declarator itself ...
Definition: SemaType.cpp:544
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:376
FunctionTypeInfo Fun
Definition: DeclSpec.h:1520
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:509
static const TST TST_union
Definition: DeclSpec.h:293
CallingConv getCC() const
Definition: Type.h:3525
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:117
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:765
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
static const TSS TSS_signed
Definition: DeclSpec.h:267
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:688
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size...
RecordDecl * CFError
The struct behind the CFErrorRef pointer.
Definition: Sema.h:10716
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:7635
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
No ref-qualifier was provided.
Definition: Type.h:1360
CanQualType FloatTy
Definition: ASTContext.h:1028
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3860
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1522
SimplePointerKind
A simple notion of pointer kinds, which matches up with the various pointer declarators.
Definition: SemaType.cpp:3455
QualType getEquivalentType() const
Definition: Type.h:4451
static CallingConv getCCForDeclaratorChunk(Sema &S, Declarator &D, const ParsedAttributesView &AttrList, const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex)
Helper for figuring out the default CC for a function declarator type.
Definition: SemaType.cpp:3372
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:2312
CanQualType VoidTy
Definition: ASTContext.h:1016
void remove(ParsedAttr *ToBeRemoved)
Definition: ParsedAttr.h:775
bool hasRestrict() const
Definition: Type.h:268
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:149
bool isContextSensitiveKeywordAttribute() const
Definition: ParsedAttr.h:418
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition: DeclSpec.h:1477
CanQualType Float16Ty
Definition: ASTContext.h:1041
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1722
bool isObjCObjectPointerType() const
Definition: Type.h:6393
bool isAnyPointerType() const
Definition: Type.h:6300
static bool distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, ParsedAttr &attr, ParsedAttributesView &attrList, QualType &declSpecType)
Try to distribute a function type attribute to the innermost function chunk or type.
Definition: SemaType.cpp:575
bool isArgExpr(unsigned Arg) const
Definition: ParsedAttr.h:456
Decl * getRepAsDecl() const
Definition: DeclSpec.h:496
static bool isBlockPointer(Expr *Arg)
is AltiVec &#39;vector bool ...&#39;
Definition: Type.h:3181
SplitQualType getSplitUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6159
bool isFunctionProtoType() const
Definition: Type.h:1947
static const TST TST_typeofType
Definition: DeclSpec.h:298
is AltiVec vector
Definition: Type.h:3175
void setAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1300
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics...
Definition: SemaExpr.cpp:212
void setLBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1469
AutoTypeKeyword getKeyword() const
Definition: Type.h:4764
TypeClass getTypeClass() const
Definition: Type.h:1811
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:149
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:1975
bool HasRestrict
The type qualifier: restrict. [GNU] C++ extension.
Definition: DeclSpec.h:1191
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:1572
TypeLoc findExplicitQualifierLoc() const
Find a type with the location of an explicit type qualifier.
Definition: TypeLoc.cpp:420
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
Definition: DeclSpec.h:1494
static bool isVectorSizeTooLarge(unsigned NumElements)
Definition: Type.h:3206
static Attr * createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, NullabilityKind NK)
Definition: SemaType.cpp:3904
SourceLocation getPragmaAssumeNonNullLoc() const
The location of the currently-active #pragma clang assume_nonnull begin.
bool isStaticMember()
Returns true if this declares a static member.
Definition: DeclSpec.cpp:397
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1366
Assigning into this object requires a lifetime extension.
Definition: Type.h:175
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:162
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
bool isVLASupported() const
Whether target supports variable-length arrays.
Definition: TargetInfo.h:1150
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
static void recordNullabilitySeen(Sema &S, SourceLocation loc)
Marks that a nullability feature has been used in the file containing loc.
Definition: SemaType.cpp:3839
SourceRange getRange() const
Definition: ParsedAttr.h:380
std::string getAsString() const
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:215
QualType getObjCInstanceType()
Retrieve the Objective-C "instancetype" type, if already known; otherwise, returns a NULL type;...
Definition: ASTContext.h:1730
Represents a pack expansion of types.
Definition: Type.h:5355
static bool checkNullabilityTypeSpecifier(TypeProcessingState &state, QualType &type, ParsedAttr &attr, bool allowOnArrayType)
Applies a nullability type specifier to the given type, if possible.
Definition: SemaType.cpp:6435
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1366
StringRef getName() const
Return the actual identifier string.
static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, ParsedAttr &attr)
Check the application of the Objective-C &#39;__kindof&#39; qualifier to the given type.
Definition: SemaType.cpp:6539
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:937
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1889
CanQualType UnsignedShortTy
Definition: ASTContext.h:1026
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array&#39;s size can require, which limits the maximu...
Definition: Type.cpp:146
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current target.
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2916
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
CanQualType CharTy
Definition: ASTContext.h:1018
TSW getTypeSpecWidth() const
Definition: DeclSpec.h:480
bool isPipeType() const
Definition: Type.h:6477
static const TST TST_decltype_auto
Definition: DeclSpec.h:301
void setClassTInfo(TypeSourceInfo *TI)
Definition: TypeLoc.h:1252
TagTypeKind
The kind of a tag type.
Definition: Type.h:5031
QualType getTypeOfType(QualType t) const
getTypeOfType - Unlike many "get<Type>" functions, we don&#39;t unique TypeOfType nodes.
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1048
Dataflow Directional Tag Classes.
unsigned TypeQuals
The type qualifiers for the array: const/volatile/restrict/__unaligned/_Atomic.
Definition: DeclSpec.h:1201
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition: Sema.h:356
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.cpp:1723
static const TSS TSS_unspecified
Definition: DeclSpec.h:266
SourceLocation getTypeSpecWidthLoc() const
Definition: DeclSpec.h:511
ExtInfo getExtInfo() const
Definition: Type.h:3624
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1262
void setAmpAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1314
bool CheckFunctionReturnType(QualType T, SourceLocation Loc)
Definition: SemaType.cpp:2396
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
Definition: SemaType.cpp:2711
static const TST TST_decltype
Definition: DeclSpec.h:300
static const TST TST_auto
Definition: DeclSpec.h:303
static const TST TST_void
Definition: DeclSpec.h:273
static TypeSourceInfo * GetTypeSourceInfoForDeclarator(TypeProcessingState &State, QualType T, TypeSourceInfo *ReturnTypeInfo)
Create and instantiate a TypeSourceInfo with type source information.
Definition: SemaType.cpp:5642
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with &#39;,...)&#39;, this is true.
Definition: DeclSpec.h:1258
const DeclaratorChunk * getInnermostNonParenChunk() const
Return the innermost (closest to the declarator) chunk of this declarator that is not a parens chunk...
Definition: DeclSpec.h:2205
bool isRecord() const
Definition: DeclBase.h:1827
static bool distributeNullabilityTypeAttr(TypeProcessingState &state, QualType type, ParsedAttr &attr)
Distribute a nullability type attribute that cannot be applied to the type specifier to a pointer...
Definition: SemaType.cpp:6597
static const TST TST_int128
Definition: DeclSpec.h:280
SourceLocation PointerEndLoc
The end location for the first pointer declarator in the file.
Definition: Sema.h:238
QualType getUnderlyingType() const
Definition: Decl.h:2971
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1027
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:118
QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a pointer type.
Definition: SemaType.cpp:1935
static Attr * getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr)
Definition: SemaType.cpp:6678
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition: Type.cpp:261
The name of a declaration.
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:559
SourceLocation getLoc() const
Definition: ParsedAttr.h:379
bool isBooleanType() const
Definition: Type.h:6657
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like &#39;int()&#39;.
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1598
LLVM_READONLY bool isIdentifierBody(unsigned char c, bool AllowDollar=false)
Returns true if this is a body character of a C identifier, which is [a-zA-Z0-9_].
Definition: CharInfo.h:59
SourceLocation getTypeSpecSignLoc() const
Definition: DeclSpec.h:514
ParsedAttr * create(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, ArgsUnion *args, unsigned numArgs, ParsedAttr::Syntax syntax, SourceLocation ellipsisLoc=SourceLocation())
Definition: ParsedAttr.h:679
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5835
QualType BuildReadPipeType(QualType T, SourceLocation Loc)
Build a Read-only Pipe type.
Definition: SemaType.cpp:2032
Represents an enum.
Definition: Decl.h:3326
#define FUNCTION_TYPE_ATTRS_CASELIST
Definition: SemaType.cpp:128
static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal)
Check whether the specified array size makes the array type a VLA.
Definition: SemaType.cpp:2050
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2756
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
bool hasObjCLifetime() const
Definition: Type.h:325
static void processTypeAttrs(TypeProcessingState &state, QualType &type, TypeAttrLocation TAL, ParsedAttributesView &attrs)
Definition: SemaType.cpp:7304
SplitQualType getSingleStepDesugaredType() const
Definition: Type.h:6065
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:866
IdentifierInfo * getName() const
Definition: ParsedAttr.h:378
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration...
Definition: DeclCXX.h:2144
static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
Handle OpenCL Access Qualifier Attribute.
Definition: SemaType.cpp:7143
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:1083
A type that was preceded by the &#39;template&#39; keyword, stored as a Type*.
static const TST TST_unspecified
Definition: DeclSpec.h:272
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:508
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1081
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 &#39;auto&#39; typ...
Definition: Type.h:6663
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1153
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition: DeclSpec.cpp:422
unsigned getNumParams() const
Definition: TypeLoc.h:1402
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2022
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr)
Represents a pointer to an Objective C object.
Definition: Type.h:5794
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:151
Pointer to a block type.
Definition: Type.h:2639
IdentifierInfo * getNSErrorIdent()
Retrieve the identifier "NSError".
Definition: SemaType.cpp:3484
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S, VectorType::VectorKind VecKind)
HandleNeonVectorTypeAttr - The "neon_vector_type" and "neon_polyvector_type" attributes are used to c...
Definition: SemaType.cpp:7096
bool isIncompleteArrayType() const
Definition: Type.h:6353
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4370
static const TST TST_decimal128
Definition: DeclSpec.h:291
static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType)
A function type attribute was written in the decl spec.
Definition: SemaType.cpp:594
CanQualType UnknownAnyTy
Definition: ASTContext.h:1045
bool empty() const
Definition: Type.h:414
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6.7.5p3.
Definition: Type.cpp:2021
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:547
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1253
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6578
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:156
#define OBJC_POINTER_TYPE_ATTRS_CASELIST
Definition: SemaType.cpp:105
CanQualType UnsignedLongTy
Definition: ASTContext.h:1026
static bool isFunctionOrMethod(const Decl *D)
isFunctionOrMethod - Return true if the given decl has function type (function or function-typed vari...
T * getAttr() const
Definition: DeclBase.h:527
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition: DeclSpec.h:2192
CanQualType DependentTy
Definition: ASTContext.h:1045
bool isImageType() const
Definition: Type.h:6470
Kind getAttrKind() const
Definition: Type.h:4446
bool isAtomicType() const
Definition: Type.h:6406
CanQualType WCharTy
Definition: ASTContext.h:1019
bool isFunctionType() const
Definition: Type.h:6292
The maximum supported address space number.
Definition: Type.h:181
static const TST TST_typename
Definition: DeclSpec.h:297
QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:8138
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2673
QualType getAutoDeductType() const
C++11 deduction pattern for &#39;auto&#39; type.
void copy(TemplateSpecializationTypeLoc Loc)
Definition: TypeLoc.h:1605
Wraps an ObjCPointerType with source location information.
Definition: TypeLoc.h:1270
unsigned AtomicQualLoc
The location of the _Atomic-qualifier, if any.
Definition: DeclSpec.h:1180
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:518
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:92
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition: DeclSpec.h:1458
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3696
The "class" keyword.
Definition: Type.h:5042
SourceLocation getTypeSpecTypeNameLoc() const
Definition: DeclSpec.h:519
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:510
CXXScopeSpec & getTypeSpecScope()
Definition: DeclSpec.h:504
BlockPointerTypeInfo Cls
Definition: DeclSpec.h:1521
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2591
SourceRange getExceptionSpecRange() const
Definition: DeclSpec.h:1411
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:1866
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2070
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, DeclaratorChunk &DeclType, QualType RT)
Produce an appropriate diagnostic for an ambiguity between a function declarator and a C++ direct-ini...
Definition: SemaType.cpp:3155
bool isObjCObjectType() const
Definition: Type.h:6397
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2031
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, std::unique_ptr< CorrectionCandidateCallback > CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2080
Describes whether we&#39;ve seen any nullability information for the given file.
Definition: Sema.h:231
CanQualType Char8Ty
Definition: ASTContext.h:1022
UnqualTypeLoc getUnqualifiedLoc() const
Definition: TypeLoc.h:275
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2133
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2253
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:238
PointerWrappingDeclaratorKind
Describes a declarator chunk wrapping a pointer that marks inference as unexpected.
Definition: SemaType.cpp:3524
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2442
Reading or writing from this object requires a barrier call.
Definition: Type.h:172
bool isInvalid() const
Definition: ParsedAttr.h:422
Context-sensitive version of a keyword attribute.
Definition: ParsedAttr.h:165
unsigned AutoTemplateParameterDepth
If this is a generic lambda, use this as the depth of each &#39;auto&#39; parameter, during initial AST const...
Definition: ScopeInfo.h:818
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:4425
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2220
unsigned TypeQuals
For now, sema will catch these as invalid.
Definition: DeclSpec.h:1486
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1009
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2682
CallingConv getCallConv() const
Definition: Type.h:3623
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6152
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:549
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:2455
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type...
bool isVoidType() const
Definition: Type.h:6544
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition: DeclSpec.h:1212
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6099
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1409
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:608
CanQualType Char16Ty
Definition: ASTContext.h:1023
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition: Sema.h:350
static const TST TST_float128
Definition: DeclSpec.h:287
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1101
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1854
static const TST TST_bool
Definition: DeclSpec.h:288
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:336
bool isSamplerT() const
Definition: Type.h:6450
The "enum" keyword.
Definition: Type.h:5045
bool isRValue() const
Definition: Expr.h:250
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:637
static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD)
Locks in the inheritance model for the given class and all of its bases.
Definition: SemaType.cpp:7716
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:61
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:129
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2391
void addAttr(Attr *A)
Definition: DeclBase.cpp:840
IdentifierInfo * getNullabilityKeyword(NullabilityKind nullability)
Retrieve the keyword associated.
Definition: SemaType.cpp:3463
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
SourceManager & getSourceManager() const
Definition: Sema.h:1236
A template-id, e.g., f<int>.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:276
ParsedType getRepAsType() const
Definition: DeclSpec.h:492
Defines the clang::TargetInfo interface.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
A SourceLocation and its associated SourceManager.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:3480
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:551
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement)
Completely replace the auto in TypeWithAuto by Replacement.
static Qualifiers fromCVRMask(unsigned CVR)
Definition: Type.h:234
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
static const TSW TSW_longlong
Definition: DeclSpec.h:256
__DEVICE__ int max(int __a, int __b)
CanQualType IntTy
Definition: ASTContext.h:1025
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
static OpaquePtr make(QualType P)
Definition: Ownership.h:61
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2079
static void emitNullabilityConsistencyWarning(Sema &S, SimplePointerKind PointerKind, SourceLocation PointerLoc, SourceLocation PointerEndLoc)
Definition: SemaType.cpp:3764
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1041
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition: DeclSpec.h:1445
Represents an extended address space qualifier where the input address space value is dependent...
Definition: Type.h:3086
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:819
void copy(TypeLoc other)
Copies the other type loc into this one.
Definition: TypeLoc.cpp:166
static const TST TST_atomic
Definition: DeclSpec.h:306
bool isPointerType() const
Definition: Type.h:6296
SourceManager & SourceMgr
Definition: Sema.h:327
bool isEmpty() const
isEmpty - Return true if this declaration specifier is completely empty: no tokens were parsed in the...
Definition: DeclSpec.h:622
void addAddressSpace(LangAS space)
Definition: Type.h:378
static const TST TST_struct
Definition: DeclSpec.h:294
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:66
class clang::Sema::DelayedDiagnostics DelayedDiagnostics
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:196
DeclaratorContext getContext() const
Definition: DeclSpec.h:1879
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:2822
QualType getType() const
Definition: Decl.h:648
Wrapper for source info for builtin types.
Definition: TypeLoc.h:544
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:114
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1105
bool isArgIdent(unsigned Arg) const
Definition: ParsedAttr.h:464
A trivial tuple used to represent a source range.
bool isModulePrivate() const
Whether this declaration was marked as being private to the module in which it was defined...
Definition: DeclBase.h:596
static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
Definition: SemaType.cpp:6333
ASTContext & Context
Definition: Sema.h:324
This represents a decl that may have a name.
Definition: Decl.h:249
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1023
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
void copy(DependentNameTypeLoc Loc)
Definition: TypeLoc.h:2033
Expr * getRepAsExpr() const
Definition: DeclSpec.h:500
QualifiedFunctionKind
Kinds of declarator that cannot contain a qualified function type.
Definition: SemaType.cpp:1904
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:76
bool hasExplicitCallingConv(QualType &T)
Definition: SemaType.cpp:6913
CanQualType BoolTy
Definition: ASTContext.h:1017
__ptr16, alignas(...), etc.
Definition: ParsedAttr.h:157
No keyword precedes the qualified type name.
Definition: Type.h:5071
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type...
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:1550
static void HandleAddressSpaceTypeAttribute(QualType &Type, const ParsedAttr &Attr, TypeProcessingState &State)
HandleAddressSpaceTypeAttribute - Process an address_space attribute on the specified type...
Definition: SemaType.cpp:5826
TypeAttrLocation
The location of a type attribute.
Definition: SemaType.cpp:318
CanQualType DoubleTy
Definition: ASTContext.h:1028
static TypeSourceInfo * GetFullTypeForDeclarator(TypeProcessingState &state, QualType declSpecType, TypeSourceInfo *TInfo)
Definition: SemaType.cpp:3923
bool isAggregate() const
Determine whether this class is an aggregate (C++ [dcl.init.aggr]), which is a class with no user-dec...
Definition: DeclCXX.h:1284
attr::Kind getKind() const
Definition: Attr.h:87
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition: DeclSpec.h:2471
llvm::StringRef getNullabilitySpelling(NullabilityKind kind, bool isContextSensitive=false)
Retrieve the spelling of the given nullability kind.
The global specifier &#39;::&#39;. There is no stored value.
bool isPrototypeContext() const
Definition: DeclSpec.h:1881
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
void setType(QualType newType)
Definition: Decl.h:649
Wrapper for source info for pointers.
Definition: TypeLoc.h:1202
SourceLocation getBegin() const
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type)
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1215
unsigned size() const
Determine the number of type parameters in this list.
Definition: DeclObjC.h:677
An implicit &#39;self&#39; parameter.
base_class_range vbases()
Definition: DeclCXX.h:840
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3773
A deduction-guide name (a template-name)
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
IdentifierLoc * getArgAsIdent(unsigned Arg) const
Definition: ParsedAttr.h:468
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3466
ParamInfo * Params
Params - This is a pointer to a new[]&#39;d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1313
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1943
Attr - This represents one attribute.
Definition: Attr.h:44
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:762
SourceLocation getLocation() const
Definition: DeclBase.h:418
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type...
Definition: Type.h:1861
SourceRange getTypeofParensRange() const
Definition: DeclSpec.h:524
QualType getPointeeType() const
Definition: Type.h:2776
TypeSourceInfo * GetTypeForDeclarator(Declarator &D, Scope *S)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5165
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:98
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3189
This parameter (which must have pointer type) is a Swift indirect result parameter.
QualType BuildTypeofExprType(Expr *E, SourceLocation Loc)
Definition: SemaType.cpp:8054
void setUnderlyingTInfo(TypeSourceInfo *TI) const
Definition: TypeLoc.h:1845
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type...
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2560
CanQualType UnsignedIntTy
Definition: ASTContext.h:1026
QualType getIncompleteArrayType(QualType EltTy, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1058
unsigned isAmbiguous
Can this declaration be a constructor-style initializer?
Definition: DeclSpec.h:1261