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 "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.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"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/DelayedDiagnostic.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/ScopeInfo.h"
33 #include "clang/Sema/Template.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/Support/ErrorHandling.h"
37 
38 using namespace clang;
39 
40 enum TypeDiagSelector {
41   TDS_Function,
42   TDS_Pointer,
43   TDS_ObjCObjOrBlock
44 };
45 
46 /// isOmittedBlockReturnType - Return true if this declarator is missing a
47 /// return type because this is a omitted return type on a block literal.
48 static bool isOmittedBlockReturnType(const Declarator &D) {
49   if (D.getContext() != Declarator::BlockLiteralContext ||
50       D.getDeclSpec().hasTypeSpecifier())
51     return false;
52 
53   if (D.getNumTypeObjects() == 0)
54     return true;   // ^{ ... }
55 
56   if (D.getNumTypeObjects() == 1 &&
57       D.getTypeObject(0).Kind == DeclaratorChunk::Function)
58     return true;   // ^(int X, float Y) { ... }
59 
60   return false;
61 }
62 
63 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
64 /// doesn't apply to the given type.
65 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
66                                      QualType type) {
67   TypeDiagSelector WhichType;
68   bool useExpansionLoc = true;
69   switch (attr.getKind()) {
70   case AttributeList::AT_ObjCGC:        WhichType = TDS_Pointer; break;
71   case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
72   default:
73     // Assume everything else was a function attribute.
74     WhichType = TDS_Function;
75     useExpansionLoc = false;
76     break;
77   }
78 
79   SourceLocation loc = attr.getLoc();
80   StringRef name = attr.getName()->getName();
81 
82   // The GC attributes are usually written with macros;  special-case them.
83   IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
84                                           : nullptr;
85   if (useExpansionLoc && loc.isMacroID() && II) {
86     if (II->isStr("strong")) {
87       if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
88     } else if (II->isStr("weak")) {
89       if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
90     }
91   }
92 
93   S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
94     << type;
95 }
96 
97 // objc_gc applies to Objective-C pointers or, otherwise, to the
98 // smallest available pointer type (i.e. 'void*' in 'void**').
99 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
100     case AttributeList::AT_ObjCGC: \
101     case AttributeList::AT_ObjCOwnership
102 
103 // Function type attributes.
104 #define FUNCTION_TYPE_ATTRS_CASELIST \
105     case AttributeList::AT_NoReturn: \
106     case AttributeList::AT_CDecl: \
107     case AttributeList::AT_FastCall: \
108     case AttributeList::AT_StdCall: \
109     case AttributeList::AT_ThisCall: \
110     case AttributeList::AT_Pascal: \
111     case AttributeList::AT_VectorCall: \
112     case AttributeList::AT_MSABI: \
113     case AttributeList::AT_SysVABI: \
114     case AttributeList::AT_Regparm: \
115     case AttributeList::AT_Pcs: \
116     case AttributeList::AT_IntelOclBicc
117 
118 // Microsoft-specific type qualifiers.
119 #define MS_TYPE_ATTRS_CASELIST  \
120     case AttributeList::AT_Ptr32: \
121     case AttributeList::AT_Ptr64: \
122     case AttributeList::AT_SPtr: \
123     case AttributeList::AT_UPtr
124 
125 // Nullability qualifiers.
126 #define NULLABILITY_TYPE_ATTRS_CASELIST         \
127     case AttributeList::AT_TypeNonNull:         \
128     case AttributeList::AT_TypeNullable:        \
129     case AttributeList::AT_TypeNullUnspecified
130 
131 namespace {
132   /// An object which stores processing state for the entire
133   /// GetTypeForDeclarator process.
134   class TypeProcessingState {
135     Sema &sema;
136 
137     /// The declarator being processed.
138     Declarator &declarator;
139 
140     /// The index of the declarator chunk we're currently processing.
141     /// May be the total number of valid chunks, indicating the
142     /// DeclSpec.
143     unsigned chunkIndex;
144 
145     /// Whether there are non-trivial modifications to the decl spec.
146     bool trivial;
147 
148     /// Whether we saved the attributes in the decl spec.
149     bool hasSavedAttrs;
150 
151     /// The original set of attributes on the DeclSpec.
152     SmallVector<AttributeList*, 2> savedAttrs;
153 
154     /// A list of attributes to diagnose the uselessness of when the
155     /// processing is complete.
156     SmallVector<AttributeList*, 2> ignoredTypeAttrs;
157 
158   public:
159     TypeProcessingState(Sema &sema, Declarator &declarator)
160       : sema(sema), declarator(declarator),
161         chunkIndex(declarator.getNumTypeObjects()),
162         trivial(true), hasSavedAttrs(false) {}
163 
164     Sema &getSema() const {
165       return sema;
166     }
167 
168     Declarator &getDeclarator() const {
169       return declarator;
170     }
171 
172     bool isProcessingDeclSpec() const {
173       return chunkIndex == declarator.getNumTypeObjects();
174     }
175 
176     unsigned getCurrentChunkIndex() const {
177       return chunkIndex;
178     }
179 
180     void setCurrentChunkIndex(unsigned idx) {
181       assert(idx <= declarator.getNumTypeObjects());
182       chunkIndex = idx;
183     }
184 
185     AttributeList *&getCurrentAttrListRef() const {
186       if (isProcessingDeclSpec())
187         return getMutableDeclSpec().getAttributes().getListRef();
188       return declarator.getTypeObject(chunkIndex).getAttrListRef();
189     }
190 
191     /// Save the current set of attributes on the DeclSpec.
192     void saveDeclSpecAttrs() {
193       // Don't try to save them multiple times.
194       if (hasSavedAttrs) return;
195 
196       DeclSpec &spec = getMutableDeclSpec();
197       for (AttributeList *attr = spec.getAttributes().getList(); attr;
198              attr = attr->getNext())
199         savedAttrs.push_back(attr);
200       trivial &= savedAttrs.empty();
201       hasSavedAttrs = true;
202     }
203 
204     /// Record that we had nowhere to put the given type attribute.
205     /// We will diagnose such attributes later.
206     void addIgnoredTypeAttr(AttributeList &attr) {
207       ignoredTypeAttrs.push_back(&attr);
208     }
209 
210     /// Diagnose all the ignored type attributes, given that the
211     /// declarator worked out to the given type.
212     void diagnoseIgnoredTypeAttrs(QualType type) const {
213       for (auto *Attr : ignoredTypeAttrs)
214         diagnoseBadTypeAttribute(getSema(), *Attr, type);
215     }
216 
217     ~TypeProcessingState() {
218       if (trivial) return;
219 
220       restoreDeclSpecAttrs();
221     }
222 
223   private:
224     DeclSpec &getMutableDeclSpec() const {
225       return const_cast<DeclSpec&>(declarator.getDeclSpec());
226     }
227 
228     void restoreDeclSpecAttrs() {
229       assert(hasSavedAttrs);
230 
231       if (savedAttrs.empty()) {
232         getMutableDeclSpec().getAttributes().set(nullptr);
233         return;
234       }
235 
236       getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
237       for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
238         savedAttrs[i]->setNext(savedAttrs[i+1]);
239       savedAttrs.back()->setNext(nullptr);
240     }
241   };
242 } // end anonymous namespace
243 
244 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
245   attr.setNext(head);
246   head = &attr;
247 }
248 
249 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
250   if (head == &attr) {
251     head = attr.getNext();
252     return;
253   }
254 
255   AttributeList *cur = head;
256   while (true) {
257     assert(cur && cur->getNext() && "ran out of attrs?");
258     if (cur->getNext() == &attr) {
259       cur->setNext(attr.getNext());
260       return;
261     }
262     cur = cur->getNext();
263   }
264 }
265 
266 static void moveAttrFromListToList(AttributeList &attr,
267                                    AttributeList *&fromList,
268                                    AttributeList *&toList) {
269   spliceAttrOutOfList(attr, fromList);
270   spliceAttrIntoList(attr, toList);
271 }
272 
273 /// The location of a type attribute.
274 enum TypeAttrLocation {
275   /// The attribute is in the decl-specifier-seq.
276   TAL_DeclSpec,
277   /// The attribute is part of a DeclaratorChunk.
278   TAL_DeclChunk,
279   /// The attribute is immediately after the declaration's name.
280   TAL_DeclName
281 };
282 
283 static void processTypeAttrs(TypeProcessingState &state,
284                              QualType &type, TypeAttrLocation TAL,
285                              AttributeList *attrs);
286 
287 static bool handleFunctionTypeAttr(TypeProcessingState &state,
288                                    AttributeList &attr,
289                                    QualType &type);
290 
291 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
292                                              AttributeList &attr,
293                                              QualType &type);
294 
295 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
296                                  AttributeList &attr, QualType &type);
297 
298 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
299                                        AttributeList &attr, QualType &type);
300 
301 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
302                                       AttributeList &attr, QualType &type) {
303   if (attr.getKind() == AttributeList::AT_ObjCGC)
304     return handleObjCGCTypeAttr(state, attr, type);
305   assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
306   return handleObjCOwnershipTypeAttr(state, attr, type);
307 }
308 
309 /// Given the index of a declarator chunk, check whether that chunk
310 /// directly specifies the return type of a function and, if so, find
311 /// an appropriate place for it.
312 ///
313 /// \param i - a notional index which the search will start
314 ///   immediately inside
315 ///
316 /// \param onlyBlockPointers Whether we should only look into block
317 /// pointer types (vs. all pointer types).
318 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
319                                                 unsigned i,
320                                                 bool onlyBlockPointers) {
321   assert(i <= declarator.getNumTypeObjects());
322 
323   DeclaratorChunk *result = nullptr;
324 
325   // First, look inwards past parens for a function declarator.
326   for (; i != 0; --i) {
327     DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
328     switch (fnChunk.Kind) {
329     case DeclaratorChunk::Paren:
330       continue;
331 
332     // If we find anything except a function, bail out.
333     case DeclaratorChunk::Pointer:
334     case DeclaratorChunk::BlockPointer:
335     case DeclaratorChunk::Array:
336     case DeclaratorChunk::Reference:
337     case DeclaratorChunk::MemberPointer:
338     case DeclaratorChunk::Pipe:
339       return result;
340 
341     // If we do find a function declarator, scan inwards from that,
342     // looking for a (block-)pointer declarator.
343     case DeclaratorChunk::Function:
344       for (--i; i != 0; --i) {
345         DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
346         switch (ptrChunk.Kind) {
347         case DeclaratorChunk::Paren:
348         case DeclaratorChunk::Array:
349         case DeclaratorChunk::Function:
350         case DeclaratorChunk::Reference:
351         case DeclaratorChunk::Pipe:
352           continue;
353 
354         case DeclaratorChunk::MemberPointer:
355         case DeclaratorChunk::Pointer:
356           if (onlyBlockPointers)
357             continue;
358 
359           // fallthrough
360 
361         case DeclaratorChunk::BlockPointer:
362           result = &ptrChunk;
363           goto continue_outer;
364         }
365         llvm_unreachable("bad declarator chunk kind");
366       }
367 
368       // If we run out of declarators doing that, we're done.
369       return result;
370     }
371     llvm_unreachable("bad declarator chunk kind");
372 
373     // Okay, reconsider from our new point.
374   continue_outer: ;
375   }
376 
377   // Ran out of chunks, bail out.
378   return result;
379 }
380 
381 /// Given that an objc_gc attribute was written somewhere on a
382 /// declaration *other* than on the declarator itself (for which, use
383 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
384 /// didn't apply in whatever position it was written in, try to move
385 /// it to a more appropriate position.
386 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
387                                           AttributeList &attr,
388                                           QualType type) {
389   Declarator &declarator = state.getDeclarator();
390 
391   // Move it to the outermost normal or block pointer declarator.
392   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
393     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
394     switch (chunk.Kind) {
395     case DeclaratorChunk::Pointer:
396     case DeclaratorChunk::BlockPointer: {
397       // But don't move an ARC ownership attribute to the return type
398       // of a block.
399       DeclaratorChunk *destChunk = nullptr;
400       if (state.isProcessingDeclSpec() &&
401           attr.getKind() == AttributeList::AT_ObjCOwnership)
402         destChunk = maybeMovePastReturnType(declarator, i - 1,
403                                             /*onlyBlockPointers=*/true);
404       if (!destChunk) destChunk = &chunk;
405 
406       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
407                              destChunk->getAttrListRef());
408       return;
409     }
410 
411     case DeclaratorChunk::Paren:
412     case DeclaratorChunk::Array:
413       continue;
414 
415     // We may be starting at the return type of a block.
416     case DeclaratorChunk::Function:
417       if (state.isProcessingDeclSpec() &&
418           attr.getKind() == AttributeList::AT_ObjCOwnership) {
419         if (DeclaratorChunk *dest = maybeMovePastReturnType(
420                                       declarator, i,
421                                       /*onlyBlockPointers=*/true)) {
422           moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
423                                  dest->getAttrListRef());
424           return;
425         }
426       }
427       goto error;
428 
429     // Don't walk through these.
430     case DeclaratorChunk::Reference:
431     case DeclaratorChunk::MemberPointer:
432     case DeclaratorChunk::Pipe:
433       goto error;
434     }
435   }
436  error:
437 
438   diagnoseBadTypeAttribute(state.getSema(), attr, type);
439 }
440 
441 /// Distribute an objc_gc type attribute that was written on the
442 /// declarator.
443 static void
444 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
445                                             AttributeList &attr,
446                                             QualType &declSpecType) {
447   Declarator &declarator = state.getDeclarator();
448 
449   // objc_gc goes on the innermost pointer to something that's not a
450   // pointer.
451   unsigned innermost = -1U;
452   bool considerDeclSpec = true;
453   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
454     DeclaratorChunk &chunk = declarator.getTypeObject(i);
455     switch (chunk.Kind) {
456     case DeclaratorChunk::Pointer:
457     case DeclaratorChunk::BlockPointer:
458       innermost = i;
459       continue;
460 
461     case DeclaratorChunk::Reference:
462     case DeclaratorChunk::MemberPointer:
463     case DeclaratorChunk::Paren:
464     case DeclaratorChunk::Array:
465     case DeclaratorChunk::Pipe:
466       continue;
467 
468     case DeclaratorChunk::Function:
469       considerDeclSpec = false;
470       goto done;
471     }
472   }
473  done:
474 
475   // That might actually be the decl spec if we weren't blocked by
476   // anything in the declarator.
477   if (considerDeclSpec) {
478     if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
479       // Splice the attribute into the decl spec.  Prevents the
480       // attribute from being applied multiple times and gives
481       // the source-location-filler something to work with.
482       state.saveDeclSpecAttrs();
483       moveAttrFromListToList(attr, declarator.getAttrListRef(),
484                declarator.getMutableDeclSpec().getAttributes().getListRef());
485       return;
486     }
487   }
488 
489   // Otherwise, if we found an appropriate chunk, splice the attribute
490   // into it.
491   if (innermost != -1U) {
492     moveAttrFromListToList(attr, declarator.getAttrListRef(),
493                        declarator.getTypeObject(innermost).getAttrListRef());
494     return;
495   }
496 
497   // Otherwise, diagnose when we're done building the type.
498   spliceAttrOutOfList(attr, declarator.getAttrListRef());
499   state.addIgnoredTypeAttr(attr);
500 }
501 
502 /// A function type attribute was written somewhere in a declaration
503 /// *other* than on the declarator itself or in the decl spec.  Given
504 /// that it didn't apply in whatever position it was written in, try
505 /// to move it to a more appropriate position.
506 static void distributeFunctionTypeAttr(TypeProcessingState &state,
507                                        AttributeList &attr,
508                                        QualType type) {
509   Declarator &declarator = state.getDeclarator();
510 
511   // Try to push the attribute from the return type of a function to
512   // the function itself.
513   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
514     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
515     switch (chunk.Kind) {
516     case DeclaratorChunk::Function:
517       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
518                              chunk.getAttrListRef());
519       return;
520 
521     case DeclaratorChunk::Paren:
522     case DeclaratorChunk::Pointer:
523     case DeclaratorChunk::BlockPointer:
524     case DeclaratorChunk::Array:
525     case DeclaratorChunk::Reference:
526     case DeclaratorChunk::MemberPointer:
527     case DeclaratorChunk::Pipe:
528       continue;
529     }
530   }
531 
532   diagnoseBadTypeAttribute(state.getSema(), attr, type);
533 }
534 
535 /// Try to distribute a function type attribute to the innermost
536 /// function chunk or type.  Returns true if the attribute was
537 /// distributed, false if no location was found.
538 static bool
539 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
540                                       AttributeList &attr,
541                                       AttributeList *&attrList,
542                                       QualType &declSpecType) {
543   Declarator &declarator = state.getDeclarator();
544 
545   // Put it on the innermost function chunk, if there is one.
546   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
547     DeclaratorChunk &chunk = declarator.getTypeObject(i);
548     if (chunk.Kind != DeclaratorChunk::Function) continue;
549 
550     moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
551     return true;
552   }
553 
554   return handleFunctionTypeAttr(state, attr, declSpecType);
555 }
556 
557 /// A function type attribute was written in the decl spec.  Try to
558 /// apply it somewhere.
559 static void
560 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
561                                        AttributeList &attr,
562                                        QualType &declSpecType) {
563   state.saveDeclSpecAttrs();
564 
565   // C++11 attributes before the decl specifiers actually appertain to
566   // the declarators. Move them straight there. We don't support the
567   // 'put them wherever you like' semantics we allow for GNU attributes.
568   if (attr.isCXX11Attribute()) {
569     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
570                            state.getDeclarator().getAttrListRef());
571     return;
572   }
573 
574   // Try to distribute to the innermost.
575   if (distributeFunctionTypeAttrToInnermost(state, attr,
576                                             state.getCurrentAttrListRef(),
577                                             declSpecType))
578     return;
579 
580   // If that failed, diagnose the bad attribute when the declarator is
581   // fully built.
582   state.addIgnoredTypeAttr(attr);
583 }
584 
585 /// A function type attribute was written on the declarator.  Try to
586 /// apply it somewhere.
587 static void
588 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
589                                          AttributeList &attr,
590                                          QualType &declSpecType) {
591   Declarator &declarator = state.getDeclarator();
592 
593   // Try to distribute to the innermost.
594   if (distributeFunctionTypeAttrToInnermost(state, attr,
595                                             declarator.getAttrListRef(),
596                                             declSpecType))
597     return;
598 
599   // If that failed, diagnose the bad attribute when the declarator is
600   // fully built.
601   spliceAttrOutOfList(attr, declarator.getAttrListRef());
602   state.addIgnoredTypeAttr(attr);
603 }
604 
605 /// \brief Given that there are attributes written on the declarator
606 /// itself, try to distribute any type attributes to the appropriate
607 /// declarator chunk.
608 ///
609 /// These are attributes like the following:
610 ///   int f ATTR;
611 ///   int (f ATTR)();
612 /// but not necessarily this:
613 ///   int f() ATTR;
614 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
615                                               QualType &declSpecType) {
616   // Collect all the type attributes from the declarator itself.
617   assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
618   AttributeList *attr = state.getDeclarator().getAttributes();
619   AttributeList *next;
620   do {
621     next = attr->getNext();
622 
623     // Do not distribute C++11 attributes. They have strict rules for what
624     // they appertain to.
625     if (attr->isCXX11Attribute())
626       continue;
627 
628     switch (attr->getKind()) {
629     OBJC_POINTER_TYPE_ATTRS_CASELIST:
630       distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
631       break;
632 
633     case AttributeList::AT_NSReturnsRetained:
634       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
635         break;
636       // fallthrough
637 
638     FUNCTION_TYPE_ATTRS_CASELIST:
639       distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
640       break;
641 
642     MS_TYPE_ATTRS_CASELIST:
643       // Microsoft type attributes cannot go after the declarator-id.
644       continue;
645 
646     NULLABILITY_TYPE_ATTRS_CASELIST:
647       // Nullability specifiers cannot go after the declarator-id.
648 
649     // Objective-C __kindof does not get distributed.
650     case AttributeList::AT_ObjCKindOf:
651       continue;
652 
653     default:
654       break;
655     }
656   } while ((attr = next));
657 }
658 
659 /// Add a synthetic '()' to a block-literal declarator if it is
660 /// required, given the return type.
661 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
662                                           QualType declSpecType) {
663   Declarator &declarator = state.getDeclarator();
664 
665   // First, check whether the declarator would produce a function,
666   // i.e. whether the innermost semantic chunk is a function.
667   if (declarator.isFunctionDeclarator()) {
668     // If so, make that declarator a prototyped declarator.
669     declarator.getFunctionTypeInfo().hasPrototype = true;
670     return;
671   }
672 
673   // If there are any type objects, the type as written won't name a
674   // function, regardless of the decl spec type.  This is because a
675   // block signature declarator is always an abstract-declarator, and
676   // abstract-declarators can't just be parentheses chunks.  Therefore
677   // we need to build a function chunk unless there are no type
678   // objects and the decl spec type is a function.
679   if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
680     return;
681 
682   // Note that there *are* cases with invalid declarators where
683   // declarators consist solely of parentheses.  In general, these
684   // occur only in failed efforts to make function declarators, so
685   // faking up the function chunk is still the right thing to do.
686 
687   // Otherwise, we need to fake up a function declarator.
688   SourceLocation loc = declarator.getLocStart();
689 
690   // ...and *prepend* it to the declarator.
691   SourceLocation NoLoc;
692   declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
693       /*HasProto=*/true,
694       /*IsAmbiguous=*/false,
695       /*LParenLoc=*/NoLoc,
696       /*ArgInfo=*/nullptr,
697       /*NumArgs=*/0,
698       /*EllipsisLoc=*/NoLoc,
699       /*RParenLoc=*/NoLoc,
700       /*TypeQuals=*/0,
701       /*RefQualifierIsLvalueRef=*/true,
702       /*RefQualifierLoc=*/NoLoc,
703       /*ConstQualifierLoc=*/NoLoc,
704       /*VolatileQualifierLoc=*/NoLoc,
705       /*RestrictQualifierLoc=*/NoLoc,
706       /*MutableLoc=*/NoLoc, EST_None,
707       /*ESpecRange=*/SourceRange(),
708       /*Exceptions=*/nullptr,
709       /*ExceptionRanges=*/nullptr,
710       /*NumExceptions=*/0,
711       /*NoexceptExpr=*/nullptr,
712       /*ExceptionSpecTokens=*/nullptr,
713       loc, loc, declarator));
714 
715   // For consistency, make sure the state still has us as processing
716   // the decl spec.
717   assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
718   state.setCurrentChunkIndex(declarator.getNumTypeObjects());
719 }
720 
721 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
722                                             unsigned &TypeQuals,
723                                             QualType TypeSoFar,
724                                             unsigned RemoveTQs,
725                                             unsigned DiagID) {
726   // If this occurs outside a template instantiation, warn the user about
727   // it; they probably didn't mean to specify a redundant qualifier.
728   typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
729   for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
730                        QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
731                        QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
732     if (!(RemoveTQs & Qual.first))
733       continue;
734 
735     if (S.ActiveTemplateInstantiations.empty()) {
736       if (TypeQuals & Qual.first)
737         S.Diag(Qual.second, DiagID)
738           << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
739           << FixItHint::CreateRemoval(Qual.second);
740     }
741 
742     TypeQuals &= ~Qual.first;
743   }
744 }
745 
746 /// Apply Objective-C type arguments to the given type.
747 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
748                                   ArrayRef<TypeSourceInfo *> typeArgs,
749                                   SourceRange typeArgsRange,
750                                   bool failOnError = false) {
751   // We can only apply type arguments to an Objective-C class type.
752   const auto *objcObjectType = type->getAs<ObjCObjectType>();
753   if (!objcObjectType || !objcObjectType->getInterface()) {
754     S.Diag(loc, diag::err_objc_type_args_non_class)
755       << type
756       << typeArgsRange;
757 
758     if (failOnError)
759       return QualType();
760     return type;
761   }
762 
763   // The class type must be parameterized.
764   ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
765   ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
766   if (!typeParams) {
767     S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
768       << objcClass->getDeclName()
769       << FixItHint::CreateRemoval(typeArgsRange);
770 
771     if (failOnError)
772       return QualType();
773 
774     return type;
775   }
776 
777   // The type must not already be specialized.
778   if (objcObjectType->isSpecialized()) {
779     S.Diag(loc, diag::err_objc_type_args_specialized_class)
780       << type
781       << FixItHint::CreateRemoval(typeArgsRange);
782 
783     if (failOnError)
784       return QualType();
785 
786     return type;
787   }
788 
789   // Check the type arguments.
790   SmallVector<QualType, 4> finalTypeArgs;
791   unsigned numTypeParams = typeParams->size();
792   bool anyPackExpansions = false;
793   for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
794     TypeSourceInfo *typeArgInfo = typeArgs[i];
795     QualType typeArg = typeArgInfo->getType();
796 
797     // Type arguments cannot have explicit qualifiers or nullability.
798     // We ignore indirect sources of these, e.g. behind typedefs or
799     // template arguments.
800     if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
801       bool diagnosed = false;
802       SourceRange rangeToRemove;
803       if (auto attr = qual.getAs<AttributedTypeLoc>()) {
804         rangeToRemove = attr.getLocalSourceRange();
805         if (attr.getTypePtr()->getImmediateNullability()) {
806           typeArg = attr.getTypePtr()->getModifiedType();
807           S.Diag(attr.getLocStart(),
808                  diag::err_objc_type_arg_explicit_nullability)
809             << typeArg << FixItHint::CreateRemoval(rangeToRemove);
810           diagnosed = true;
811         }
812       }
813 
814       if (!diagnosed) {
815         S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified)
816           << typeArg << typeArg.getQualifiers().getAsString()
817           << FixItHint::CreateRemoval(rangeToRemove);
818       }
819     }
820 
821     // Remove qualifiers even if they're non-local.
822     typeArg = typeArg.getUnqualifiedType();
823 
824     finalTypeArgs.push_back(typeArg);
825 
826     if (typeArg->getAs<PackExpansionType>())
827       anyPackExpansions = true;
828 
829     // Find the corresponding type parameter, if there is one.
830     ObjCTypeParamDecl *typeParam = nullptr;
831     if (!anyPackExpansions) {
832       if (i < numTypeParams) {
833         typeParam = typeParams->begin()[i];
834       } else {
835         // Too many arguments.
836         S.Diag(loc, diag::err_objc_type_args_wrong_arity)
837           << false
838           << objcClass->getDeclName()
839           << (unsigned)typeArgs.size()
840           << numTypeParams;
841         S.Diag(objcClass->getLocation(), diag::note_previous_decl)
842           << objcClass;
843 
844         if (failOnError)
845           return QualType();
846 
847         return type;
848       }
849     }
850 
851     // Objective-C object pointer types must be substitutable for the bounds.
852     if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
853       // If we don't have a type parameter to match against, assume
854       // everything is fine. There was a prior pack expansion that
855       // means we won't be able to match anything.
856       if (!typeParam) {
857         assert(anyPackExpansions && "Too many arguments?");
858         continue;
859       }
860 
861       // Retrieve the bound.
862       QualType bound = typeParam->getUnderlyingType();
863       const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
864 
865       // Determine whether the type argument is substitutable for the bound.
866       if (typeArgObjC->isObjCIdType()) {
867         // When the type argument is 'id', the only acceptable type
868         // parameter bound is 'id'.
869         if (boundObjC->isObjCIdType())
870           continue;
871       } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
872         // Otherwise, we follow the assignability rules.
873         continue;
874       }
875 
876       // Diagnose the mismatch.
877       S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
878              diag::err_objc_type_arg_does_not_match_bound)
879         << typeArg << bound << typeParam->getDeclName();
880       S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
881         << typeParam->getDeclName();
882 
883       if (failOnError)
884         return QualType();
885 
886       return type;
887     }
888 
889     // Block pointer types are permitted for unqualified 'id' bounds.
890     if (typeArg->isBlockPointerType()) {
891       // If we don't have a type parameter to match against, assume
892       // everything is fine. There was a prior pack expansion that
893       // means we won't be able to match anything.
894       if (!typeParam) {
895         assert(anyPackExpansions && "Too many arguments?");
896         continue;
897       }
898 
899       // Retrieve the bound.
900       QualType bound = typeParam->getUnderlyingType();
901       if (bound->isBlockCompatibleObjCPointerType(S.Context))
902         continue;
903 
904       // Diagnose the mismatch.
905       S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
906              diag::err_objc_type_arg_does_not_match_bound)
907         << typeArg << bound << typeParam->getDeclName();
908       S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
909         << typeParam->getDeclName();
910 
911       if (failOnError)
912         return QualType();
913 
914       return type;
915     }
916 
917     // Dependent types will be checked at instantiation time.
918     if (typeArg->isDependentType()) {
919       continue;
920     }
921 
922     // Diagnose non-id-compatible type arguments.
923     S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
924            diag::err_objc_type_arg_not_id_compatible)
925       << typeArg
926       << typeArgInfo->getTypeLoc().getSourceRange();
927 
928     if (failOnError)
929       return QualType();
930 
931     return type;
932   }
933 
934   // Make sure we didn't have the wrong number of arguments.
935   if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
936     S.Diag(loc, diag::err_objc_type_args_wrong_arity)
937       << (typeArgs.size() < typeParams->size())
938       << objcClass->getDeclName()
939       << (unsigned)finalTypeArgs.size()
940       << (unsigned)numTypeParams;
941     S.Diag(objcClass->getLocation(), diag::note_previous_decl)
942       << objcClass;
943 
944     if (failOnError)
945       return QualType();
946 
947     return type;
948   }
949 
950   // Success. Form the specialized type.
951   return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
952 }
953 
954 /// Apply Objective-C protocol qualifiers to the given type.
955 static QualType applyObjCProtocolQualifiers(
956                   Sema &S, SourceLocation loc, SourceRange range, QualType type,
957                   ArrayRef<ObjCProtocolDecl *> protocols,
958                   const SourceLocation *protocolLocs,
959                   bool failOnError = false) {
960   ASTContext &ctx = S.Context;
961   if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
962     // FIXME: Check for protocols to which the class type is already
963     // known to conform.
964 
965     return ctx.getObjCObjectType(objT->getBaseType(),
966                                  objT->getTypeArgsAsWritten(),
967                                  protocols,
968                                  objT->isKindOfTypeAsWritten());
969   }
970 
971   if (type->isObjCObjectType()) {
972     // Silently overwrite any existing protocol qualifiers.
973     // TODO: determine whether that's the right thing to do.
974 
975     // FIXME: Check for protocols to which the class type is already
976     // known to conform.
977     return ctx.getObjCObjectType(type, { }, protocols, false);
978   }
979 
980   // id<protocol-list>
981   if (type->isObjCIdType()) {
982     const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
983     type = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, { }, protocols,
984                                  objPtr->isKindOfType());
985     return ctx.getObjCObjectPointerType(type);
986   }
987 
988   // Class<protocol-list>
989   if (type->isObjCClassType()) {
990     const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
991     type = ctx.getObjCObjectType(ctx.ObjCBuiltinClassTy, { }, protocols,
992                                  objPtr->isKindOfType());
993     return ctx.getObjCObjectPointerType(type);
994   }
995 
996   S.Diag(loc, diag::err_invalid_protocol_qualifiers)
997     << range;
998 
999   if (failOnError)
1000     return QualType();
1001 
1002   return type;
1003 }
1004 
1005 QualType Sema::BuildObjCObjectType(QualType BaseType,
1006                                    SourceLocation Loc,
1007                                    SourceLocation TypeArgsLAngleLoc,
1008                                    ArrayRef<TypeSourceInfo *> TypeArgs,
1009                                    SourceLocation TypeArgsRAngleLoc,
1010                                    SourceLocation ProtocolLAngleLoc,
1011                                    ArrayRef<ObjCProtocolDecl *> Protocols,
1012                                    ArrayRef<SourceLocation> ProtocolLocs,
1013                                    SourceLocation ProtocolRAngleLoc,
1014                                    bool FailOnError) {
1015   QualType Result = BaseType;
1016   if (!TypeArgs.empty()) {
1017     Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1018                                SourceRange(TypeArgsLAngleLoc,
1019                                            TypeArgsRAngleLoc),
1020                                FailOnError);
1021     if (FailOnError && Result.isNull())
1022       return QualType();
1023   }
1024 
1025   if (!Protocols.empty()) {
1026     Result = applyObjCProtocolQualifiers(*this, Loc,
1027                                          SourceRange(ProtocolLAngleLoc,
1028                                                      ProtocolRAngleLoc),
1029                                          Result, Protocols,
1030                                          ProtocolLocs.data(),
1031                                          FailOnError);
1032     if (FailOnError && Result.isNull())
1033       return QualType();
1034   }
1035 
1036   return Result;
1037 }
1038 
1039 TypeResult Sema::actOnObjCProtocolQualifierType(
1040              SourceLocation lAngleLoc,
1041              ArrayRef<Decl *> protocols,
1042              ArrayRef<SourceLocation> protocolLocs,
1043              SourceLocation rAngleLoc) {
1044   // Form id<protocol-list>.
1045   QualType Result = Context.getObjCObjectType(
1046                       Context.ObjCBuiltinIdTy, { },
1047                       llvm::makeArrayRef(
1048                         (ObjCProtocolDecl * const *)protocols.data(),
1049                         protocols.size()),
1050                       false);
1051   Result = Context.getObjCObjectPointerType(Result);
1052 
1053   TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1054   TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1055 
1056   auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1057   ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1058 
1059   auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1060                         .castAs<ObjCObjectTypeLoc>();
1061   ObjCObjectTL.setHasBaseTypeAsWritten(false);
1062   ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1063 
1064   // No type arguments.
1065   ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1066   ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1067 
1068   // Fill in protocol qualifiers.
1069   ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1070   ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1071   for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1072     ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1073 
1074   // We're done. Return the completed type to the parser.
1075   return CreateParsedType(Result, ResultTInfo);
1076 }
1077 
1078 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1079              Scope *S,
1080              SourceLocation Loc,
1081              ParsedType BaseType,
1082              SourceLocation TypeArgsLAngleLoc,
1083              ArrayRef<ParsedType> TypeArgs,
1084              SourceLocation TypeArgsRAngleLoc,
1085              SourceLocation ProtocolLAngleLoc,
1086              ArrayRef<Decl *> Protocols,
1087              ArrayRef<SourceLocation> ProtocolLocs,
1088              SourceLocation ProtocolRAngleLoc) {
1089   TypeSourceInfo *BaseTypeInfo = nullptr;
1090   QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1091   if (T.isNull())
1092     return true;
1093 
1094   // Handle missing type-source info.
1095   if (!BaseTypeInfo)
1096     BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1097 
1098   // Extract type arguments.
1099   SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1100   for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1101     TypeSourceInfo *TypeArgInfo = nullptr;
1102     QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1103     if (TypeArg.isNull()) {
1104       ActualTypeArgInfos.clear();
1105       break;
1106     }
1107 
1108     assert(TypeArgInfo && "No type source info?");
1109     ActualTypeArgInfos.push_back(TypeArgInfo);
1110   }
1111 
1112   // Build the object type.
1113   QualType Result = BuildObjCObjectType(
1114       T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1115       TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1116       ProtocolLAngleLoc,
1117       llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1118                          Protocols.size()),
1119       ProtocolLocs, ProtocolRAngleLoc,
1120       /*FailOnError=*/false);
1121 
1122   if (Result == T)
1123     return BaseType;
1124 
1125   // Create source information for this type.
1126   TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1127   TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1128 
1129   // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1130   // object pointer type. Fill in source information for it.
1131   if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1132     // The '*' is implicit.
1133     ObjCObjectPointerTL.setStarLoc(SourceLocation());
1134     ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1135   }
1136 
1137   auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1138 
1139   // Type argument information.
1140   if (ObjCObjectTL.getNumTypeArgs() > 0) {
1141     assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1142     ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1143     ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1144     for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1145       ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1146   } else {
1147     ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1148     ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1149   }
1150 
1151   // Protocol qualifier information.
1152   if (ObjCObjectTL.getNumProtocols() > 0) {
1153     assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1154     ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1155     ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1156     for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1157       ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1158   } else {
1159     ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1160     ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1161   }
1162 
1163   // Base type.
1164   ObjCObjectTL.setHasBaseTypeAsWritten(true);
1165   if (ObjCObjectTL.getType() == T)
1166     ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1167   else
1168     ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1169 
1170   // We're done. Return the completed type to the parser.
1171   return CreateParsedType(Result, ResultTInfo);
1172 }
1173 
1174 /// \brief Convert the specified declspec to the appropriate type
1175 /// object.
1176 /// \param state Specifies the declarator containing the declaration specifier
1177 /// to be converted, along with other associated processing state.
1178 /// \returns The type described by the declaration specifiers.  This function
1179 /// never returns null.
1180 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1181   // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1182   // checking.
1183 
1184   Sema &S = state.getSema();
1185   Declarator &declarator = state.getDeclarator();
1186   const DeclSpec &DS = declarator.getDeclSpec();
1187   SourceLocation DeclLoc = declarator.getIdentifierLoc();
1188   if (DeclLoc.isInvalid())
1189     DeclLoc = DS.getLocStart();
1190 
1191   ASTContext &Context = S.Context;
1192 
1193   QualType Result;
1194   switch (DS.getTypeSpecType()) {
1195   case DeclSpec::TST_void:
1196     Result = Context.VoidTy;
1197     break;
1198   case DeclSpec::TST_char:
1199     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1200       Result = Context.CharTy;
1201     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1202       Result = Context.SignedCharTy;
1203     else {
1204       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1205              "Unknown TSS value");
1206       Result = Context.UnsignedCharTy;
1207     }
1208     break;
1209   case DeclSpec::TST_wchar:
1210     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1211       Result = Context.WCharTy;
1212     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1213       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1214         << DS.getSpecifierName(DS.getTypeSpecType(),
1215                                Context.getPrintingPolicy());
1216       Result = Context.getSignedWCharType();
1217     } else {
1218       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1219         "Unknown TSS value");
1220       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1221         << DS.getSpecifierName(DS.getTypeSpecType(),
1222                                Context.getPrintingPolicy());
1223       Result = Context.getUnsignedWCharType();
1224     }
1225     break;
1226   case DeclSpec::TST_char16:
1227       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1228         "Unknown TSS value");
1229       Result = Context.Char16Ty;
1230     break;
1231   case DeclSpec::TST_char32:
1232       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1233         "Unknown TSS value");
1234       Result = Context.Char32Ty;
1235     break;
1236   case DeclSpec::TST_unspecified:
1237     // If this is a missing declspec in a block literal return context, then it
1238     // is inferred from the return statements inside the block.
1239     // The declspec is always missing in a lambda expr context; it is either
1240     // specified with a trailing return type or inferred.
1241     if (S.getLangOpts().CPlusPlus14 &&
1242         declarator.getContext() == Declarator::LambdaExprContext) {
1243       // In C++1y, a lambda's implicit return type is 'auto'.
1244       Result = Context.getAutoDeductType();
1245       break;
1246     } else if (declarator.getContext() == Declarator::LambdaExprContext ||
1247                isOmittedBlockReturnType(declarator)) {
1248       Result = Context.DependentTy;
1249       break;
1250     }
1251 
1252     // Unspecified typespec defaults to int in C90.  However, the C90 grammar
1253     // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1254     // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
1255     // Note that the one exception to this is function definitions, which are
1256     // allowed to be completely missing a declspec.  This is handled in the
1257     // parser already though by it pretending to have seen an 'int' in this
1258     // case.
1259     if (S.getLangOpts().ImplicitInt) {
1260       // In C89 mode, we only warn if there is a completely missing declspec
1261       // when one is not allowed.
1262       if (DS.isEmpty()) {
1263         S.Diag(DeclLoc, diag::ext_missing_declspec)
1264           << DS.getSourceRange()
1265         << FixItHint::CreateInsertion(DS.getLocStart(), "int");
1266       }
1267     } else if (!DS.hasTypeSpecifier()) {
1268       // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
1269       // "At least one type specifier shall be given in the declaration
1270       // specifiers in each declaration, and in the specifier-qualifier list in
1271       // each struct declaration and type name."
1272       if (S.getLangOpts().CPlusPlus) {
1273         S.Diag(DeclLoc, diag::err_missing_type_specifier)
1274           << DS.getSourceRange();
1275 
1276         // When this occurs in C++ code, often something is very broken with the
1277         // value being declared, poison it as invalid so we don't get chains of
1278         // errors.
1279         declarator.setInvalidType(true);
1280       } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1281         S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1282           << DS.getSourceRange();
1283         declarator.setInvalidType(true);
1284       } else {
1285         S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1286           << DS.getSourceRange();
1287       }
1288     }
1289 
1290     // FALL THROUGH.
1291   case DeclSpec::TST_int: {
1292     if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
1293       switch (DS.getTypeSpecWidth()) {
1294       case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1295       case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
1296       case DeclSpec::TSW_long:        Result = Context.LongTy; break;
1297       case DeclSpec::TSW_longlong:
1298         Result = Context.LongLongTy;
1299 
1300         // 'long long' is a C99 or C++11 feature.
1301         if (!S.getLangOpts().C99) {
1302           if (S.getLangOpts().CPlusPlus)
1303             S.Diag(DS.getTypeSpecWidthLoc(),
1304                    S.getLangOpts().CPlusPlus11 ?
1305                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1306           else
1307             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1308         }
1309         break;
1310       }
1311     } else {
1312       switch (DS.getTypeSpecWidth()) {
1313       case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1314       case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
1315       case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
1316       case DeclSpec::TSW_longlong:
1317         Result = Context.UnsignedLongLongTy;
1318 
1319         // 'long long' is a C99 or C++11 feature.
1320         if (!S.getLangOpts().C99) {
1321           if (S.getLangOpts().CPlusPlus)
1322             S.Diag(DS.getTypeSpecWidthLoc(),
1323                    S.getLangOpts().CPlusPlus11 ?
1324                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1325           else
1326             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1327         }
1328         break;
1329       }
1330     }
1331     break;
1332   }
1333   case DeclSpec::TST_int128:
1334     if (!S.Context.getTargetInfo().hasInt128Type())
1335       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
1336     if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1337       Result = Context.UnsignedInt128Ty;
1338     else
1339       Result = Context.Int128Ty;
1340     break;
1341   case DeclSpec::TST_half: Result = Context.HalfTy; break;
1342   case DeclSpec::TST_float: Result = Context.FloatTy; break;
1343   case DeclSpec::TST_double:
1344     if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1345       Result = Context.LongDoubleTy;
1346     else
1347       Result = Context.DoubleTy;
1348 
1349     if (S.getLangOpts().OpenCL &&
1350         !((S.getLangOpts().OpenCLVersion >= 120) ||
1351           S.getOpenCLOptions().cl_khr_fp64)) {
1352       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1353           << Result << "cl_khr_fp64";
1354       declarator.setInvalidType(true);
1355     }
1356     break;
1357   case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1358   case DeclSpec::TST_decimal32:    // _Decimal32
1359   case DeclSpec::TST_decimal64:    // _Decimal64
1360   case DeclSpec::TST_decimal128:   // _Decimal128
1361     S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1362     Result = Context.IntTy;
1363     declarator.setInvalidType(true);
1364     break;
1365   case DeclSpec::TST_class:
1366   case DeclSpec::TST_enum:
1367   case DeclSpec::TST_union:
1368   case DeclSpec::TST_struct:
1369   case DeclSpec::TST_interface: {
1370     TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
1371     if (!D) {
1372       // This can happen in C++ with ambiguous lookups.
1373       Result = Context.IntTy;
1374       declarator.setInvalidType(true);
1375       break;
1376     }
1377 
1378     // If the type is deprecated or unavailable, diagnose it.
1379     S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1380 
1381     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1382            DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1383 
1384     // TypeQuals handled by caller.
1385     Result = Context.getTypeDeclType(D);
1386 
1387     // In both C and C++, make an ElaboratedType.
1388     ElaboratedTypeKeyword Keyword
1389       = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1390     Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
1391     break;
1392   }
1393   case DeclSpec::TST_typename: {
1394     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1395            DS.getTypeSpecSign() == 0 &&
1396            "Can't handle qualifiers on typedef names yet!");
1397     Result = S.GetTypeFromParser(DS.getRepAsType());
1398     if (Result.isNull()) {
1399       declarator.setInvalidType(true);
1400     } else if (S.getLangOpts().OpenCL) {
1401       if (Result->getAs<AtomicType>()) {
1402         StringRef TypeName = Result.getBaseTypeIdentifier()->getName();
1403         bool NoExtTypes =
1404             llvm::StringSwitch<bool>(TypeName)
1405                 .Cases("atomic_int", "atomic_uint", "atomic_float",
1406                        "atomic_flag", true)
1407                 .Default(false);
1408         if (!S.getOpenCLOptions().cl_khr_int64_base_atomics && !NoExtTypes) {
1409           S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1410               << Result << "cl_khr_int64_base_atomics";
1411           declarator.setInvalidType(true);
1412         }
1413         if (!S.getOpenCLOptions().cl_khr_int64_extended_atomics &&
1414             !NoExtTypes) {
1415           S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1416               << Result << "cl_khr_int64_extended_atomics";
1417           declarator.setInvalidType(true);
1418         }
1419         if (!S.getOpenCLOptions().cl_khr_fp64 &&
1420             !TypeName.compare("atomic_double")) {
1421           S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1422               << Result << "cl_khr_fp64";
1423           declarator.setInvalidType(true);
1424         }
1425       } else if (!S.getOpenCLOptions().cl_khr_gl_msaa_sharing &&
1426                  (Result->isImage2dMSAAT() || Result->isImage2dArrayMSAAT() ||
1427                   Result->isImage2dArrayMSAATDepth() ||
1428                   Result->isImage2dMSAATDepth())) {
1429         S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1430             << Result << "cl_khr_gl_msaa_sharing";
1431         declarator.setInvalidType(true);
1432       }
1433     }
1434 
1435     // TypeQuals handled by caller.
1436     break;
1437   }
1438   case DeclSpec::TST_typeofType:
1439     // FIXME: Preserve type source info.
1440     Result = S.GetTypeFromParser(DS.getRepAsType());
1441     assert(!Result.isNull() && "Didn't get a type for typeof?");
1442     if (!Result->isDependentType())
1443       if (const TagType *TT = Result->getAs<TagType>())
1444         S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1445     // TypeQuals handled by caller.
1446     Result = Context.getTypeOfType(Result);
1447     break;
1448   case DeclSpec::TST_typeofExpr: {
1449     Expr *E = DS.getRepAsExpr();
1450     assert(E && "Didn't get an expression for typeof?");
1451     // TypeQuals handled by caller.
1452     Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1453     if (Result.isNull()) {
1454       Result = Context.IntTy;
1455       declarator.setInvalidType(true);
1456     }
1457     break;
1458   }
1459   case DeclSpec::TST_decltype: {
1460     Expr *E = DS.getRepAsExpr();
1461     assert(E && "Didn't get an expression for decltype?");
1462     // TypeQuals handled by caller.
1463     Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1464     if (Result.isNull()) {
1465       Result = Context.IntTy;
1466       declarator.setInvalidType(true);
1467     }
1468     break;
1469   }
1470   case DeclSpec::TST_underlyingType:
1471     Result = S.GetTypeFromParser(DS.getRepAsType());
1472     assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1473     Result = S.BuildUnaryTransformType(Result,
1474                                        UnaryTransformType::EnumUnderlyingType,
1475                                        DS.getTypeSpecTypeLoc());
1476     if (Result.isNull()) {
1477       Result = Context.IntTy;
1478       declarator.setInvalidType(true);
1479     }
1480     break;
1481 
1482   case DeclSpec::TST_auto:
1483     // TypeQuals handled by caller.
1484     // If auto is mentioned in a lambda parameter context, convert it to a
1485     // template parameter type immediately, with the appropriate depth and
1486     // index, and update sema's state (LambdaScopeInfo) for the current lambda
1487     // being analyzed (which tracks the invented type template parameter).
1488     if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1489       sema::LambdaScopeInfo *LSI = S.getCurLambda();
1490       assert(LSI && "No LambdaScopeInfo on the stack!");
1491       const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1492       const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1493       const bool IsParameterPack = declarator.hasEllipsis();
1494 
1495       // Turns out we must create the TemplateTypeParmDecl here to
1496       // retrieve the corresponding template parameter type.
1497       TemplateTypeParmDecl *CorrespondingTemplateParam =
1498         TemplateTypeParmDecl::Create(Context,
1499         // Temporarily add to the TranslationUnit DeclContext.  When the
1500         // associated TemplateParameterList is attached to a template
1501         // declaration (such as FunctionTemplateDecl), the DeclContext
1502         // for each template parameter gets updated appropriately via
1503         // a call to AdoptTemplateParameterList.
1504         Context.getTranslationUnitDecl(),
1505         /*KeyLoc*/ SourceLocation(),
1506         /*NameLoc*/ declarator.getLocStart(),
1507         TemplateParameterDepth,
1508         AutoParameterPosition,  // our template param index
1509         /* Identifier*/ nullptr, false, IsParameterPack);
1510       LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1511       // Replace the 'auto' in the function parameter with this invented
1512       // template type parameter.
1513       Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1514     } else {
1515       Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1516     }
1517     break;
1518 
1519   case DeclSpec::TST_auto_type:
1520     Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1521     break;
1522 
1523   case DeclSpec::TST_decltype_auto:
1524     Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1525                                  /*IsDependent*/ false);
1526     break;
1527 
1528   case DeclSpec::TST_unknown_anytype:
1529     Result = Context.UnknownAnyTy;
1530     break;
1531 
1532   case DeclSpec::TST_atomic:
1533     Result = S.GetTypeFromParser(DS.getRepAsType());
1534     assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1535     Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1536     if (Result.isNull()) {
1537       Result = Context.IntTy;
1538       declarator.setInvalidType(true);
1539     }
1540     break;
1541 
1542   case DeclSpec::TST_error:
1543     Result = Context.IntTy;
1544     declarator.setInvalidType(true);
1545     break;
1546   }
1547 
1548   // Handle complex types.
1549   if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1550     if (S.getLangOpts().Freestanding)
1551       S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1552     Result = Context.getComplexType(Result);
1553   } else if (DS.isTypeAltiVecVector()) {
1554     unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1555     assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1556     VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1557     if (DS.isTypeAltiVecPixel())
1558       VecKind = VectorType::AltiVecPixel;
1559     else if (DS.isTypeAltiVecBool())
1560       VecKind = VectorType::AltiVecBool;
1561     Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1562   }
1563 
1564   // FIXME: Imaginary.
1565   if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1566     S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1567 
1568   // Before we process any type attributes, synthesize a block literal
1569   // function declarator if necessary.
1570   if (declarator.getContext() == Declarator::BlockLiteralContext)
1571     maybeSynthesizeBlockSignature(state, Result);
1572 
1573   // Apply any type attributes from the decl spec.  This may cause the
1574   // list of type attributes to be temporarily saved while the type
1575   // attributes are pushed around.
1576   // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1577   if (!DS.isTypeSpecPipe())
1578       processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList());
1579 
1580   // Apply const/volatile/restrict qualifiers to T.
1581   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1582     // Warn about CV qualifiers on function types.
1583     // C99 6.7.3p8:
1584     //   If the specification of a function type includes any type qualifiers,
1585     //   the behavior is undefined.
1586     // C++11 [dcl.fct]p7:
1587     //   The effect of a cv-qualifier-seq in a function declarator is not the
1588     //   same as adding cv-qualification on top of the function type. In the
1589     //   latter case, the cv-qualifiers are ignored.
1590     if (TypeQuals && Result->isFunctionType()) {
1591       diagnoseAndRemoveTypeQualifiers(
1592           S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1593           S.getLangOpts().CPlusPlus
1594               ? diag::warn_typecheck_function_qualifiers_ignored
1595               : diag::warn_typecheck_function_qualifiers_unspecified);
1596       // No diagnostic for 'restrict' or '_Atomic' applied to a
1597       // function type; we'll diagnose those later, in BuildQualifiedType.
1598     }
1599 
1600     // C++11 [dcl.ref]p1:
1601     //   Cv-qualified references are ill-formed except when the
1602     //   cv-qualifiers are introduced through the use of a typedef-name
1603     //   or decltype-specifier, in which case the cv-qualifiers are ignored.
1604     //
1605     // There don't appear to be any other contexts in which a cv-qualified
1606     // reference type could be formed, so the 'ill-formed' clause here appears
1607     // to never happen.
1608     if (TypeQuals && Result->isReferenceType()) {
1609       diagnoseAndRemoveTypeQualifiers(
1610           S, DS, TypeQuals, Result,
1611           DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1612           diag::warn_typecheck_reference_qualifiers);
1613     }
1614 
1615     // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1616     // than once in the same specifier-list or qualifier-list, either directly
1617     // or via one or more typedefs."
1618     if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1619         && TypeQuals & Result.getCVRQualifiers()) {
1620       if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1621         S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1622           << "const";
1623       }
1624 
1625       if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1626         S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1627           << "volatile";
1628       }
1629 
1630       // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1631       // produce a warning in this case.
1632     }
1633 
1634     QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1635 
1636     // If adding qualifiers fails, just use the unqualified type.
1637     if (Qualified.isNull())
1638       declarator.setInvalidType(true);
1639     else
1640       Result = Qualified;
1641   }
1642 
1643   assert(!Result.isNull() && "This function should not return a null type");
1644   return Result;
1645 }
1646 
1647 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1648   if (Entity)
1649     return Entity.getAsString();
1650 
1651   return "type name";
1652 }
1653 
1654 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1655                                   Qualifiers Qs, const DeclSpec *DS) {
1656   if (T.isNull())
1657     return QualType();
1658 
1659   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1660   // object or incomplete types shall not be restrict-qualified."
1661   if (Qs.hasRestrict()) {
1662     unsigned DiagID = 0;
1663     QualType ProblemTy;
1664 
1665     if (T->isAnyPointerType() || T->isReferenceType() ||
1666         T->isMemberPointerType()) {
1667       QualType EltTy;
1668       if (T->isObjCObjectPointerType())
1669         EltTy = T;
1670       else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1671         EltTy = PTy->getPointeeType();
1672       else
1673         EltTy = T->getPointeeType();
1674 
1675       // If we have a pointer or reference, the pointee must have an object
1676       // incomplete type.
1677       if (!EltTy->isIncompleteOrObjectType()) {
1678         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1679         ProblemTy = EltTy;
1680       }
1681     } else if (!T->isDependentType()) {
1682       DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1683       ProblemTy = T;
1684     }
1685 
1686     if (DiagID) {
1687       Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1688       Qs.removeRestrict();
1689     }
1690   }
1691 
1692   return Context.getQualifiedType(T, Qs);
1693 }
1694 
1695 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1696                                   unsigned CVRA, const DeclSpec *DS) {
1697   if (T.isNull())
1698     return QualType();
1699 
1700   // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
1701   unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
1702 
1703   // C11 6.7.3/5:
1704   //   If the same qualifier appears more than once in the same
1705   //   specifier-qualifier-list, either directly or via one or more typedefs,
1706   //   the behavior is the same as if it appeared only once.
1707   //
1708   // It's not specified what happens when the _Atomic qualifier is applied to
1709   // a type specified with the _Atomic specifier, but we assume that this
1710   // should be treated as if the _Atomic qualifier appeared multiple times.
1711   if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1712     // C11 6.7.3/5:
1713     //   If other qualifiers appear along with the _Atomic qualifier in a
1714     //   specifier-qualifier-list, the resulting type is the so-qualified
1715     //   atomic type.
1716     //
1717     // Don't need to worry about array types here, since _Atomic can't be
1718     // applied to such types.
1719     SplitQualType Split = T.getSplitUnqualifiedType();
1720     T = BuildAtomicType(QualType(Split.Ty, 0),
1721                         DS ? DS->getAtomicSpecLoc() : Loc);
1722     if (T.isNull())
1723       return T;
1724     Split.Quals.addCVRQualifiers(CVR);
1725     return BuildQualifiedType(T, Loc, Split.Quals);
1726   }
1727 
1728   return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS);
1729 }
1730 
1731 /// \brief Build a paren type including \p T.
1732 QualType Sema::BuildParenType(QualType T) {
1733   return Context.getParenType(T);
1734 }
1735 
1736 /// Given that we're building a pointer or reference to the given
1737 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1738                                            SourceLocation loc,
1739                                            bool isReference) {
1740   // Bail out if retention is unrequired or already specified.
1741   if (!type->isObjCLifetimeType() ||
1742       type.getObjCLifetime() != Qualifiers::OCL_None)
1743     return type;
1744 
1745   Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1746 
1747   // If the object type is const-qualified, we can safely use
1748   // __unsafe_unretained.  This is safe (because there are no read
1749   // barriers), and it'll be safe to coerce anything but __weak* to
1750   // the resulting type.
1751   if (type.isConstQualified()) {
1752     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1753 
1754   // Otherwise, check whether the static type does not require
1755   // retaining.  This currently only triggers for Class (possibly
1756   // protocol-qualifed, and arrays thereof).
1757   } else if (type->isObjCARCImplicitlyUnretainedType()) {
1758     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1759 
1760   // If we are in an unevaluated context, like sizeof, skip adding a
1761   // qualification.
1762   } else if (S.isUnevaluatedContext()) {
1763     return type;
1764 
1765   // If that failed, give an error and recover using __strong.  __strong
1766   // is the option most likely to prevent spurious second-order diagnostics,
1767   // like when binding a reference to a field.
1768   } else {
1769     // These types can show up in private ivars in system headers, so
1770     // we need this to not be an error in those cases.  Instead we
1771     // want to delay.
1772     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1773       S.DelayedDiagnostics.add(
1774           sema::DelayedDiagnostic::makeForbiddenType(loc,
1775               diag::err_arc_indirect_no_ownership, type, isReference));
1776     } else {
1777       S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1778     }
1779     implicitLifetime = Qualifiers::OCL_Strong;
1780   }
1781   assert(implicitLifetime && "didn't infer any lifetime!");
1782 
1783   Qualifiers qs;
1784   qs.addObjCLifetime(implicitLifetime);
1785   return S.Context.getQualifiedType(type, qs);
1786 }
1787 
1788 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1789   std::string Quals =
1790     Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1791 
1792   switch (FnTy->getRefQualifier()) {
1793   case RQ_None:
1794     break;
1795 
1796   case RQ_LValue:
1797     if (!Quals.empty())
1798       Quals += ' ';
1799     Quals += '&';
1800     break;
1801 
1802   case RQ_RValue:
1803     if (!Quals.empty())
1804       Quals += ' ';
1805     Quals += "&&";
1806     break;
1807   }
1808 
1809   return Quals;
1810 }
1811 
1812 namespace {
1813 /// Kinds of declarator that cannot contain a qualified function type.
1814 ///
1815 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1816 ///     a function type with a cv-qualifier or a ref-qualifier can only appear
1817 ///     at the topmost level of a type.
1818 ///
1819 /// Parens and member pointers are permitted. We don't diagnose array and
1820 /// function declarators, because they don't allow function types at all.
1821 ///
1822 /// The values of this enum are used in diagnostics.
1823 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1824 } // end anonymous namespace
1825 
1826 /// Check whether the type T is a qualified function type, and if it is,
1827 /// diagnose that it cannot be contained within the given kind of declarator.
1828 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1829                                    QualifiedFunctionKind QFK) {
1830   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1831   const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1832   if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1833     return false;
1834 
1835   S.Diag(Loc, diag::err_compound_qualified_function_type)
1836     << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1837     << getFunctionQualifiersAsString(FPT);
1838   return true;
1839 }
1840 
1841 /// \brief Build a pointer type.
1842 ///
1843 /// \param T The type to which we'll be building a pointer.
1844 ///
1845 /// \param Loc The location of the entity whose type involves this
1846 /// pointer type or, if there is no such entity, the location of the
1847 /// type that will have pointer type.
1848 ///
1849 /// \param Entity The name of the entity that involves the pointer
1850 /// type, if known.
1851 ///
1852 /// \returns A suitable pointer type, if there are no
1853 /// errors. Otherwise, returns a NULL type.
1854 QualType Sema::BuildPointerType(QualType T,
1855                                 SourceLocation Loc, DeclarationName Entity) {
1856   if (T->isReferenceType()) {
1857     // C++ 8.3.2p4: There shall be no ... pointers to references ...
1858     Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1859       << getPrintableNameForEntity(Entity) << T;
1860     return QualType();
1861   }
1862 
1863   if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1864     return QualType();
1865 
1866   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1867 
1868   // In ARC, it is forbidden to build pointers to unqualified pointers.
1869   if (getLangOpts().ObjCAutoRefCount)
1870     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1871 
1872   // Build the pointer type.
1873   return Context.getPointerType(T);
1874 }
1875 
1876 /// \brief Build a reference type.
1877 ///
1878 /// \param T The type to which we'll be building a reference.
1879 ///
1880 /// \param Loc The location of the entity whose type involves this
1881 /// reference type or, if there is no such entity, the location of the
1882 /// type that will have reference type.
1883 ///
1884 /// \param Entity The name of the entity that involves the reference
1885 /// type, if known.
1886 ///
1887 /// \returns A suitable reference type, if there are no
1888 /// errors. Otherwise, returns a NULL type.
1889 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1890                                   SourceLocation Loc,
1891                                   DeclarationName Entity) {
1892   assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1893          "Unresolved overloaded function type");
1894 
1895   // C++0x [dcl.ref]p6:
1896   //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1897   //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1898   //   type T, an attempt to create the type "lvalue reference to cv TR" creates
1899   //   the type "lvalue reference to T", while an attempt to create the type
1900   //   "rvalue reference to cv TR" creates the type TR.
1901   bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1902 
1903   // C++ [dcl.ref]p4: There shall be no references to references.
1904   //
1905   // According to C++ DR 106, references to references are only
1906   // diagnosed when they are written directly (e.g., "int & &"),
1907   // but not when they happen via a typedef:
1908   //
1909   //   typedef int& intref;
1910   //   typedef intref& intref2;
1911   //
1912   // Parser::ParseDeclaratorInternal diagnoses the case where
1913   // references are written directly; here, we handle the
1914   // collapsing of references-to-references as described in C++0x.
1915   // DR 106 and 540 introduce reference-collapsing into C++98/03.
1916 
1917   // C++ [dcl.ref]p1:
1918   //   A declarator that specifies the type "reference to cv void"
1919   //   is ill-formed.
1920   if (T->isVoidType()) {
1921     Diag(Loc, diag::err_reference_to_void);
1922     return QualType();
1923   }
1924 
1925   if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1926     return QualType();
1927 
1928   // In ARC, it is forbidden to build references to unqualified pointers.
1929   if (getLangOpts().ObjCAutoRefCount)
1930     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1931 
1932   // Handle restrict on references.
1933   if (LValueRef)
1934     return Context.getLValueReferenceType(T, SpelledAsLValue);
1935   return Context.getRValueReferenceType(T);
1936 }
1937 
1938 /// \brief Build a Pipe type.
1939 ///
1940 /// \param T The type to which we'll be building a Pipe.
1941 ///
1942 /// \param Loc We do not use it for now.
1943 ///
1944 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1945 /// NULL type.
1946 QualType Sema::BuildPipeType(QualType T, SourceLocation Loc) {
1947   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1948 
1949   // Build the pipe type.
1950   return Context.getPipeType(T);
1951 }
1952 
1953 /// Check whether the specified array size makes the array type a VLA.  If so,
1954 /// return true, if not, return the size of the array in SizeVal.
1955 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1956   // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1957   // (like gnu99, but not c99) accept any evaluatable value as an extension.
1958   class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1959   public:
1960     VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1961 
1962     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1963     }
1964 
1965     void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
1966       S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1967     }
1968   } Diagnoser;
1969 
1970   return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1971                                            S.LangOpts.GNUMode).isInvalid();
1972 }
1973 
1974 /// \brief Build an array type.
1975 ///
1976 /// \param T The type of each element in the array.
1977 ///
1978 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1979 ///
1980 /// \param ArraySize Expression describing the size of the array.
1981 ///
1982 /// \param Brackets The range from the opening '[' to the closing ']'.
1983 ///
1984 /// \param Entity The name of the entity that involves the array
1985 /// type, if known.
1986 ///
1987 /// \returns A suitable array type, if there are no errors. Otherwise,
1988 /// returns a NULL type.
1989 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1990                               Expr *ArraySize, unsigned Quals,
1991                               SourceRange Brackets, DeclarationName Entity) {
1992 
1993   SourceLocation Loc = Brackets.getBegin();
1994   if (getLangOpts().CPlusPlus) {
1995     // C++ [dcl.array]p1:
1996     //   T is called the array element type; this type shall not be a reference
1997     //   type, the (possibly cv-qualified) type void, a function type or an
1998     //   abstract class type.
1999     //
2000     // C++ [dcl.array]p3:
2001     //   When several "array of" specifications are adjacent, [...] only the
2002     //   first of the constant expressions that specify the bounds of the arrays
2003     //   may be omitted.
2004     //
2005     // Note: function types are handled in the common path with C.
2006     if (T->isReferenceType()) {
2007       Diag(Loc, diag::err_illegal_decl_array_of_references)
2008       << getPrintableNameForEntity(Entity) << T;
2009       return QualType();
2010     }
2011 
2012     if (T->isVoidType() || T->isIncompleteArrayType()) {
2013       Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2014       return QualType();
2015     }
2016 
2017     if (RequireNonAbstractType(Brackets.getBegin(), T,
2018                                diag::err_array_of_abstract_type))
2019       return QualType();
2020 
2021     // Mentioning a member pointer type for an array type causes us to lock in
2022     // an inheritance model, even if it's inside an unused typedef.
2023     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2024       if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2025         if (!MPTy->getClass()->isDependentType())
2026           (void)isCompleteType(Loc, T);
2027 
2028   } else {
2029     // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2030     // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2031     if (RequireCompleteType(Loc, T,
2032                             diag::err_illegal_decl_array_incomplete_type))
2033       return QualType();
2034   }
2035 
2036   if (T->isFunctionType()) {
2037     Diag(Loc, diag::err_illegal_decl_array_of_functions)
2038       << getPrintableNameForEntity(Entity) << T;
2039     return QualType();
2040   }
2041 
2042   if (const RecordType *EltTy = T->getAs<RecordType>()) {
2043     // If the element type is a struct or union that contains a variadic
2044     // array, accept it as a GNU extension: C99 6.7.2.1p2.
2045     if (EltTy->getDecl()->hasFlexibleArrayMember())
2046       Diag(Loc, diag::ext_flexible_array_in_array) << T;
2047   } else if (T->isObjCObjectType()) {
2048     Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2049     return QualType();
2050   }
2051 
2052   // Do placeholder conversions on the array size expression.
2053   if (ArraySize && ArraySize->hasPlaceholderType()) {
2054     ExprResult Result = CheckPlaceholderExpr(ArraySize);
2055     if (Result.isInvalid()) return QualType();
2056     ArraySize = Result.get();
2057   }
2058 
2059   // Do lvalue-to-rvalue conversions on the array size expression.
2060   if (ArraySize && !ArraySize->isRValue()) {
2061     ExprResult Result = DefaultLvalueConversion(ArraySize);
2062     if (Result.isInvalid())
2063       return QualType();
2064 
2065     ArraySize = Result.get();
2066   }
2067 
2068   // C99 6.7.5.2p1: The size expression shall have integer type.
2069   // C++11 allows contextual conversions to such types.
2070   if (!getLangOpts().CPlusPlus11 &&
2071       ArraySize && !ArraySize->isTypeDependent() &&
2072       !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2073     Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2074       << ArraySize->getType() << ArraySize->getSourceRange();
2075     return QualType();
2076   }
2077 
2078   llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2079   if (!ArraySize) {
2080     if (ASM == ArrayType::Star)
2081       T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2082     else
2083       T = Context.getIncompleteArrayType(T, ASM, Quals);
2084   } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2085     T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2086   } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2087               !T->isConstantSizeType()) ||
2088              isArraySizeVLA(*this, ArraySize, ConstVal)) {
2089     // Even in C++11, don't allow contextual conversions in the array bound
2090     // of a VLA.
2091     if (getLangOpts().CPlusPlus11 &&
2092         !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2093       Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2094         << ArraySize->getType() << ArraySize->getSourceRange();
2095       return QualType();
2096     }
2097 
2098     // C99: an array with an element type that has a non-constant-size is a VLA.
2099     // C99: an array with a non-ICE size is a VLA.  We accept any expression
2100     // that we can fold to a non-zero positive value as an extension.
2101     T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2102   } else {
2103     // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2104     // have a value greater than zero.
2105     if (ConstVal.isSigned() && ConstVal.isNegative()) {
2106       if (Entity)
2107         Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2108           << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2109       else
2110         Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2111           << ArraySize->getSourceRange();
2112       return QualType();
2113     }
2114     if (ConstVal == 0) {
2115       // GCC accepts zero sized static arrays. We allow them when
2116       // we're not in a SFINAE context.
2117       Diag(ArraySize->getLocStart(),
2118            isSFINAEContext()? diag::err_typecheck_zero_array_size
2119                             : diag::ext_typecheck_zero_array_size)
2120         << ArraySize->getSourceRange();
2121 
2122       if (ASM == ArrayType::Static) {
2123         Diag(ArraySize->getLocStart(),
2124              diag::warn_typecheck_zero_static_array_size)
2125           << ArraySize->getSourceRange();
2126         ASM = ArrayType::Normal;
2127       }
2128     } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2129                !T->isIncompleteType() && !T->isUndeducedType()) {
2130       // Is the array too large?
2131       unsigned ActiveSizeBits
2132         = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2133       if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2134         Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2135           << ConstVal.toString(10)
2136           << ArraySize->getSourceRange();
2137         return QualType();
2138       }
2139     }
2140 
2141     T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2142   }
2143 
2144   // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2145   if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2146     Diag(Loc, diag::err_opencl_vla);
2147     return QualType();
2148   }
2149   // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2150   if (!getLangOpts().C99) {
2151     if (T->isVariableArrayType()) {
2152       // Prohibit the use of non-POD types in VLAs.
2153       QualType BaseT = Context.getBaseElementType(T);
2154       if (!T->isDependentType() && isCompleteType(Loc, BaseT) &&
2155           !BaseT.isPODType(Context) && !BaseT->isObjCLifetimeType()) {
2156         Diag(Loc, diag::err_vla_non_pod) << BaseT;
2157         return QualType();
2158       }
2159       // Prohibit the use of VLAs during template argument deduction.
2160       else if (isSFINAEContext()) {
2161         Diag(Loc, diag::err_vla_in_sfinae);
2162         return QualType();
2163       }
2164       // Just extwarn about VLAs.
2165       else
2166         Diag(Loc, diag::ext_vla);
2167     } else if (ASM != ArrayType::Normal || Quals != 0)
2168       Diag(Loc,
2169            getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2170                                   : diag::ext_c99_array_usage) << ASM;
2171   }
2172 
2173   if (T->isVariableArrayType()) {
2174     // Warn about VLAs for -Wvla.
2175     Diag(Loc, diag::warn_vla_used);
2176   }
2177 
2178   return T;
2179 }
2180 
2181 /// \brief Build an ext-vector type.
2182 ///
2183 /// Run the required checks for the extended vector type.
2184 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2185                                   SourceLocation AttrLoc) {
2186   // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2187   // in conjunction with complex types (pointers, arrays, functions, etc.).
2188   if (!T->isDependentType() &&
2189       !T->isIntegerType() && !T->isRealFloatingType()) {
2190     Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2191     return QualType();
2192   }
2193 
2194   if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2195     llvm::APSInt vecSize(32);
2196     if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2197       Diag(AttrLoc, diag::err_attribute_argument_type)
2198         << "ext_vector_type" << AANT_ArgumentIntegerConstant
2199         << ArraySize->getSourceRange();
2200       return QualType();
2201     }
2202 
2203     // unlike gcc's vector_size attribute, the size is specified as the
2204     // number of elements, not the number of bytes.
2205     unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2206 
2207     if (vectorSize == 0) {
2208       Diag(AttrLoc, diag::err_attribute_zero_size)
2209       << ArraySize->getSourceRange();
2210       return QualType();
2211     }
2212 
2213     if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2214       Diag(AttrLoc, diag::err_attribute_size_too_large)
2215         << ArraySize->getSourceRange();
2216       return QualType();
2217     }
2218 
2219     return Context.getExtVectorType(T, vectorSize);
2220   }
2221 
2222   return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2223 }
2224 
2225 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2226   if (T->isArrayType() || T->isFunctionType()) {
2227     Diag(Loc, diag::err_func_returning_array_function)
2228       << T->isFunctionType() << T;
2229     return true;
2230   }
2231 
2232   // Functions cannot return half FP.
2233   if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2234     Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2235       FixItHint::CreateInsertion(Loc, "*");
2236     return true;
2237   }
2238 
2239   // Methods cannot return interface types. All ObjC objects are
2240   // passed by reference.
2241   if (T->isObjCObjectType()) {
2242     Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
2243     return 0;
2244   }
2245 
2246   return false;
2247 }
2248 
2249 QualType Sema::BuildFunctionType(QualType T,
2250                                  MutableArrayRef<QualType> ParamTypes,
2251                                  SourceLocation Loc, DeclarationName Entity,
2252                                  const FunctionProtoType::ExtProtoInfo &EPI) {
2253   bool Invalid = false;
2254 
2255   Invalid |= CheckFunctionReturnType(T, Loc);
2256 
2257   for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2258     // FIXME: Loc is too inprecise here, should use proper locations for args.
2259     QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2260     if (ParamType->isVoidType()) {
2261       Diag(Loc, diag::err_param_with_void_type);
2262       Invalid = true;
2263     } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2264       // Disallow half FP arguments.
2265       Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2266         FixItHint::CreateInsertion(Loc, "*");
2267       Invalid = true;
2268     }
2269 
2270     ParamTypes[Idx] = ParamType;
2271   }
2272 
2273   if (Invalid)
2274     return QualType();
2275 
2276   return Context.getFunctionType(T, ParamTypes, EPI);
2277 }
2278 
2279 /// \brief Build a member pointer type \c T Class::*.
2280 ///
2281 /// \param T the type to which the member pointer refers.
2282 /// \param Class the class type into which the member pointer points.
2283 /// \param Loc the location where this type begins
2284 /// \param Entity the name of the entity that will have this member pointer type
2285 ///
2286 /// \returns a member pointer type, if successful, or a NULL type if there was
2287 /// an error.
2288 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2289                                       SourceLocation Loc,
2290                                       DeclarationName Entity) {
2291   // Verify that we're not building a pointer to pointer to function with
2292   // exception specification.
2293   if (CheckDistantExceptionSpec(T)) {
2294     Diag(Loc, diag::err_distant_exception_spec);
2295     return QualType();
2296   }
2297 
2298   // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2299   //   with reference type, or "cv void."
2300   if (T->isReferenceType()) {
2301     Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2302       << getPrintableNameForEntity(Entity) << T;
2303     return QualType();
2304   }
2305 
2306   if (T->isVoidType()) {
2307     Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2308       << getPrintableNameForEntity(Entity);
2309     return QualType();
2310   }
2311 
2312   if (!Class->isDependentType() && !Class->isRecordType()) {
2313     Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2314     return QualType();
2315   }
2316 
2317   // Adjust the default free function calling convention to the default method
2318   // calling convention.
2319   bool IsCtorOrDtor =
2320       (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2321       (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2322   if (T->isFunctionType())
2323     adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2324 
2325   return Context.getMemberPointerType(T, Class.getTypePtr());
2326 }
2327 
2328 /// \brief Build a block pointer type.
2329 ///
2330 /// \param T The type to which we'll be building a block pointer.
2331 ///
2332 /// \param Loc The source location, used for diagnostics.
2333 ///
2334 /// \param Entity The name of the entity that involves the block pointer
2335 /// type, if known.
2336 ///
2337 /// \returns A suitable block pointer type, if there are no
2338 /// errors. Otherwise, returns a NULL type.
2339 QualType Sema::BuildBlockPointerType(QualType T,
2340                                      SourceLocation Loc,
2341                                      DeclarationName Entity) {
2342   if (!T->isFunctionType()) {
2343     Diag(Loc, diag::err_nonfunction_block_type);
2344     return QualType();
2345   }
2346 
2347   if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2348     return QualType();
2349 
2350   return Context.getBlockPointerType(T);
2351 }
2352 
2353 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2354   QualType QT = Ty.get();
2355   if (QT.isNull()) {
2356     if (TInfo) *TInfo = nullptr;
2357     return QualType();
2358   }
2359 
2360   TypeSourceInfo *DI = nullptr;
2361   if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2362     QT = LIT->getType();
2363     DI = LIT->getTypeSourceInfo();
2364   }
2365 
2366   if (TInfo) *TInfo = DI;
2367   return QT;
2368 }
2369 
2370 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2371                                             Qualifiers::ObjCLifetime ownership,
2372                                             unsigned chunkIndex);
2373 
2374 /// Given that this is the declaration of a parameter under ARC,
2375 /// attempt to infer attributes and such for pointer-to-whatever
2376 /// types.
2377 static void inferARCWriteback(TypeProcessingState &state,
2378                               QualType &declSpecType) {
2379   Sema &S = state.getSema();
2380   Declarator &declarator = state.getDeclarator();
2381 
2382   // TODO: should we care about decl qualifiers?
2383 
2384   // Check whether the declarator has the expected form.  We walk
2385   // from the inside out in order to make the block logic work.
2386   unsigned outermostPointerIndex = 0;
2387   bool isBlockPointer = false;
2388   unsigned numPointers = 0;
2389   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2390     unsigned chunkIndex = i;
2391     DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2392     switch (chunk.Kind) {
2393     case DeclaratorChunk::Paren:
2394       // Ignore parens.
2395       break;
2396 
2397     case DeclaratorChunk::Reference:
2398     case DeclaratorChunk::Pointer:
2399       // Count the number of pointers.  Treat references
2400       // interchangeably as pointers; if they're mis-ordered, normal
2401       // type building will discover that.
2402       outermostPointerIndex = chunkIndex;
2403       numPointers++;
2404       break;
2405 
2406     case DeclaratorChunk::BlockPointer:
2407       // If we have a pointer to block pointer, that's an acceptable
2408       // indirect reference; anything else is not an application of
2409       // the rules.
2410       if (numPointers != 1) return;
2411       numPointers++;
2412       outermostPointerIndex = chunkIndex;
2413       isBlockPointer = true;
2414 
2415       // We don't care about pointer structure in return values here.
2416       goto done;
2417 
2418     case DeclaratorChunk::Array: // suppress if written (id[])?
2419     case DeclaratorChunk::Function:
2420     case DeclaratorChunk::MemberPointer:
2421     case DeclaratorChunk::Pipe:
2422       return;
2423     }
2424   }
2425  done:
2426 
2427   // If we have *one* pointer, then we want to throw the qualifier on
2428   // the declaration-specifiers, which means that it needs to be a
2429   // retainable object type.
2430   if (numPointers == 1) {
2431     // If it's not a retainable object type, the rule doesn't apply.
2432     if (!declSpecType->isObjCRetainableType()) return;
2433 
2434     // If it already has lifetime, don't do anything.
2435     if (declSpecType.getObjCLifetime()) return;
2436 
2437     // Otherwise, modify the type in-place.
2438     Qualifiers qs;
2439 
2440     if (declSpecType->isObjCARCImplicitlyUnretainedType())
2441       qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2442     else
2443       qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2444     declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2445 
2446   // If we have *two* pointers, then we want to throw the qualifier on
2447   // the outermost pointer.
2448   } else if (numPointers == 2) {
2449     // If we don't have a block pointer, we need to check whether the
2450     // declaration-specifiers gave us something that will turn into a
2451     // retainable object pointer after we slap the first pointer on it.
2452     if (!isBlockPointer && !declSpecType->isObjCObjectType())
2453       return;
2454 
2455     // Look for an explicit lifetime attribute there.
2456     DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2457     if (chunk.Kind != DeclaratorChunk::Pointer &&
2458         chunk.Kind != DeclaratorChunk::BlockPointer)
2459       return;
2460     for (const AttributeList *attr = chunk.getAttrs(); attr;
2461            attr = attr->getNext())
2462       if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2463         return;
2464 
2465     transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2466                                           outermostPointerIndex);
2467 
2468   // Any other number of pointers/references does not trigger the rule.
2469   } else return;
2470 
2471   // TODO: mark whether we did this inference?
2472 }
2473 
2474 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2475                                      SourceLocation FallbackLoc,
2476                                      SourceLocation ConstQualLoc,
2477                                      SourceLocation VolatileQualLoc,
2478                                      SourceLocation RestrictQualLoc,
2479                                      SourceLocation AtomicQualLoc) {
2480   if (!Quals)
2481     return;
2482 
2483   struct Qual {
2484     const char *Name;
2485     unsigned Mask;
2486     SourceLocation Loc;
2487   } const QualKinds[4] = {
2488     { "const", DeclSpec::TQ_const, ConstQualLoc },
2489     { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2490     { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2491     { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2492   };
2493 
2494   SmallString<32> QualStr;
2495   unsigned NumQuals = 0;
2496   SourceLocation Loc;
2497   FixItHint FixIts[4];
2498 
2499   // Build a string naming the redundant qualifiers.
2500   for (unsigned I = 0; I != 4; ++I) {
2501     if (Quals & QualKinds[I].Mask) {
2502       if (!QualStr.empty()) QualStr += ' ';
2503       QualStr += QualKinds[I].Name;
2504 
2505       // If we have a location for the qualifier, offer a fixit.
2506       SourceLocation QualLoc = QualKinds[I].Loc;
2507       if (QualLoc.isValid()) {
2508         FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2509         if (Loc.isInvalid() ||
2510             getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2511           Loc = QualLoc;
2512       }
2513 
2514       ++NumQuals;
2515     }
2516   }
2517 
2518   Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2519     << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2520 }
2521 
2522 // Diagnose pointless type qualifiers on the return type of a function.
2523 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2524                                                   Declarator &D,
2525                                                   unsigned FunctionChunkIndex) {
2526   if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2527     // FIXME: TypeSourceInfo doesn't preserve location information for
2528     // qualifiers.
2529     S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2530                                 RetTy.getLocalCVRQualifiers(),
2531                                 D.getIdentifierLoc());
2532     return;
2533   }
2534 
2535   for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2536                 End = D.getNumTypeObjects();
2537        OuterChunkIndex != End; ++OuterChunkIndex) {
2538     DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2539     switch (OuterChunk.Kind) {
2540     case DeclaratorChunk::Paren:
2541       continue;
2542 
2543     case DeclaratorChunk::Pointer: {
2544       DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2545       S.diagnoseIgnoredQualifiers(
2546           diag::warn_qual_return_type,
2547           PTI.TypeQuals,
2548           SourceLocation(),
2549           SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2550           SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2551           SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2552           SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc));
2553       return;
2554     }
2555 
2556     case DeclaratorChunk::Function:
2557     case DeclaratorChunk::BlockPointer:
2558     case DeclaratorChunk::Reference:
2559     case DeclaratorChunk::Array:
2560     case DeclaratorChunk::MemberPointer:
2561     case DeclaratorChunk::Pipe:
2562       // FIXME: We can't currently provide an accurate source location and a
2563       // fix-it hint for these.
2564       unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2565       S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2566                                   RetTy.getCVRQualifiers() | AtomicQual,
2567                                   D.getIdentifierLoc());
2568       return;
2569     }
2570 
2571     llvm_unreachable("unknown declarator chunk kind");
2572   }
2573 
2574   // If the qualifiers come from a conversion function type, don't diagnose
2575   // them -- they're not necessarily redundant, since such a conversion
2576   // operator can be explicitly called as "x.operator const int()".
2577   if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2578     return;
2579 
2580   // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2581   // which are present there.
2582   S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2583                               D.getDeclSpec().getTypeQualifiers(),
2584                               D.getIdentifierLoc(),
2585                               D.getDeclSpec().getConstSpecLoc(),
2586                               D.getDeclSpec().getVolatileSpecLoc(),
2587                               D.getDeclSpec().getRestrictSpecLoc(),
2588                               D.getDeclSpec().getAtomicSpecLoc());
2589 }
2590 
2591 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2592                                              TypeSourceInfo *&ReturnTypeInfo) {
2593   Sema &SemaRef = state.getSema();
2594   Declarator &D = state.getDeclarator();
2595   QualType T;
2596   ReturnTypeInfo = nullptr;
2597 
2598   // The TagDecl owned by the DeclSpec.
2599   TagDecl *OwnedTagDecl = nullptr;
2600 
2601   switch (D.getName().getKind()) {
2602   case UnqualifiedId::IK_ImplicitSelfParam:
2603   case UnqualifiedId::IK_OperatorFunctionId:
2604   case UnqualifiedId::IK_Identifier:
2605   case UnqualifiedId::IK_LiteralOperatorId:
2606   case UnqualifiedId::IK_TemplateId:
2607     T = ConvertDeclSpecToType(state);
2608 
2609     if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2610       OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2611       // Owned declaration is embedded in declarator.
2612       OwnedTagDecl->setEmbeddedInDeclarator(true);
2613     }
2614     break;
2615 
2616   case UnqualifiedId::IK_ConstructorName:
2617   case UnqualifiedId::IK_ConstructorTemplateId:
2618   case UnqualifiedId::IK_DestructorName:
2619     // Constructors and destructors don't have return types. Use
2620     // "void" instead.
2621     T = SemaRef.Context.VoidTy;
2622     processTypeAttrs(state, T, TAL_DeclSpec,
2623                      D.getDeclSpec().getAttributes().getList());
2624     break;
2625 
2626   case UnqualifiedId::IK_ConversionFunctionId:
2627     // The result type of a conversion function is the type that it
2628     // converts to.
2629     T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2630                                   &ReturnTypeInfo);
2631     break;
2632   }
2633 
2634   if (D.getAttributes())
2635     distributeTypeAttrsFromDeclarator(state, T);
2636 
2637   // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2638   if (D.getDeclSpec().containsPlaceholderType()) {
2639     int Error = -1;
2640 
2641     switch (D.getContext()) {
2642     case Declarator::LambdaExprContext:
2643       llvm_unreachable("Can't specify a type specifier in lambda grammar");
2644     case Declarator::ObjCParameterContext:
2645     case Declarator::ObjCResultContext:
2646     case Declarator::PrototypeContext:
2647       Error = 0;
2648       break;
2649     case Declarator::LambdaExprParameterContext:
2650       // In C++14, generic lambdas allow 'auto' in their parameters.
2651       if (!(SemaRef.getLangOpts().CPlusPlus14
2652               && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2653         Error = 16;
2654       break;
2655     case Declarator::MemberContext: {
2656       if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2657           D.isFunctionDeclarator())
2658         break;
2659       bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2660       switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2661       case TTK_Enum: llvm_unreachable("unhandled tag kind");
2662       case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2663       case TTK_Union:  Error = Cxx ? 3 : 4; /* Union member */ break;
2664       case TTK_Class:  Error = 5; /* Class member */ break;
2665       case TTK_Interface: Error = 6; /* Interface member */ break;
2666       }
2667       break;
2668     }
2669     case Declarator::CXXCatchContext:
2670     case Declarator::ObjCCatchContext:
2671       Error = 7; // Exception declaration
2672       break;
2673     case Declarator::TemplateParamContext:
2674       Error = 8; // Template parameter
2675       break;
2676     case Declarator::BlockLiteralContext:
2677       Error = 9; // Block literal
2678       break;
2679     case Declarator::TemplateTypeArgContext:
2680       Error = 10; // Template type argument
2681       break;
2682     case Declarator::AliasDeclContext:
2683     case Declarator::AliasTemplateContext:
2684       Error = 12; // Type alias
2685       break;
2686     case Declarator::TrailingReturnContext:
2687       if (!SemaRef.getLangOpts().CPlusPlus14 ||
2688           D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2689         Error = 13; // Function return type
2690       break;
2691     case Declarator::ConversionIdContext:
2692       if (!SemaRef.getLangOpts().CPlusPlus14 ||
2693           D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2694         Error = 14; // conversion-type-id
2695       break;
2696     case Declarator::TypeNameContext:
2697       Error = 15; // Generic
2698       break;
2699     case Declarator::FileContext:
2700     case Declarator::BlockContext:
2701     case Declarator::ForContext:
2702     case Declarator::ConditionContext:
2703       break;
2704     case Declarator::CXXNewContext:
2705       if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2706         Error = 17; // 'new' type
2707       break;
2708     case Declarator::KNRTypeListContext:
2709       Error = 18; // K&R function parameter
2710       break;
2711     }
2712 
2713     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2714       Error = 11;
2715 
2716     // In Objective-C it is an error to use 'auto' on a function declarator
2717     // (and everywhere for '__auto_type').
2718     if (D.isFunctionDeclarator() &&
2719         (!SemaRef.getLangOpts().CPlusPlus11 ||
2720          D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type))
2721       Error = 13;
2722 
2723     bool HaveTrailing = false;
2724 
2725     // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2726     // contains a trailing return type. That is only legal at the outermost
2727     // level. Check all declarator chunks (outermost first) anyway, to give
2728     // better diagnostics.
2729     // We don't support '__auto_type' with trailing return types.
2730     if (SemaRef.getLangOpts().CPlusPlus11 &&
2731         D.getDeclSpec().getTypeSpecType() != DeclSpec::TST_auto_type) {
2732       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2733         unsigned chunkIndex = e - i - 1;
2734         state.setCurrentChunkIndex(chunkIndex);
2735         DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2736         if (DeclType.Kind == DeclaratorChunk::Function) {
2737           const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2738           if (FTI.hasTrailingReturnType()) {
2739             HaveTrailing = true;
2740             Error = -1;
2741             break;
2742           }
2743         }
2744       }
2745     }
2746 
2747     SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2748     if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2749       AutoRange = D.getName().getSourceRange();
2750 
2751     if (Error != -1) {
2752       unsigned Keyword;
2753       switch (D.getDeclSpec().getTypeSpecType()) {
2754       case DeclSpec::TST_auto: Keyword = 0; break;
2755       case DeclSpec::TST_decltype_auto: Keyword = 1; break;
2756       case DeclSpec::TST_auto_type: Keyword = 2; break;
2757       default: llvm_unreachable("unknown auto TypeSpecType");
2758       }
2759       SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2760         << Keyword << Error << AutoRange;
2761       T = SemaRef.Context.IntTy;
2762       D.setInvalidType(true);
2763     } else if (!HaveTrailing) {
2764       // If there was a trailing return type, we already got
2765       // warn_cxx98_compat_trailing_return_type in the parser.
2766       SemaRef.Diag(AutoRange.getBegin(),
2767                    diag::warn_cxx98_compat_auto_type_specifier)
2768         << AutoRange;
2769     }
2770   }
2771 
2772   if (SemaRef.getLangOpts().CPlusPlus &&
2773       OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2774     // Check the contexts where C++ forbids the declaration of a new class
2775     // or enumeration in a type-specifier-seq.
2776     unsigned DiagID = 0;
2777     switch (D.getContext()) {
2778     case Declarator::TrailingReturnContext:
2779       // Class and enumeration definitions are syntactically not allowed in
2780       // trailing return types.
2781       llvm_unreachable("parser should not have allowed this");
2782       break;
2783     case Declarator::FileContext:
2784     case Declarator::MemberContext:
2785     case Declarator::BlockContext:
2786     case Declarator::ForContext:
2787     case Declarator::BlockLiteralContext:
2788     case Declarator::LambdaExprContext:
2789       // C++11 [dcl.type]p3:
2790       //   A type-specifier-seq shall not define a class or enumeration unless
2791       //   it appears in the type-id of an alias-declaration (7.1.3) that is not
2792       //   the declaration of a template-declaration.
2793     case Declarator::AliasDeclContext:
2794       break;
2795     case Declarator::AliasTemplateContext:
2796       DiagID = diag::err_type_defined_in_alias_template;
2797       break;
2798     case Declarator::TypeNameContext:
2799     case Declarator::ConversionIdContext:
2800     case Declarator::TemplateParamContext:
2801     case Declarator::CXXNewContext:
2802     case Declarator::CXXCatchContext:
2803     case Declarator::ObjCCatchContext:
2804     case Declarator::TemplateTypeArgContext:
2805       DiagID = diag::err_type_defined_in_type_specifier;
2806       break;
2807     case Declarator::PrototypeContext:
2808     case Declarator::LambdaExprParameterContext:
2809     case Declarator::ObjCParameterContext:
2810     case Declarator::ObjCResultContext:
2811     case Declarator::KNRTypeListContext:
2812       // C++ [dcl.fct]p6:
2813       //   Types shall not be defined in return or parameter types.
2814       DiagID = diag::err_type_defined_in_param_type;
2815       break;
2816     case Declarator::ConditionContext:
2817       // C++ 6.4p2:
2818       // The type-specifier-seq shall not contain typedef and shall not declare
2819       // a new class or enumeration.
2820       DiagID = diag::err_type_defined_in_condition;
2821       break;
2822     }
2823 
2824     if (DiagID != 0) {
2825       SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
2826           << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2827       D.setInvalidType(true);
2828     }
2829   }
2830 
2831   assert(!T.isNull() && "This function should not return a null type");
2832   return T;
2833 }
2834 
2835 /// Produce an appropriate diagnostic for an ambiguity between a function
2836 /// declarator and a C++ direct-initializer.
2837 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2838                                        DeclaratorChunk &DeclType, QualType RT) {
2839   const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2840   assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2841 
2842   // If the return type is void there is no ambiguity.
2843   if (RT->isVoidType())
2844     return;
2845 
2846   // An initializer for a non-class type can have at most one argument.
2847   if (!RT->isRecordType() && FTI.NumParams > 1)
2848     return;
2849 
2850   // An initializer for a reference must have exactly one argument.
2851   if (RT->isReferenceType() && FTI.NumParams != 1)
2852     return;
2853 
2854   // Only warn if this declarator is declaring a function at block scope, and
2855   // doesn't have a storage class (such as 'extern') specified.
2856   if (!D.isFunctionDeclarator() ||
2857       D.getFunctionDefinitionKind() != FDK_Declaration ||
2858       !S.CurContext->isFunctionOrMethod() ||
2859       D.getDeclSpec().getStorageClassSpec()
2860         != DeclSpec::SCS_unspecified)
2861     return;
2862 
2863   // Inside a condition, a direct initializer is not permitted. We allow one to
2864   // be parsed in order to give better diagnostics in condition parsing.
2865   if (D.getContext() == Declarator::ConditionContext)
2866     return;
2867 
2868   SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2869 
2870   S.Diag(DeclType.Loc,
2871          FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
2872                        : diag::warn_empty_parens_are_function_decl)
2873       << ParenRange;
2874 
2875   // If the declaration looks like:
2876   //   T var1,
2877   //   f();
2878   // and name lookup finds a function named 'f', then the ',' was
2879   // probably intended to be a ';'.
2880   if (!D.isFirstDeclarator() && D.getIdentifier()) {
2881     FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2882     FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2883     if (Comma.getFileID() != Name.getFileID() ||
2884         Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2885       LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2886                           Sema::LookupOrdinaryName);
2887       if (S.LookupName(Result, S.getCurScope()))
2888         S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2889           << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2890           << D.getIdentifier();
2891     }
2892   }
2893 
2894   if (FTI.NumParams > 0) {
2895     // For a declaration with parameters, eg. "T var(T());", suggest adding
2896     // parens around the first parameter to turn the declaration into a
2897     // variable declaration.
2898     SourceRange Range = FTI.Params[0].Param->getSourceRange();
2899     SourceLocation B = Range.getBegin();
2900     SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
2901     // FIXME: Maybe we should suggest adding braces instead of parens
2902     // in C++11 for classes that don't have an initializer_list constructor.
2903     S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2904       << FixItHint::CreateInsertion(B, "(")
2905       << FixItHint::CreateInsertion(E, ")");
2906   } else {
2907     // For a declaration without parameters, eg. "T var();", suggest replacing
2908     // the parens with an initializer to turn the declaration into a variable
2909     // declaration.
2910     const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
2911 
2912     // Empty parens mean value-initialization, and no parens mean
2913     // default initialization. These are equivalent if the default
2914     // constructor is user-provided or if zero-initialization is a
2915     // no-op.
2916     if (RD && RD->hasDefinition() &&
2917         (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2918       S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2919         << FixItHint::CreateRemoval(ParenRange);
2920     else {
2921       std::string Init =
2922           S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
2923       if (Init.empty() && S.LangOpts.CPlusPlus11)
2924         Init = "{}";
2925       if (!Init.empty())
2926         S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2927           << FixItHint::CreateReplacement(ParenRange, Init);
2928     }
2929   }
2930 }
2931 
2932 /// Helper for figuring out the default CC for a function declarator type.  If
2933 /// this is the outermost chunk, then we can determine the CC from the
2934 /// declarator context.  If not, then this could be either a member function
2935 /// type or normal function type.
2936 static CallingConv
2937 getCCForDeclaratorChunk(Sema &S, Declarator &D,
2938                         const DeclaratorChunk::FunctionTypeInfo &FTI,
2939                         unsigned ChunkIndex) {
2940   assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
2941 
2942   bool IsCXXInstanceMethod = false;
2943 
2944   if (S.getLangOpts().CPlusPlus) {
2945     // Look inwards through parentheses to see if this chunk will form a
2946     // member pointer type or if we're the declarator.  Any type attributes
2947     // between here and there will override the CC we choose here.
2948     unsigned I = ChunkIndex;
2949     bool FoundNonParen = false;
2950     while (I && !FoundNonParen) {
2951       --I;
2952       if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
2953         FoundNonParen = true;
2954     }
2955 
2956     if (FoundNonParen) {
2957       // If we're not the declarator, we're a regular function type unless we're
2958       // in a member pointer.
2959       IsCXXInstanceMethod =
2960           D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
2961     } else if (D.getContext() == Declarator::LambdaExprContext) {
2962       // This can only be a call operator for a lambda, which is an instance
2963       // method.
2964       IsCXXInstanceMethod = true;
2965     } else {
2966       // We're the innermost decl chunk, so must be a function declarator.
2967       assert(D.isFunctionDeclarator());
2968 
2969       // If we're inside a record, we're declaring a method, but it could be
2970       // explicitly or implicitly static.
2971       IsCXXInstanceMethod =
2972           D.isFirstDeclarationOfMember() &&
2973           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
2974           !D.isStaticMember();
2975     }
2976   }
2977 
2978   CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
2979                                                          IsCXXInstanceMethod);
2980 
2981   // Attribute AT_OpenCLKernel affects the calling convention only on
2982   // the SPIR target, hence it cannot be treated as a calling
2983   // convention attribute. This is the simplest place to infer
2984   // "spir_kernel" for OpenCL kernels on SPIR.
2985   if (CC == CC_SpirFunction) {
2986     for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
2987          Attr; Attr = Attr->getNext()) {
2988       if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
2989         CC = CC_SpirKernel;
2990         break;
2991       }
2992     }
2993   }
2994 
2995   return CC;
2996 }
2997 
2998 namespace {
2999   /// A simple notion of pointer kinds, which matches up with the various
3000   /// pointer declarators.
3001   enum class SimplePointerKind {
3002     Pointer,
3003     BlockPointer,
3004     MemberPointer,
3005   };
3006 } // end anonymous namespace
3007 
3008 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3009   switch (nullability) {
3010   case NullabilityKind::NonNull:
3011     if (!Ident__Nonnull)
3012       Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3013     return Ident__Nonnull;
3014 
3015   case NullabilityKind::Nullable:
3016     if (!Ident__Nullable)
3017       Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3018     return Ident__Nullable;
3019 
3020   case NullabilityKind::Unspecified:
3021     if (!Ident__Null_unspecified)
3022       Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3023     return Ident__Null_unspecified;
3024   }
3025   llvm_unreachable("Unknown nullability kind.");
3026 }
3027 
3028 /// Retrieve the identifier "NSError".
3029 IdentifierInfo *Sema::getNSErrorIdent() {
3030   if (!Ident_NSError)
3031     Ident_NSError = PP.getIdentifierInfo("NSError");
3032 
3033   return Ident_NSError;
3034 }
3035 
3036 /// Check whether there is a nullability attribute of any kind in the given
3037 /// attribute list.
3038 static bool hasNullabilityAttr(const AttributeList *attrs) {
3039   for (const AttributeList *attr = attrs; attr;
3040        attr = attr->getNext()) {
3041     if (attr->getKind() == AttributeList::AT_TypeNonNull ||
3042         attr->getKind() == AttributeList::AT_TypeNullable ||
3043         attr->getKind() == AttributeList::AT_TypeNullUnspecified)
3044       return true;
3045   }
3046 
3047   return false;
3048 }
3049 
3050 namespace {
3051   /// Describes the kind of a pointer a declarator describes.
3052   enum class PointerDeclaratorKind {
3053     // Not a pointer.
3054     NonPointer,
3055     // Single-level pointer.
3056     SingleLevelPointer,
3057     // Multi-level pointer (of any pointer kind).
3058     MultiLevelPointer,
3059     // CFFooRef*
3060     MaybePointerToCFRef,
3061     // CFErrorRef*
3062     CFErrorRefPointer,
3063     // NSError**
3064     NSErrorPointerPointer,
3065   };
3066 } // end anonymous namespace
3067 
3068 /// Classify the given declarator, whose type-specified is \c type, based on
3069 /// what kind of pointer it refers to.
3070 ///
3071 /// This is used to determine the default nullability.
3072 static PointerDeclaratorKind classifyPointerDeclarator(Sema &S,
3073                                                        QualType type,
3074                                                        Declarator &declarator) {
3075   unsigned numNormalPointers = 0;
3076 
3077   // For any dependent type, we consider it a non-pointer.
3078   if (type->isDependentType())
3079     return PointerDeclaratorKind::NonPointer;
3080 
3081   // Look through the declarator chunks to identify pointers.
3082   for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3083     DeclaratorChunk &chunk = declarator.getTypeObject(i);
3084     switch (chunk.Kind) {
3085     case DeclaratorChunk::Array:
3086     case DeclaratorChunk::Function:
3087     case DeclaratorChunk::Pipe:
3088       break;
3089 
3090     case DeclaratorChunk::BlockPointer:
3091     case DeclaratorChunk::MemberPointer:
3092       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3093                                    : PointerDeclaratorKind::SingleLevelPointer;
3094 
3095     case DeclaratorChunk::Paren:
3096     case DeclaratorChunk::Reference:
3097       continue;
3098 
3099     case DeclaratorChunk::Pointer:
3100       ++numNormalPointers;
3101       if (numNormalPointers > 2)
3102         return PointerDeclaratorKind::MultiLevelPointer;
3103       continue;
3104     }
3105   }
3106 
3107   // Then, dig into the type specifier itself.
3108   unsigned numTypeSpecifierPointers = 0;
3109   do {
3110     // Decompose normal pointers.
3111     if (auto ptrType = type->getAs<PointerType>()) {
3112       ++numNormalPointers;
3113 
3114       if (numNormalPointers > 2)
3115         return PointerDeclaratorKind::MultiLevelPointer;
3116 
3117       type = ptrType->getPointeeType();
3118       ++numTypeSpecifierPointers;
3119       continue;
3120     }
3121 
3122     // Decompose block pointers.
3123     if (type->getAs<BlockPointerType>()) {
3124       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3125                                    : PointerDeclaratorKind::SingleLevelPointer;
3126     }
3127 
3128     // Decompose member pointers.
3129     if (type->getAs<MemberPointerType>()) {
3130       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3131                                    : PointerDeclaratorKind::SingleLevelPointer;
3132     }
3133 
3134     // Look at Objective-C object pointers.
3135     if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3136       ++numNormalPointers;
3137       ++numTypeSpecifierPointers;
3138 
3139       // If this is NSError**, report that.
3140       if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3141         if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3142             numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3143           return PointerDeclaratorKind::NSErrorPointerPointer;
3144         }
3145       }
3146 
3147       break;
3148     }
3149 
3150     // Look at Objective-C class types.
3151     if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3152       if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3153         if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3154           return PointerDeclaratorKind::NSErrorPointerPointer;;
3155       }
3156 
3157       break;
3158     }
3159 
3160     // If at this point we haven't seen a pointer, we won't see one.
3161     if (numNormalPointers == 0)
3162       return PointerDeclaratorKind::NonPointer;
3163 
3164     if (auto recordType = type->getAs<RecordType>()) {
3165       RecordDecl *recordDecl = recordType->getDecl();
3166 
3167       bool isCFError = false;
3168       if (S.CFError) {
3169         // If we already know about CFError, test it directly.
3170         isCFError = (S.CFError == recordDecl);
3171       } else {
3172         // Check whether this is CFError, which we identify based on its bridge
3173         // to NSError.
3174         if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3175           if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) {
3176             if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) {
3177               S.CFError = recordDecl;
3178               isCFError = true;
3179             }
3180           }
3181         }
3182       }
3183 
3184       // If this is CFErrorRef*, report it as such.
3185       if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3186         return PointerDeclaratorKind::CFErrorRefPointer;
3187       }
3188       break;
3189     }
3190 
3191     break;
3192   } while (true);
3193 
3194   switch (numNormalPointers) {
3195   case 0:
3196     return PointerDeclaratorKind::NonPointer;
3197 
3198   case 1:
3199     return PointerDeclaratorKind::SingleLevelPointer;
3200 
3201   case 2:
3202     return PointerDeclaratorKind::MaybePointerToCFRef;
3203 
3204   default:
3205     return PointerDeclaratorKind::MultiLevelPointer;
3206   }
3207 }
3208 
3209 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
3210                                                     SourceLocation loc) {
3211   // If we're anywhere in a function, method, or closure context, don't perform
3212   // completeness checks.
3213   for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3214     if (ctx->isFunctionOrMethod())
3215       return FileID();
3216 
3217     if (ctx->isFileContext())
3218       break;
3219   }
3220 
3221   // We only care about the expansion location.
3222   loc = S.SourceMgr.getExpansionLoc(loc);
3223   FileID file = S.SourceMgr.getFileID(loc);
3224   if (file.isInvalid())
3225     return FileID();
3226 
3227   // Retrieve file information.
3228   bool invalid = false;
3229   const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3230   if (invalid || !sloc.isFile())
3231     return FileID();
3232 
3233   // We don't want to perform completeness checks on the main file or in
3234   // system headers.
3235   const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3236   if (fileInfo.getIncludeLoc().isInvalid())
3237     return FileID();
3238   if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3239       S.Diags.getSuppressSystemWarnings()) {
3240     return FileID();
3241   }
3242 
3243   return file;
3244 }
3245 
3246 /// Check for consistent use of nullability.
3247 static void checkNullabilityConsistency(TypeProcessingState &state,
3248                                         SimplePointerKind pointerKind,
3249                                         SourceLocation pointerLoc) {
3250   Sema &S = state.getSema();
3251 
3252   // Determine which file we're performing consistency checking for.
3253   FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3254   if (file.isInvalid())
3255     return;
3256 
3257   // If we haven't seen any type nullability in this file, we won't warn now
3258   // about anything.
3259   FileNullability &fileNullability = S.NullabilityMap[file];
3260   if (!fileNullability.SawTypeNullability) {
3261     // If this is the first pointer declarator in the file, record it.
3262     if (fileNullability.PointerLoc.isInvalid() &&
3263         !S.Context.getDiagnostics().isIgnored(diag::warn_nullability_missing,
3264                                               pointerLoc)) {
3265       fileNullability.PointerLoc = pointerLoc;
3266       fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3267     }
3268 
3269     return;
3270   }
3271 
3272   // Complain about missing nullability.
3273   S.Diag(pointerLoc, diag::warn_nullability_missing)
3274     << static_cast<unsigned>(pointerKind);
3275 }
3276 
3277 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3278                                                 QualType declSpecType,
3279                                                 TypeSourceInfo *TInfo) {
3280   // The TypeSourceInfo that this function returns will not be a null type.
3281   // If there is an error, this function will fill in a dummy type as fallback.
3282   QualType T = declSpecType;
3283   Declarator &D = state.getDeclarator();
3284   Sema &S = state.getSema();
3285   ASTContext &Context = S.Context;
3286   const LangOptions &LangOpts = S.getLangOpts();
3287 
3288   // The name we're declaring, if any.
3289   DeclarationName Name;
3290   if (D.getIdentifier())
3291     Name = D.getIdentifier();
3292 
3293   // Does this declaration declare a typedef-name?
3294   bool IsTypedefName =
3295     D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
3296     D.getContext() == Declarator::AliasDeclContext ||
3297     D.getContext() == Declarator::AliasTemplateContext;
3298 
3299   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3300   bool IsQualifiedFunction = T->isFunctionProtoType() &&
3301       (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3302        T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3303 
3304   // If T is 'decltype(auto)', the only declarators we can have are parens
3305   // and at most one function declarator if this is a function declaration.
3306   if (const AutoType *AT = T->getAs<AutoType>()) {
3307     if (AT->isDecltypeAuto()) {
3308       for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3309         unsigned Index = E - I - 1;
3310         DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3311         unsigned DiagId = diag::err_decltype_auto_compound_type;
3312         unsigned DiagKind = 0;
3313         switch (DeclChunk.Kind) {
3314         case DeclaratorChunk::Paren:
3315           continue;
3316         case DeclaratorChunk::Function: {
3317           unsigned FnIndex;
3318           if (D.isFunctionDeclarationContext() &&
3319               D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3320             continue;
3321           DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3322           break;
3323         }
3324         case DeclaratorChunk::Pointer:
3325         case DeclaratorChunk::BlockPointer:
3326         case DeclaratorChunk::MemberPointer:
3327           DiagKind = 0;
3328           break;
3329         case DeclaratorChunk::Reference:
3330           DiagKind = 1;
3331           break;
3332         case DeclaratorChunk::Array:
3333           DiagKind = 2;
3334           break;
3335         case DeclaratorChunk::Pipe:
3336           break;
3337         }
3338 
3339         S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3340         D.setInvalidType(true);
3341         break;
3342       }
3343     }
3344   }
3345 
3346   // Determine whether we should infer _Nonnull on pointer types.
3347   Optional<NullabilityKind> inferNullability;
3348   bool inferNullabilityCS = false;
3349   bool inferNullabilityInnerOnly = false;
3350   bool inferNullabilityInnerOnlyComplete = false;
3351 
3352   // Are we in an assume-nonnull region?
3353   bool inAssumeNonNullRegion = false;
3354   if (S.PP.getPragmaAssumeNonNullLoc().isValid()) {
3355     inAssumeNonNullRegion = true;
3356     // Determine which file we saw the assume-nonnull region in.
3357     FileID file = getNullabilityCompletenessCheckFileID(
3358                     S, S.PP.getPragmaAssumeNonNullLoc());
3359     if (file.isValid()) {
3360       FileNullability &fileNullability = S.NullabilityMap[file];
3361 
3362       // If we haven't seen any type nullability before, now we have.
3363       if (!fileNullability.SawTypeNullability) {
3364         if (fileNullability.PointerLoc.isValid()) {
3365           S.Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
3366             << static_cast<unsigned>(fileNullability.PointerKind);
3367         }
3368 
3369         fileNullability.SawTypeNullability = true;
3370       }
3371     }
3372   }
3373 
3374   // Whether to complain about missing nullability specifiers or not.
3375   enum {
3376     /// Never complain.
3377     CAMN_No,
3378     /// Complain on the inner pointers (but not the outermost
3379     /// pointer).
3380     CAMN_InnerPointers,
3381     /// Complain about any pointers that don't have nullability
3382     /// specified or inferred.
3383     CAMN_Yes
3384   } complainAboutMissingNullability = CAMN_No;
3385   unsigned NumPointersRemaining = 0;
3386 
3387   if (IsTypedefName) {
3388     // For typedefs, we do not infer any nullability (the default),
3389     // and we only complain about missing nullability specifiers on
3390     // inner pointers.
3391     complainAboutMissingNullability = CAMN_InnerPointers;
3392 
3393     if (T->canHaveNullability() && !T->getNullability(S.Context)) {
3394       ++NumPointersRemaining;
3395     }
3396 
3397     for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3398       DeclaratorChunk &chunk = D.getTypeObject(i);
3399       switch (chunk.Kind) {
3400       case DeclaratorChunk::Array:
3401       case DeclaratorChunk::Function:
3402       case DeclaratorChunk::Pipe:
3403         break;
3404 
3405       case DeclaratorChunk::BlockPointer:
3406       case DeclaratorChunk::MemberPointer:
3407         ++NumPointersRemaining;
3408         break;
3409 
3410       case DeclaratorChunk::Paren:
3411       case DeclaratorChunk::Reference:
3412         continue;
3413 
3414       case DeclaratorChunk::Pointer:
3415         ++NumPointersRemaining;
3416         continue;
3417       }
3418     }
3419   } else {
3420     bool isFunctionOrMethod = false;
3421     switch (auto context = state.getDeclarator().getContext()) {
3422     case Declarator::ObjCParameterContext:
3423     case Declarator::ObjCResultContext:
3424     case Declarator::PrototypeContext:
3425     case Declarator::TrailingReturnContext:
3426       isFunctionOrMethod = true;
3427       // fallthrough
3428 
3429     case Declarator::MemberContext:
3430       if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3431         complainAboutMissingNullability = CAMN_No;
3432         break;
3433       }
3434 
3435       // Weak properties are inferred to be nullable.
3436       if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
3437         inferNullability = NullabilityKind::Nullable;
3438         break;
3439       }
3440 
3441       // fallthrough
3442 
3443     case Declarator::FileContext:
3444     case Declarator::KNRTypeListContext:
3445       complainAboutMissingNullability = CAMN_Yes;
3446 
3447       // Nullability inference depends on the type and declarator.
3448       switch (classifyPointerDeclarator(S, T, D)) {
3449       case PointerDeclaratorKind::NonPointer:
3450       case PointerDeclaratorKind::MultiLevelPointer:
3451         // Cannot infer nullability.
3452         break;
3453 
3454       case PointerDeclaratorKind::SingleLevelPointer:
3455         // Infer _Nonnull if we are in an assumes-nonnull region.
3456         if (inAssumeNonNullRegion) {
3457           inferNullability = NullabilityKind::NonNull;
3458           inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3459                                 context == Declarator::ObjCResultContext);
3460         }
3461         break;
3462 
3463       case PointerDeclaratorKind::CFErrorRefPointer:
3464       case PointerDeclaratorKind::NSErrorPointerPointer:
3465         // Within a function or method signature, infer _Nullable at both
3466         // levels.
3467         if (isFunctionOrMethod && inAssumeNonNullRegion)
3468           inferNullability = NullabilityKind::Nullable;
3469         break;
3470 
3471       case PointerDeclaratorKind::MaybePointerToCFRef:
3472         if (isFunctionOrMethod) {
3473           // On pointer-to-pointer parameters marked cf_returns_retained or
3474           // cf_returns_not_retained, if the outer pointer is explicit then
3475           // infer the inner pointer as _Nullable.
3476           auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3477             while (NextAttr) {
3478               if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3479                   NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3480                 return true;
3481               NextAttr = NextAttr->getNext();
3482             }
3483             return false;
3484           };
3485           if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3486             if (hasCFReturnsAttr(D.getAttributes()) ||
3487                 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3488                 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3489               inferNullability = NullabilityKind::Nullable;
3490               inferNullabilityInnerOnly = true;
3491             }
3492           }
3493         }
3494         break;
3495       }
3496       break;
3497 
3498     case Declarator::ConversionIdContext:
3499       complainAboutMissingNullability = CAMN_Yes;
3500       break;
3501 
3502     case Declarator::AliasDeclContext:
3503     case Declarator::AliasTemplateContext:
3504     case Declarator::BlockContext:
3505     case Declarator::BlockLiteralContext:
3506     case Declarator::ConditionContext:
3507     case Declarator::CXXCatchContext:
3508     case Declarator::CXXNewContext:
3509     case Declarator::ForContext:
3510     case Declarator::LambdaExprContext:
3511     case Declarator::LambdaExprParameterContext:
3512     case Declarator::ObjCCatchContext:
3513     case Declarator::TemplateParamContext:
3514     case Declarator::TemplateTypeArgContext:
3515     case Declarator::TypeNameContext:
3516       // Don't infer in these contexts.
3517       break;
3518     }
3519   }
3520 
3521   // Local function that checks the nullability for a given pointer declarator.
3522   // Returns true if _Nonnull was inferred.
3523   auto inferPointerNullability = [&](SimplePointerKind pointerKind,
3524                                      SourceLocation pointerLoc,
3525                                      AttributeList *&attrs) -> AttributeList * {
3526     // We've seen a pointer.
3527     if (NumPointersRemaining > 0)
3528       --NumPointersRemaining;
3529 
3530     // If a nullability attribute is present, there's nothing to do.
3531     if (hasNullabilityAttr(attrs))
3532       return nullptr;
3533 
3534     // If we're supposed to infer nullability, do so now.
3535     if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3536       AttributeList::Syntax syntax
3537         = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3538                              : AttributeList::AS_Keyword;
3539       AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3540                                          .create(
3541                                            S.getNullabilityKeyword(
3542                                              *inferNullability),
3543                                            SourceRange(pointerLoc),
3544                                            nullptr, SourceLocation(),
3545                                            nullptr, 0, syntax);
3546 
3547       spliceAttrIntoList(*nullabilityAttr, attrs);
3548 
3549       if (inferNullabilityCS) {
3550         state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
3551           ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
3552       }
3553 
3554       if (inferNullabilityInnerOnly)
3555         inferNullabilityInnerOnlyComplete = true;
3556       return nullabilityAttr;
3557     }
3558 
3559     // If we're supposed to complain about missing nullability, do so
3560     // now if it's truly missing.
3561     switch (complainAboutMissingNullability) {
3562     case CAMN_No:
3563       break;
3564 
3565     case CAMN_InnerPointers:
3566       if (NumPointersRemaining == 0)
3567         break;
3568       // Fallthrough.
3569 
3570     case CAMN_Yes:
3571       checkNullabilityConsistency(state, pointerKind, pointerLoc);
3572     }
3573     return nullptr;
3574   };
3575 
3576   // If the type itself could have nullability but does not, infer pointer
3577   // nullability and perform consistency checking.
3578   if (T->canHaveNullability() && S.ActiveTemplateInstantiations.empty() &&
3579       !T->getNullability(S.Context)) {
3580     SimplePointerKind pointerKind = SimplePointerKind::Pointer;
3581     if (T->isBlockPointerType())
3582       pointerKind = SimplePointerKind::BlockPointer;
3583     else if (T->isMemberPointerType())
3584       pointerKind = SimplePointerKind::MemberPointer;
3585 
3586     if (auto *attr = inferPointerNullability(
3587                        pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3588                        D.getMutableDeclSpec().getAttributes().getListRef())) {
3589       T = Context.getAttributedType(
3590             AttributedType::getNullabilityAttrKind(*inferNullability), T, T);
3591       attr->setUsedAsTypeAttr();
3592     }
3593   }
3594 
3595   // Walk the DeclTypeInfo, building the recursive type as we go.
3596   // DeclTypeInfos are ordered from the identifier out, which is
3597   // opposite of what we want :).
3598   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3599     unsigned chunkIndex = e - i - 1;
3600     state.setCurrentChunkIndex(chunkIndex);
3601     DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
3602     IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
3603     switch (DeclType.Kind) {
3604     case DeclaratorChunk::Paren:
3605       T = S.BuildParenType(T);
3606       break;
3607     case DeclaratorChunk::BlockPointer:
3608       // If blocks are disabled, emit an error.
3609       if (!LangOpts.Blocks)
3610         S.Diag(DeclType.Loc, diag::err_blocks_disable);
3611 
3612       // Handle pointer nullability.
3613       inferPointerNullability(SimplePointerKind::BlockPointer,
3614                               DeclType.Loc, DeclType.getAttrListRef());
3615 
3616       T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
3617       if (DeclType.Cls.TypeQuals)
3618         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
3619       break;
3620     case DeclaratorChunk::Pointer:
3621       // Verify that we're not building a pointer to pointer to function with
3622       // exception specification.
3623       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3624         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3625         D.setInvalidType(true);
3626         // Build the type anyway.
3627       }
3628 
3629       // Handle pointer nullability
3630       inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
3631                               DeclType.getAttrListRef());
3632 
3633       if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
3634         T = Context.getObjCObjectPointerType(T);
3635         if (DeclType.Ptr.TypeQuals)
3636           T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3637         break;
3638       }
3639       T = S.BuildPointerType(T, DeclType.Loc, Name);
3640       if (DeclType.Ptr.TypeQuals)
3641         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3642       break;
3643     case DeclaratorChunk::Reference: {
3644       // Verify that we're not building a reference to pointer to function with
3645       // exception specification.
3646       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3647         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3648         D.setInvalidType(true);
3649         // Build the type anyway.
3650       }
3651       T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
3652 
3653       if (DeclType.Ref.HasRestrict)
3654         T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
3655       break;
3656     }
3657     case DeclaratorChunk::Array: {
3658       // Verify that we're not building an array of pointers to function with
3659       // exception specification.
3660       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3661         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3662         D.setInvalidType(true);
3663         // Build the type anyway.
3664       }
3665       DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
3666       Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
3667       ArrayType::ArraySizeModifier ASM;
3668       if (ATI.isStar)
3669         ASM = ArrayType::Star;
3670       else if (ATI.hasStatic)
3671         ASM = ArrayType::Static;
3672       else
3673         ASM = ArrayType::Normal;
3674       if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
3675         // FIXME: This check isn't quite right: it allows star in prototypes
3676         // for function definitions, and disallows some edge cases detailed
3677         // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
3678         S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
3679         ASM = ArrayType::Normal;
3680         D.setInvalidType(true);
3681       }
3682 
3683       // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
3684       // shall appear only in a declaration of a function parameter with an
3685       // array type, ...
3686       if (ASM == ArrayType::Static || ATI.TypeQuals) {
3687         if (!(D.isPrototypeContext() ||
3688               D.getContext() == Declarator::KNRTypeListContext)) {
3689           S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
3690               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3691           // Remove the 'static' and the type qualifiers.
3692           if (ASM == ArrayType::Static)
3693             ASM = ArrayType::Normal;
3694           ATI.TypeQuals = 0;
3695           D.setInvalidType(true);
3696         }
3697 
3698         // C99 6.7.5.2p1: ... and then only in the outermost array type
3699         // derivation.
3700         unsigned x = chunkIndex;
3701         while (x != 0) {
3702           // Walk outwards along the declarator chunks.
3703           x--;
3704           const DeclaratorChunk &DC = D.getTypeObject(x);
3705           switch (DC.Kind) {
3706           case DeclaratorChunk::Paren:
3707             continue;
3708           case DeclaratorChunk::Array:
3709           case DeclaratorChunk::Pointer:
3710           case DeclaratorChunk::Reference:
3711           case DeclaratorChunk::MemberPointer:
3712             S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
3713               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3714             if (ASM == ArrayType::Static)
3715               ASM = ArrayType::Normal;
3716             ATI.TypeQuals = 0;
3717             D.setInvalidType(true);
3718             break;
3719           case DeclaratorChunk::Function:
3720           case DeclaratorChunk::BlockPointer:
3721           case DeclaratorChunk::Pipe:
3722             // These are invalid anyway, so just ignore.
3723             break;
3724           }
3725         }
3726       }
3727       const AutoType *AT = T->getContainedAutoType();
3728       // Allow arrays of auto if we are a generic lambda parameter.
3729       // i.e. [](auto (&array)[5]) { return array[0]; }; OK
3730       if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
3731         // We've already diagnosed this for decltype(auto).
3732         if (!AT->isDecltypeAuto())
3733           S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
3734             << getPrintableNameForEntity(Name) << T;
3735         T = QualType();
3736         break;
3737       }
3738 
3739       T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
3740                            SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
3741       break;
3742     }
3743     case DeclaratorChunk::Function: {
3744       // If the function declarator has a prototype (i.e. it is not () and
3745       // does not have a K&R-style identifier list), then the arguments are part
3746       // of the type, otherwise the argument list is ().
3747       const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3748       IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
3749 
3750       // Check for auto functions and trailing return type and adjust the
3751       // return type accordingly.
3752       if (!D.isInvalidType()) {
3753         // trailing-return-type is only required if we're declaring a function,
3754         // and not, for instance, a pointer to a function.
3755         if (D.getDeclSpec().containsPlaceholderType() &&
3756             !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
3757             !S.getLangOpts().CPlusPlus14) {
3758           S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3759                  D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
3760                      ? diag::err_auto_missing_trailing_return
3761                      : diag::err_deduced_return_type);
3762           T = Context.IntTy;
3763           D.setInvalidType(true);
3764         } else if (FTI.hasTrailingReturnType()) {
3765           // T must be exactly 'auto' at this point. See CWG issue 681.
3766           if (isa<ParenType>(T)) {
3767             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3768                  diag::err_trailing_return_in_parens)
3769               << T << D.getDeclSpec().getSourceRange();
3770             D.setInvalidType(true);
3771           } else if (D.getContext() != Declarator::LambdaExprContext &&
3772                      (T.hasQualifiers() || !isa<AutoType>(T) ||
3773                       cast<AutoType>(T)->getKeyword() != AutoTypeKeyword::Auto)) {
3774             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3775                  diag::err_trailing_return_without_auto)
3776               << T << D.getDeclSpec().getSourceRange();
3777             D.setInvalidType(true);
3778           }
3779           T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
3780           if (T.isNull()) {
3781             // An error occurred parsing the trailing return type.
3782             T = Context.IntTy;
3783             D.setInvalidType(true);
3784           }
3785         }
3786       }
3787 
3788       // C99 6.7.5.3p1: The return type may not be a function or array type.
3789       // For conversion functions, we'll diagnose this particular error later.
3790       if ((T->isArrayType() || T->isFunctionType()) &&
3791           (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
3792         unsigned diagID = diag::err_func_returning_array_function;
3793         // Last processing chunk in block context means this function chunk
3794         // represents the block.
3795         if (chunkIndex == 0 &&
3796             D.getContext() == Declarator::BlockLiteralContext)
3797           diagID = diag::err_block_returning_array_function;
3798         S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
3799         T = Context.IntTy;
3800         D.setInvalidType(true);
3801       }
3802 
3803       // Do not allow returning half FP value.
3804       // FIXME: This really should be in BuildFunctionType.
3805       if (T->isHalfType()) {
3806         if (S.getLangOpts().OpenCL) {
3807           if (!S.getOpenCLOptions().cl_khr_fp16) {
3808             S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
3809             D.setInvalidType(true);
3810           }
3811         } else if (!S.getLangOpts().HalfArgsAndReturns) {
3812           S.Diag(D.getIdentifierLoc(),
3813             diag::err_parameters_retval_cannot_have_fp16_type) << 1;
3814           D.setInvalidType(true);
3815         }
3816       }
3817 
3818       // Methods cannot return interface types. All ObjC objects are
3819       // passed by reference.
3820       if (T->isObjCObjectType()) {
3821         SourceLocation DiagLoc, FixitLoc;
3822         if (TInfo) {
3823           DiagLoc = TInfo->getTypeLoc().getLocStart();
3824           FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
3825         } else {
3826           DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
3827           FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
3828         }
3829         S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
3830           << 0 << T
3831           << FixItHint::CreateInsertion(FixitLoc, "*");
3832 
3833         T = Context.getObjCObjectPointerType(T);
3834         if (TInfo) {
3835           TypeLocBuilder TLB;
3836           TLB.pushFullCopy(TInfo->getTypeLoc());
3837           ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
3838           TLoc.setStarLoc(FixitLoc);
3839           TInfo = TLB.getTypeSourceInfo(Context, T);
3840         }
3841 
3842         D.setInvalidType(true);
3843       }
3844 
3845       // cv-qualifiers on return types are pointless except when the type is a
3846       // class type in C++.
3847       if ((T.getCVRQualifiers() || T->isAtomicType()) &&
3848           !(S.getLangOpts().CPlusPlus &&
3849             (T->isDependentType() || T->isRecordType()))) {
3850         if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
3851             D.getFunctionDefinitionKind() == FDK_Definition) {
3852           // [6.9.1/3] qualified void return is invalid on a C
3853           // function definition.  Apparently ok on declarations and
3854           // in C++ though (!)
3855           S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
3856         } else
3857           diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
3858       }
3859 
3860       // Objective-C ARC ownership qualifiers are ignored on the function
3861       // return type (by type canonicalization). Complain if this attribute
3862       // was written here.
3863       if (T.getQualifiers().hasObjCLifetime()) {
3864         SourceLocation AttrLoc;
3865         if (chunkIndex + 1 < D.getNumTypeObjects()) {
3866           DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
3867           for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
3868                Attr; Attr = Attr->getNext()) {
3869             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
3870               AttrLoc = Attr->getLoc();
3871               break;
3872             }
3873           }
3874         }
3875         if (AttrLoc.isInvalid()) {
3876           for (const AttributeList *Attr
3877                  = D.getDeclSpec().getAttributes().getList();
3878                Attr; Attr = Attr->getNext()) {
3879             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
3880               AttrLoc = Attr->getLoc();
3881               break;
3882             }
3883           }
3884         }
3885 
3886         if (AttrLoc.isValid()) {
3887           // The ownership attributes are almost always written via
3888           // the predefined
3889           // __strong/__weak/__autoreleasing/__unsafe_unretained.
3890           if (AttrLoc.isMacroID())
3891             AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
3892 
3893           S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
3894             << T.getQualifiers().getObjCLifetime();
3895         }
3896       }
3897 
3898       if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
3899         // C++ [dcl.fct]p6:
3900         //   Types shall not be defined in return or parameter types.
3901         TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3902         S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
3903           << Context.getTypeDeclType(Tag);
3904       }
3905 
3906       // Exception specs are not allowed in typedefs. Complain, but add it
3907       // anyway.
3908       if (IsTypedefName && FTI.getExceptionSpecType())
3909         S.Diag(FTI.getExceptionSpecLocBeg(),
3910                diag::err_exception_spec_in_typedef)
3911             << (D.getContext() == Declarator::AliasDeclContext ||
3912                 D.getContext() == Declarator::AliasTemplateContext);
3913 
3914       // If we see "T var();" or "T var(T());" at block scope, it is probably
3915       // an attempt to initialize a variable, not a function declaration.
3916       if (FTI.isAmbiguous)
3917         warnAboutAmbiguousFunction(S, D, DeclType, T);
3918 
3919       FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
3920 
3921       if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
3922         // Simple void foo(), where the incoming T is the result type.
3923         T = Context.getFunctionNoProtoType(T, EI);
3924       } else {
3925         // We allow a zero-parameter variadic function in C if the
3926         // function is marked with the "overloadable" attribute. Scan
3927         // for this attribute now.
3928         if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
3929           bool Overloadable = false;
3930           for (const AttributeList *Attrs = D.getAttributes();
3931                Attrs; Attrs = Attrs->getNext()) {
3932             if (Attrs->getKind() == AttributeList::AT_Overloadable) {
3933               Overloadable = true;
3934               break;
3935             }
3936           }
3937 
3938           if (!Overloadable)
3939             S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
3940         }
3941 
3942         if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
3943           // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
3944           // definition.
3945           S.Diag(FTI.Params[0].IdentLoc,
3946                  diag::err_ident_list_in_fn_declaration);
3947           D.setInvalidType(true);
3948           // Recover by creating a K&R-style function type.
3949           T = Context.getFunctionNoProtoType(T, EI);
3950           break;
3951         }
3952 
3953         FunctionProtoType::ExtProtoInfo EPI;
3954         EPI.ExtInfo = EI;
3955         EPI.Variadic = FTI.isVariadic;
3956         EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
3957         EPI.TypeQuals = FTI.TypeQuals;
3958         EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
3959                     : FTI.RefQualifierIsLValueRef? RQ_LValue
3960                     : RQ_RValue;
3961 
3962         // Otherwise, we have a function with a parameter list that is
3963         // potentially variadic.
3964         SmallVector<QualType, 16> ParamTys;
3965         ParamTys.reserve(FTI.NumParams);
3966 
3967         SmallVector<bool, 16> ConsumedParameters;
3968         ConsumedParameters.reserve(FTI.NumParams);
3969         bool HasAnyConsumedParameters = false;
3970 
3971         for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
3972           ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
3973           QualType ParamTy = Param->getType();
3974           assert(!ParamTy.isNull() && "Couldn't parse type?");
3975 
3976           // Look for 'void'.  void is allowed only as a single parameter to a
3977           // function with no other parameters (C99 6.7.5.3p10).  We record
3978           // int(void) as a FunctionProtoType with an empty parameter list.
3979           if (ParamTy->isVoidType()) {
3980             // If this is something like 'float(int, void)', reject it.  'void'
3981             // is an incomplete type (C99 6.2.5p19) and function decls cannot
3982             // have parameters of incomplete type.
3983             if (FTI.NumParams != 1 || FTI.isVariadic) {
3984               S.Diag(DeclType.Loc, diag::err_void_only_param);
3985               ParamTy = Context.IntTy;
3986               Param->setType(ParamTy);
3987             } else if (FTI.Params[i].Ident) {
3988               // Reject, but continue to parse 'int(void abc)'.
3989               S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
3990               ParamTy = Context.IntTy;
3991               Param->setType(ParamTy);
3992             } else {
3993               // Reject, but continue to parse 'float(const void)'.
3994               if (ParamTy.hasQualifiers())
3995                 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
3996 
3997               // Do not add 'void' to the list.
3998               break;
3999             }
4000           } else if (ParamTy->isHalfType()) {
4001             // Disallow half FP parameters.
4002             // FIXME: This really should be in BuildFunctionType.
4003             if (S.getLangOpts().OpenCL) {
4004               if (!S.getOpenCLOptions().cl_khr_fp16) {
4005                 S.Diag(Param->getLocation(),
4006                   diag::err_opencl_half_param) << ParamTy;
4007                 D.setInvalidType();
4008                 Param->setInvalidDecl();
4009               }
4010             } else if (!S.getLangOpts().HalfArgsAndReturns) {
4011               S.Diag(Param->getLocation(),
4012                 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4013               D.setInvalidType();
4014             }
4015           } else if (!FTI.hasPrototype) {
4016             if (ParamTy->isPromotableIntegerType()) {
4017               ParamTy = Context.getPromotedIntegerType(ParamTy);
4018               Param->setKNRPromoted(true);
4019             } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4020               if (BTy->getKind() == BuiltinType::Float) {
4021                 ParamTy = Context.DoubleTy;
4022                 Param->setKNRPromoted(true);
4023               }
4024             }
4025           }
4026 
4027           if (LangOpts.ObjCAutoRefCount) {
4028             bool Consumed = Param->hasAttr<NSConsumedAttr>();
4029             ConsumedParameters.push_back(Consumed);
4030             HasAnyConsumedParameters |= Consumed;
4031           }
4032 
4033           ParamTys.push_back(ParamTy);
4034         }
4035 
4036         if (HasAnyConsumedParameters)
4037           EPI.ConsumedParameters = ConsumedParameters.data();
4038 
4039         SmallVector<QualType, 4> Exceptions;
4040         SmallVector<ParsedType, 2> DynamicExceptions;
4041         SmallVector<SourceRange, 2> DynamicExceptionRanges;
4042         Expr *NoexceptExpr = nullptr;
4043 
4044         if (FTI.getExceptionSpecType() == EST_Dynamic) {
4045           // FIXME: It's rather inefficient to have to split into two vectors
4046           // here.
4047           unsigned N = FTI.NumExceptions;
4048           DynamicExceptions.reserve(N);
4049           DynamicExceptionRanges.reserve(N);
4050           for (unsigned I = 0; I != N; ++I) {
4051             DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4052             DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4053           }
4054         } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
4055           NoexceptExpr = FTI.NoexceptExpr;
4056         }
4057 
4058         S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4059                                       FTI.getExceptionSpecType(),
4060                                       DynamicExceptions,
4061                                       DynamicExceptionRanges,
4062                                       NoexceptExpr,
4063                                       Exceptions,
4064                                       EPI.ExceptionSpec);
4065 
4066         T = Context.getFunctionType(T, ParamTys, EPI);
4067       }
4068       break;
4069     }
4070     case DeclaratorChunk::MemberPointer: {
4071       // The scope spec must refer to a class, or be dependent.
4072       CXXScopeSpec &SS = DeclType.Mem.Scope();
4073       QualType ClsType;
4074 
4075       // Handle pointer nullability.
4076       inferPointerNullability(SimplePointerKind::MemberPointer,
4077                               DeclType.Loc, DeclType.getAttrListRef());
4078 
4079       if (SS.isInvalid()) {
4080         // Avoid emitting extra errors if we already errored on the scope.
4081         D.setInvalidType(true);
4082       } else if (S.isDependentScopeSpecifier(SS) ||
4083                  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4084         NestedNameSpecifier *NNS = SS.getScopeRep();
4085         NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4086         switch (NNS->getKind()) {
4087         case NestedNameSpecifier::Identifier:
4088           ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4089                                                  NNS->getAsIdentifier());
4090           break;
4091 
4092         case NestedNameSpecifier::Namespace:
4093         case NestedNameSpecifier::NamespaceAlias:
4094         case NestedNameSpecifier::Global:
4095         case NestedNameSpecifier::Super:
4096           llvm_unreachable("Nested-name-specifier must name a type");
4097 
4098         case NestedNameSpecifier::TypeSpec:
4099         case NestedNameSpecifier::TypeSpecWithTemplate:
4100           ClsType = QualType(NNS->getAsType(), 0);
4101           // Note: if the NNS has a prefix and ClsType is a nondependent
4102           // TemplateSpecializationType, then the NNS prefix is NOT included
4103           // in ClsType; hence we wrap ClsType into an ElaboratedType.
4104           // NOTE: in particular, no wrap occurs if ClsType already is an
4105           // Elaborated, DependentName, or DependentTemplateSpecialization.
4106           if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4107             ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4108           break;
4109         }
4110       } else {
4111         S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4112              diag::err_illegal_decl_mempointer_in_nonclass)
4113           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4114           << DeclType.Mem.Scope().getRange();
4115         D.setInvalidType(true);
4116       }
4117 
4118       if (!ClsType.isNull())
4119         T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4120                                      D.getIdentifier());
4121       if (T.isNull()) {
4122         T = Context.IntTy;
4123         D.setInvalidType(true);
4124       } else if (DeclType.Mem.TypeQuals) {
4125         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4126       }
4127       break;
4128     }
4129 
4130     case DeclaratorChunk::Pipe: {
4131       T = S.BuildPipeType(T, DeclType.Loc );
4132       break;
4133     }
4134     }
4135 
4136     if (T.isNull()) {
4137       D.setInvalidType(true);
4138       T = Context.IntTy;
4139     }
4140 
4141     // See if there are any attributes on this declarator chunk.
4142     processTypeAttrs(state, T, TAL_DeclChunk,
4143                      const_cast<AttributeList *>(DeclType.getAttrs()));
4144   }
4145 
4146   assert(!T.isNull() && "T must not be null after this point");
4147 
4148   if (LangOpts.CPlusPlus && T->isFunctionType()) {
4149     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4150     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4151 
4152     // C++ 8.3.5p4:
4153     //   A cv-qualifier-seq shall only be part of the function type
4154     //   for a nonstatic member function, the function type to which a pointer
4155     //   to member refers, or the top-level function type of a function typedef
4156     //   declaration.
4157     //
4158     // Core issue 547 also allows cv-qualifiers on function types that are
4159     // top-level template type arguments.
4160     bool FreeFunction;
4161     if (!D.getCXXScopeSpec().isSet()) {
4162       FreeFunction = ((D.getContext() != Declarator::MemberContext &&
4163                        D.getContext() != Declarator::LambdaExprContext) ||
4164                       D.getDeclSpec().isFriendSpecified());
4165     } else {
4166       DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4167       FreeFunction = (DC && !DC->isRecord());
4168     }
4169 
4170     // C++11 [dcl.fct]p6 (w/DR1417):
4171     // An attempt to specify a function type with a cv-qualifier-seq or a
4172     // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4173     //  - the function type for a non-static member function,
4174     //  - the function type to which a pointer to member refers,
4175     //  - the top-level function type of a function typedef declaration or
4176     //    alias-declaration,
4177     //  - the type-id in the default argument of a type-parameter, or
4178     //  - the type-id of a template-argument for a type-parameter
4179     //
4180     // FIXME: Checking this here is insufficient. We accept-invalid on:
4181     //
4182     //   template<typename T> struct S { void f(T); };
4183     //   S<int() const> s;
4184     //
4185     // ... for instance.
4186     if (IsQualifiedFunction &&
4187         !(!FreeFunction &&
4188           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4189         !IsTypedefName &&
4190         D.getContext() != Declarator::TemplateTypeArgContext) {
4191       SourceLocation Loc = D.getLocStart();
4192       SourceRange RemovalRange;
4193       unsigned I;
4194       if (D.isFunctionDeclarator(I)) {
4195         SmallVector<SourceLocation, 4> RemovalLocs;
4196         const DeclaratorChunk &Chunk = D.getTypeObject(I);
4197         assert(Chunk.Kind == DeclaratorChunk::Function);
4198         if (Chunk.Fun.hasRefQualifier())
4199           RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4200         if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4201           RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4202         if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4203           RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4204         if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4205           RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4206         if (!RemovalLocs.empty()) {
4207           std::sort(RemovalLocs.begin(), RemovalLocs.end(),
4208                     BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4209           RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4210           Loc = RemovalLocs.front();
4211         }
4212       }
4213 
4214       S.Diag(Loc, diag::err_invalid_qualified_function_type)
4215         << FreeFunction << D.isFunctionDeclarator() << T
4216         << getFunctionQualifiersAsString(FnTy)
4217         << FixItHint::CreateRemoval(RemovalRange);
4218 
4219       // Strip the cv-qualifiers and ref-qualifiers from the type.
4220       FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4221       EPI.TypeQuals = 0;
4222       EPI.RefQualifier = RQ_None;
4223 
4224       T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4225                                   EPI);
4226       // Rebuild any parens around the identifier in the function type.
4227       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4228         if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4229           break;
4230         T = S.BuildParenType(T);
4231       }
4232     }
4233   }
4234 
4235   // Apply any undistributed attributes from the declarator.
4236   processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
4237 
4238   // Diagnose any ignored type attributes.
4239   state.diagnoseIgnoredTypeAttrs(T);
4240 
4241   // C++0x [dcl.constexpr]p9:
4242   //  A constexpr specifier used in an object declaration declares the object
4243   //  as const.
4244   if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4245     T.addConst();
4246   }
4247 
4248   // If there was an ellipsis in the declarator, the declaration declares a
4249   // parameter pack whose type may be a pack expansion type.
4250   if (D.hasEllipsis()) {
4251     // C++0x [dcl.fct]p13:
4252     //   A declarator-id or abstract-declarator containing an ellipsis shall
4253     //   only be used in a parameter-declaration. Such a parameter-declaration
4254     //   is a parameter pack (14.5.3). [...]
4255     switch (D.getContext()) {
4256     case Declarator::PrototypeContext:
4257     case Declarator::LambdaExprParameterContext:
4258       // C++0x [dcl.fct]p13:
4259       //   [...] When it is part of a parameter-declaration-clause, the
4260       //   parameter pack is a function parameter pack (14.5.3). The type T
4261       //   of the declarator-id of the function parameter pack shall contain
4262       //   a template parameter pack; each template parameter pack in T is
4263       //   expanded by the function parameter pack.
4264       //
4265       // We represent function parameter packs as function parameters whose
4266       // type is a pack expansion.
4267       if (!T->containsUnexpandedParameterPack()) {
4268         S.Diag(D.getEllipsisLoc(),
4269              diag::err_function_parameter_pack_without_parameter_packs)
4270           << T <<  D.getSourceRange();
4271         D.setEllipsisLoc(SourceLocation());
4272       } else {
4273         T = Context.getPackExpansionType(T, None);
4274       }
4275       break;
4276     case Declarator::TemplateParamContext:
4277       // C++0x [temp.param]p15:
4278       //   If a template-parameter is a [...] is a parameter-declaration that
4279       //   declares a parameter pack (8.3.5), then the template-parameter is a
4280       //   template parameter pack (14.5.3).
4281       //
4282       // Note: core issue 778 clarifies that, if there are any unexpanded
4283       // parameter packs in the type of the non-type template parameter, then
4284       // it expands those parameter packs.
4285       if (T->containsUnexpandedParameterPack())
4286         T = Context.getPackExpansionType(T, None);
4287       else
4288         S.Diag(D.getEllipsisLoc(),
4289                LangOpts.CPlusPlus11
4290                  ? diag::warn_cxx98_compat_variadic_templates
4291                  : diag::ext_variadic_templates);
4292       break;
4293 
4294     case Declarator::FileContext:
4295     case Declarator::KNRTypeListContext:
4296     case Declarator::ObjCParameterContext:  // FIXME: special diagnostic here?
4297     case Declarator::ObjCResultContext:     // FIXME: special diagnostic here?
4298     case Declarator::TypeNameContext:
4299     case Declarator::CXXNewContext:
4300     case Declarator::AliasDeclContext:
4301     case Declarator::AliasTemplateContext:
4302     case Declarator::MemberContext:
4303     case Declarator::BlockContext:
4304     case Declarator::ForContext:
4305     case Declarator::ConditionContext:
4306     case Declarator::CXXCatchContext:
4307     case Declarator::ObjCCatchContext:
4308     case Declarator::BlockLiteralContext:
4309     case Declarator::LambdaExprContext:
4310     case Declarator::ConversionIdContext:
4311     case Declarator::TrailingReturnContext:
4312     case Declarator::TemplateTypeArgContext:
4313       // FIXME: We may want to allow parameter packs in block-literal contexts
4314       // in the future.
4315       S.Diag(D.getEllipsisLoc(),
4316              diag::err_ellipsis_in_declarator_not_parameter);
4317       D.setEllipsisLoc(SourceLocation());
4318       break;
4319     }
4320   }
4321 
4322   assert(!T.isNull() && "T must not be null at the end of this function");
4323   if (D.isInvalidType())
4324     return Context.getTrivialTypeSourceInfo(T);
4325 
4326   return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
4327 }
4328 
4329 /// GetTypeForDeclarator - Convert the type for the specified
4330 /// declarator to Type instances.
4331 ///
4332 /// The result of this call will never be null, but the associated
4333 /// type may be a null type if there's an unrecoverable error.
4334 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
4335   // Determine the type of the declarator. Not all forms of declarator
4336   // have a type.
4337 
4338   TypeProcessingState state(*this, D);
4339 
4340   TypeSourceInfo *ReturnTypeInfo = nullptr;
4341   QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4342 
4343   if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
4344     inferARCWriteback(state, T);
4345 
4346   return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
4347 }
4348 
4349 static void transferARCOwnershipToDeclSpec(Sema &S,
4350                                            QualType &declSpecTy,
4351                                            Qualifiers::ObjCLifetime ownership) {
4352   if (declSpecTy->isObjCRetainableType() &&
4353       declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
4354     Qualifiers qs;
4355     qs.addObjCLifetime(ownership);
4356     declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
4357   }
4358 }
4359 
4360 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
4361                                             Qualifiers::ObjCLifetime ownership,
4362                                             unsigned chunkIndex) {
4363   Sema &S = state.getSema();
4364   Declarator &D = state.getDeclarator();
4365 
4366   // Look for an explicit lifetime attribute.
4367   DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
4368   for (const AttributeList *attr = chunk.getAttrs(); attr;
4369          attr = attr->getNext())
4370     if (attr->getKind() == AttributeList::AT_ObjCOwnership)
4371       return;
4372 
4373   const char *attrStr = nullptr;
4374   switch (ownership) {
4375   case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
4376   case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
4377   case Qualifiers::OCL_Strong: attrStr = "strong"; break;
4378   case Qualifiers::OCL_Weak: attrStr = "weak"; break;
4379   case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
4380   }
4381 
4382   IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
4383   Arg->Ident = &S.Context.Idents.get(attrStr);
4384   Arg->Loc = SourceLocation();
4385 
4386   ArgsUnion Args(Arg);
4387 
4388   // If there wasn't one, add one (with an invalid source location
4389   // so that we don't make an AttributedType for it).
4390   AttributeList *attr = D.getAttributePool()
4391     .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
4392             /*scope*/ nullptr, SourceLocation(),
4393             /*args*/ &Args, 1, AttributeList::AS_GNU);
4394   spliceAttrIntoList(*attr, chunk.getAttrListRef());
4395 
4396   // TODO: mark whether we did this inference?
4397 }
4398 
4399 /// \brief Used for transferring ownership in casts resulting in l-values.
4400 static void transferARCOwnership(TypeProcessingState &state,
4401                                  QualType &declSpecTy,
4402                                  Qualifiers::ObjCLifetime ownership) {
4403   Sema &S = state.getSema();
4404   Declarator &D = state.getDeclarator();
4405 
4406   int inner = -1;
4407   bool hasIndirection = false;
4408   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4409     DeclaratorChunk &chunk = D.getTypeObject(i);
4410     switch (chunk.Kind) {
4411     case DeclaratorChunk::Paren:
4412       // Ignore parens.
4413       break;
4414 
4415     case DeclaratorChunk::Array:
4416     case DeclaratorChunk::Reference:
4417     case DeclaratorChunk::Pointer:
4418       if (inner != -1)
4419         hasIndirection = true;
4420       inner = i;
4421       break;
4422 
4423     case DeclaratorChunk::BlockPointer:
4424       if (inner != -1)
4425         transferARCOwnershipToDeclaratorChunk(state, ownership, i);
4426       return;
4427 
4428     case DeclaratorChunk::Function:
4429     case DeclaratorChunk::MemberPointer:
4430     case DeclaratorChunk::Pipe:
4431       return;
4432     }
4433   }
4434 
4435   if (inner == -1)
4436     return;
4437 
4438   DeclaratorChunk &chunk = D.getTypeObject(inner);
4439   if (chunk.Kind == DeclaratorChunk::Pointer) {
4440     if (declSpecTy->isObjCRetainableType())
4441       return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4442     if (declSpecTy->isObjCObjectType() && hasIndirection)
4443       return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
4444   } else {
4445     assert(chunk.Kind == DeclaratorChunk::Array ||
4446            chunk.Kind == DeclaratorChunk::Reference);
4447     return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4448   }
4449 }
4450 
4451 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
4452   TypeProcessingState state(*this, D);
4453 
4454   TypeSourceInfo *ReturnTypeInfo = nullptr;
4455   QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4456 
4457   if (getLangOpts().ObjC1) {
4458     Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
4459     if (ownership != Qualifiers::OCL_None)
4460       transferARCOwnership(state, declSpecTy, ownership);
4461   }
4462 
4463   return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4464 }
4465 
4466 /// Map an AttributedType::Kind to an AttributeList::Kind.
4467 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
4468   switch (kind) {
4469   case AttributedType::attr_address_space:
4470     return AttributeList::AT_AddressSpace;
4471   case AttributedType::attr_regparm:
4472     return AttributeList::AT_Regparm;
4473   case AttributedType::attr_vector_size:
4474     return AttributeList::AT_VectorSize;
4475   case AttributedType::attr_neon_vector_type:
4476     return AttributeList::AT_NeonVectorType;
4477   case AttributedType::attr_neon_polyvector_type:
4478     return AttributeList::AT_NeonPolyVectorType;
4479   case AttributedType::attr_objc_gc:
4480     return AttributeList::AT_ObjCGC;
4481   case AttributedType::attr_objc_ownership:
4482   case AttributedType::attr_objc_inert_unsafe_unretained:
4483     return AttributeList::AT_ObjCOwnership;
4484   case AttributedType::attr_noreturn:
4485     return AttributeList::AT_NoReturn;
4486   case AttributedType::attr_cdecl:
4487     return AttributeList::AT_CDecl;
4488   case AttributedType::attr_fastcall:
4489     return AttributeList::AT_FastCall;
4490   case AttributedType::attr_stdcall:
4491     return AttributeList::AT_StdCall;
4492   case AttributedType::attr_thiscall:
4493     return AttributeList::AT_ThisCall;
4494   case AttributedType::attr_pascal:
4495     return AttributeList::AT_Pascal;
4496   case AttributedType::attr_vectorcall:
4497     return AttributeList::AT_VectorCall;
4498   case AttributedType::attr_pcs:
4499   case AttributedType::attr_pcs_vfp:
4500     return AttributeList::AT_Pcs;
4501   case AttributedType::attr_inteloclbicc:
4502     return AttributeList::AT_IntelOclBicc;
4503   case AttributedType::attr_ms_abi:
4504     return AttributeList::AT_MSABI;
4505   case AttributedType::attr_sysv_abi:
4506     return AttributeList::AT_SysVABI;
4507   case AttributedType::attr_ptr32:
4508     return AttributeList::AT_Ptr32;
4509   case AttributedType::attr_ptr64:
4510     return AttributeList::AT_Ptr64;
4511   case AttributedType::attr_sptr:
4512     return AttributeList::AT_SPtr;
4513   case AttributedType::attr_uptr:
4514     return AttributeList::AT_UPtr;
4515   case AttributedType::attr_nonnull:
4516     return AttributeList::AT_TypeNonNull;
4517   case AttributedType::attr_nullable:
4518     return AttributeList::AT_TypeNullable;
4519   case AttributedType::attr_null_unspecified:
4520     return AttributeList::AT_TypeNullUnspecified;
4521   case AttributedType::attr_objc_kindof:
4522     return AttributeList::AT_ObjCKindOf;
4523   }
4524   llvm_unreachable("unexpected attribute kind!");
4525 }
4526 
4527 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
4528                                   const AttributeList *attrs,
4529                                   const AttributeList *DeclAttrs = nullptr) {
4530   // DeclAttrs and attrs cannot be both empty.
4531   assert((attrs || DeclAttrs) &&
4532          "no type attributes in the expected location!");
4533 
4534   AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
4535   // Try to search for an attribute of matching kind in attrs list.
4536   while (attrs && attrs->getKind() != parsedKind)
4537     attrs = attrs->getNext();
4538   if (!attrs) {
4539     // No matching type attribute in attrs list found.
4540     // Try searching through C++11 attributes in the declarator attribute list.
4541     while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
4542                          DeclAttrs->getKind() != parsedKind))
4543       DeclAttrs = DeclAttrs->getNext();
4544     attrs = DeclAttrs;
4545   }
4546 
4547   assert(attrs && "no matching type attribute in expected location!");
4548 
4549   TL.setAttrNameLoc(attrs->getLoc());
4550   if (TL.hasAttrExprOperand()) {
4551     assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
4552     TL.setAttrExprOperand(attrs->getArgAsExpr(0));
4553   } else if (TL.hasAttrEnumOperand()) {
4554     assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
4555            "unexpected attribute operand kind");
4556     if (attrs->isArgIdent(0))
4557       TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
4558     else
4559       TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
4560   }
4561 
4562   // FIXME: preserve this information to here.
4563   if (TL.hasAttrOperand())
4564     TL.setAttrOperandParensRange(SourceRange());
4565 }
4566 
4567 namespace {
4568   class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
4569     ASTContext &Context;
4570     const DeclSpec &DS;
4571 
4572   public:
4573     TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
4574       : Context(Context), DS(DS) {}
4575 
4576     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4577       fillAttributedTypeLoc(TL, DS.getAttributes().getList());
4578       Visit(TL.getModifiedLoc());
4579     }
4580     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4581       Visit(TL.getUnqualifiedLoc());
4582     }
4583     void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4584       TL.setNameLoc(DS.getTypeSpecTypeLoc());
4585     }
4586     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
4587       TL.setNameLoc(DS.getTypeSpecTypeLoc());
4588       // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
4589       // addition field. What we have is good enough for dispay of location
4590       // of 'fixit' on interface name.
4591       TL.setNameEndLoc(DS.getLocEnd());
4592     }
4593     void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
4594       TypeSourceInfo *RepTInfo = nullptr;
4595       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4596       TL.copy(RepTInfo->getTypeLoc());
4597     }
4598     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4599       TypeSourceInfo *RepTInfo = nullptr;
4600       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4601       TL.copy(RepTInfo->getTypeLoc());
4602     }
4603     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
4604       TypeSourceInfo *TInfo = nullptr;
4605       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4606 
4607       // If we got no declarator info from previous Sema routines,
4608       // just fill with the typespec loc.
4609       if (!TInfo) {
4610         TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
4611         return;
4612       }
4613 
4614       TypeLoc OldTL = TInfo->getTypeLoc();
4615       if (TInfo->getType()->getAs<ElaboratedType>()) {
4616         ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
4617         TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
4618             .castAs<TemplateSpecializationTypeLoc>();
4619         TL.copy(NamedTL);
4620       } else {
4621         TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
4622         assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
4623       }
4624 
4625     }
4626     void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4627       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
4628       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4629       TL.setParensRange(DS.getTypeofParensRange());
4630     }
4631     void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4632       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
4633       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4634       TL.setParensRange(DS.getTypeofParensRange());
4635       assert(DS.getRepAsType());
4636       TypeSourceInfo *TInfo = nullptr;
4637       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4638       TL.setUnderlyingTInfo(TInfo);
4639     }
4640     void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4641       // FIXME: This holds only because we only have one unary transform.
4642       assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
4643       TL.setKWLoc(DS.getTypeSpecTypeLoc());
4644       TL.setParensRange(DS.getTypeofParensRange());
4645       assert(DS.getRepAsType());
4646       TypeSourceInfo *TInfo = nullptr;
4647       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4648       TL.setUnderlyingTInfo(TInfo);
4649     }
4650     void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4651       // By default, use the source location of the type specifier.
4652       TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
4653       if (TL.needsExtraLocalData()) {
4654         // Set info for the written builtin specifiers.
4655         TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
4656         // Try to have a meaningful source location.
4657         if (TL.getWrittenSignSpec() != TSS_unspecified)
4658           // Sign spec loc overrides the others (e.g., 'unsigned long').
4659           TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
4660         else if (TL.getWrittenWidthSpec() != TSW_unspecified)
4661           // Width spec loc overrides type spec loc (e.g., 'short int').
4662           TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
4663       }
4664     }
4665     void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
4666       ElaboratedTypeKeyword Keyword
4667         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
4668       if (DS.getTypeSpecType() == TST_typename) {
4669         TypeSourceInfo *TInfo = nullptr;
4670         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4671         if (TInfo) {
4672           TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
4673           return;
4674         }
4675       }
4676       TL.setElaboratedKeywordLoc(Keyword != ETK_None
4677                                  ? DS.getTypeSpecTypeLoc()
4678                                  : SourceLocation());
4679       const CXXScopeSpec& SS = DS.getTypeSpecScope();
4680       TL.setQualifierLoc(SS.getWithLocInContext(Context));
4681       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
4682     }
4683     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
4684       assert(DS.getTypeSpecType() == TST_typename);
4685       TypeSourceInfo *TInfo = nullptr;
4686       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4687       assert(TInfo);
4688       TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
4689     }
4690     void VisitDependentTemplateSpecializationTypeLoc(
4691                                  DependentTemplateSpecializationTypeLoc TL) {
4692       assert(DS.getTypeSpecType() == TST_typename);
4693       TypeSourceInfo *TInfo = nullptr;
4694       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4695       assert(TInfo);
4696       TL.copy(
4697           TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
4698     }
4699     void VisitTagTypeLoc(TagTypeLoc TL) {
4700       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
4701     }
4702     void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
4703       // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
4704       // or an _Atomic qualifier.
4705       if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
4706         TL.setKWLoc(DS.getTypeSpecTypeLoc());
4707         TL.setParensRange(DS.getTypeofParensRange());
4708 
4709         TypeSourceInfo *TInfo = nullptr;
4710         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4711         assert(TInfo);
4712         TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4713       } else {
4714         TL.setKWLoc(DS.getAtomicSpecLoc());
4715         // No parens, to indicate this was spelled as an _Atomic qualifier.
4716         TL.setParensRange(SourceRange());
4717         Visit(TL.getValueLoc());
4718       }
4719     }
4720 
4721     void VisitPipeTypeLoc(PipeTypeLoc TL) {
4722       TL.setKWLoc(DS.getTypeSpecTypeLoc());
4723 
4724       TypeSourceInfo *TInfo = nullptr;
4725       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4726       TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4727     }
4728 
4729     void VisitTypeLoc(TypeLoc TL) {
4730       // FIXME: add other typespec types and change this to an assert.
4731       TL.initialize(Context, DS.getTypeSpecTypeLoc());
4732     }
4733   };
4734 
4735   class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
4736     ASTContext &Context;
4737     const DeclaratorChunk &Chunk;
4738 
4739   public:
4740     DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
4741       : Context(Context), Chunk(Chunk) {}
4742 
4743     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4744       llvm_unreachable("qualified type locs not expected here!");
4745     }
4746     void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
4747       llvm_unreachable("decayed type locs not expected here!");
4748     }
4749 
4750     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4751       fillAttributedTypeLoc(TL, Chunk.getAttrs());
4752     }
4753     void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
4754       // nothing
4755     }
4756     void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4757       assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
4758       TL.setCaretLoc(Chunk.Loc);
4759     }
4760     void VisitPointerTypeLoc(PointerTypeLoc TL) {
4761       assert(Chunk.Kind == DeclaratorChunk::Pointer);
4762       TL.setStarLoc(Chunk.Loc);
4763     }
4764     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4765       assert(Chunk.Kind == DeclaratorChunk::Pointer);
4766       TL.setStarLoc(Chunk.Loc);
4767     }
4768     void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4769       assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
4770       const CXXScopeSpec& SS = Chunk.Mem.Scope();
4771       NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
4772 
4773       const Type* ClsTy = TL.getClass();
4774       QualType ClsQT = QualType(ClsTy, 0);
4775       TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
4776       // Now copy source location info into the type loc component.
4777       TypeLoc ClsTL = ClsTInfo->getTypeLoc();
4778       switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
4779       case NestedNameSpecifier::Identifier:
4780         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
4781         {
4782           DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
4783           DNTLoc.setElaboratedKeywordLoc(SourceLocation());
4784           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
4785           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
4786         }
4787         break;
4788 
4789       case NestedNameSpecifier::TypeSpec:
4790       case NestedNameSpecifier::TypeSpecWithTemplate:
4791         if (isa<ElaboratedType>(ClsTy)) {
4792           ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
4793           ETLoc.setElaboratedKeywordLoc(SourceLocation());
4794           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
4795           TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
4796           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
4797         } else {
4798           ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
4799         }
4800         break;
4801 
4802       case NestedNameSpecifier::Namespace:
4803       case NestedNameSpecifier::NamespaceAlias:
4804       case NestedNameSpecifier::Global:
4805       case NestedNameSpecifier::Super:
4806         llvm_unreachable("Nested-name-specifier must name a type");
4807       }
4808 
4809       // Finally fill in MemberPointerLocInfo fields.
4810       TL.setStarLoc(Chunk.Loc);
4811       TL.setClassTInfo(ClsTInfo);
4812     }
4813     void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4814       assert(Chunk.Kind == DeclaratorChunk::Reference);
4815       // 'Amp' is misleading: this might have been originally
4816       /// spelled with AmpAmp.
4817       TL.setAmpLoc(Chunk.Loc);
4818     }
4819     void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4820       assert(Chunk.Kind == DeclaratorChunk::Reference);
4821       assert(!Chunk.Ref.LValueRef);
4822       TL.setAmpAmpLoc(Chunk.Loc);
4823     }
4824     void VisitArrayTypeLoc(ArrayTypeLoc TL) {
4825       assert(Chunk.Kind == DeclaratorChunk::Array);
4826       TL.setLBracketLoc(Chunk.Loc);
4827       TL.setRBracketLoc(Chunk.EndLoc);
4828       TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
4829     }
4830     void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4831       assert(Chunk.Kind == DeclaratorChunk::Function);
4832       TL.setLocalRangeBegin(Chunk.Loc);
4833       TL.setLocalRangeEnd(Chunk.EndLoc);
4834 
4835       const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
4836       TL.setLParenLoc(FTI.getLParenLoc());
4837       TL.setRParenLoc(FTI.getRParenLoc());
4838       for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
4839         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4840         TL.setParam(tpi++, Param);
4841       }
4842       // FIXME: exception specs
4843     }
4844     void VisitParenTypeLoc(ParenTypeLoc TL) {
4845       assert(Chunk.Kind == DeclaratorChunk::Paren);
4846       TL.setLParenLoc(Chunk.Loc);
4847       TL.setRParenLoc(Chunk.EndLoc);
4848     }
4849     void VisitPipeTypeLoc(PipeTypeLoc TL) {
4850       assert(Chunk.Kind == DeclaratorChunk::Pipe);
4851       TL.setKWLoc(Chunk.Loc);
4852     }
4853 
4854     void VisitTypeLoc(TypeLoc TL) {
4855       llvm_unreachable("unsupported TypeLoc kind in declarator!");
4856     }
4857   };
4858 } // end anonymous namespace
4859 
4860 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
4861   SourceLocation Loc;
4862   switch (Chunk.Kind) {
4863   case DeclaratorChunk::Function:
4864   case DeclaratorChunk::Array:
4865   case DeclaratorChunk::Paren:
4866   case DeclaratorChunk::Pipe:
4867     llvm_unreachable("cannot be _Atomic qualified");
4868 
4869   case DeclaratorChunk::Pointer:
4870     Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
4871     break;
4872 
4873   case DeclaratorChunk::BlockPointer:
4874   case DeclaratorChunk::Reference:
4875   case DeclaratorChunk::MemberPointer:
4876     // FIXME: Provide a source location for the _Atomic keyword.
4877     break;
4878   }
4879 
4880   ATL.setKWLoc(Loc);
4881   ATL.setParensRange(SourceRange());
4882 }
4883 
4884 /// \brief Create and instantiate a TypeSourceInfo with type source information.
4885 ///
4886 /// \param T QualType referring to the type as written in source code.
4887 ///
4888 /// \param ReturnTypeInfo For declarators whose return type does not show
4889 /// up in the normal place in the declaration specifiers (such as a C++
4890 /// conversion function), this pointer will refer to a type source information
4891 /// for that return type.
4892 TypeSourceInfo *
4893 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
4894                                      TypeSourceInfo *ReturnTypeInfo) {
4895   TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
4896   UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
4897   const AttributeList *DeclAttrs = D.getAttributes();
4898 
4899   // Handle parameter packs whose type is a pack expansion.
4900   if (isa<PackExpansionType>(T)) {
4901     CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
4902     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
4903   }
4904 
4905   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4906     // An AtomicTypeLoc might be produced by an atomic qualifier in this
4907     // declarator chunk.
4908     if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
4909       fillAtomicQualLoc(ATL, D.getTypeObject(i));
4910       CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
4911     }
4912 
4913     while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
4914       fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
4915       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4916     }
4917 
4918     // FIXME: Ordering here?
4919     while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
4920       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4921 
4922     DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
4923     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
4924   }
4925 
4926   // If we have different source information for the return type, use
4927   // that.  This really only applies to C++ conversion functions.
4928   if (ReturnTypeInfo) {
4929     TypeLoc TL = ReturnTypeInfo->getTypeLoc();
4930     assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
4931     memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
4932   } else {
4933     TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
4934   }
4935 
4936   return TInfo;
4937 }
4938 
4939 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
4940 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
4941   // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
4942   // and Sema during declaration parsing. Try deallocating/caching them when
4943   // it's appropriate, instead of allocating them and keeping them around.
4944   LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
4945                                                        TypeAlignment);
4946   new (LocT) LocInfoType(T, TInfo);
4947   assert(LocT->getTypeClass() != T->getTypeClass() &&
4948          "LocInfoType's TypeClass conflicts with an existing Type class");
4949   return ParsedType::make(QualType(LocT, 0));
4950 }
4951 
4952 void LocInfoType::getAsStringInternal(std::string &Str,
4953                                       const PrintingPolicy &Policy) const {
4954   llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
4955          " was used directly instead of getting the QualType through"
4956          " GetTypeFromParser");
4957 }
4958 
4959 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
4960   // C99 6.7.6: Type names have no identifier.  This is already validated by
4961   // the parser.
4962   assert(D.getIdentifier() == nullptr &&
4963          "Type name should have no identifier!");
4964 
4965   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4966   QualType T = TInfo->getType();
4967   if (D.isInvalidType())
4968     return true;
4969 
4970   // Make sure there are no unused decl attributes on the declarator.
4971   // We don't want to do this for ObjC parameters because we're going
4972   // to apply them to the actual parameter declaration.
4973   // Likewise, we don't want to do this for alias declarations, because
4974   // we are actually going to build a declaration from this eventually.
4975   if (D.getContext() != Declarator::ObjCParameterContext &&
4976       D.getContext() != Declarator::AliasDeclContext &&
4977       D.getContext() != Declarator::AliasTemplateContext)
4978     checkUnusedDeclAttributes(D);
4979 
4980   if (getLangOpts().CPlusPlus) {
4981     // Check that there are no default arguments (C++ only).
4982     CheckExtraCXXDefaultArguments(D);
4983   }
4984 
4985   return CreateParsedType(T, TInfo);
4986 }
4987 
4988 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
4989   QualType T = Context.getObjCInstanceType();
4990   TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
4991   return CreateParsedType(T, TInfo);
4992 }
4993 
4994 //===----------------------------------------------------------------------===//
4995 // Type Attribute Processing
4996 //===----------------------------------------------------------------------===//
4997 
4998 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
4999 /// specified type.  The attribute contains 1 argument, the id of the address
5000 /// space for the type.
5001 static void HandleAddressSpaceTypeAttribute(QualType &Type,
5002                                             const AttributeList &Attr, Sema &S){
5003 
5004   // If this type is already address space qualified, reject it.
5005   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5006   // qualifiers for two or more different address spaces."
5007   if (Type.getAddressSpace()) {
5008     S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5009     Attr.setInvalid();
5010     return;
5011   }
5012 
5013   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5014   // qualified by an address-space qualifier."
5015   if (Type->isFunctionType()) {
5016     S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5017     Attr.setInvalid();
5018     return;
5019   }
5020 
5021   unsigned ASIdx;
5022   if (Attr.getKind() == AttributeList::AT_AddressSpace) {
5023     // Check the attribute arguments.
5024     if (Attr.getNumArgs() != 1) {
5025       S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5026         << Attr.getName() << 1;
5027       Attr.setInvalid();
5028       return;
5029     }
5030     Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5031     llvm::APSInt addrSpace(32);
5032     if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
5033         !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
5034       S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5035         << Attr.getName() << AANT_ArgumentIntegerConstant
5036         << ASArgExpr->getSourceRange();
5037       Attr.setInvalid();
5038       return;
5039     }
5040 
5041     // Bounds checking.
5042     if (addrSpace.isSigned()) {
5043       if (addrSpace.isNegative()) {
5044         S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
5045           << ASArgExpr->getSourceRange();
5046         Attr.setInvalid();
5047         return;
5048       }
5049       addrSpace.setIsSigned(false);
5050     }
5051     llvm::APSInt max(addrSpace.getBitWidth());
5052     max = Qualifiers::MaxAddressSpace;
5053     if (addrSpace > max) {
5054       S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
5055         << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
5056       Attr.setInvalid();
5057       return;
5058     }
5059     ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
5060   } else {
5061     // The keyword-based type attributes imply which address space to use.
5062     switch (Attr.getKind()) {
5063     case AttributeList::AT_OpenCLGlobalAddressSpace:
5064       ASIdx = LangAS::opencl_global; break;
5065     case AttributeList::AT_OpenCLLocalAddressSpace:
5066       ASIdx = LangAS::opencl_local; break;
5067     case AttributeList::AT_OpenCLConstantAddressSpace:
5068       ASIdx = LangAS::opencl_constant; break;
5069     case AttributeList::AT_OpenCLGenericAddressSpace:
5070       ASIdx = LangAS::opencl_generic; break;
5071     default:
5072       assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
5073       ASIdx = 0; break;
5074     }
5075   }
5076 
5077   Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5078 }
5079 
5080 /// Does this type have a "direct" ownership qualifier?  That is,
5081 /// is it written like "__strong id", as opposed to something like
5082 /// "typeof(foo)", where that happens to be strong?
5083 static bool hasDirectOwnershipQualifier(QualType type) {
5084   // Fast path: no qualifier at all.
5085   assert(type.getQualifiers().hasObjCLifetime());
5086 
5087   while (true) {
5088     // __strong id
5089     if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5090       if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5091         return true;
5092 
5093       type = attr->getModifiedType();
5094 
5095     // X *__strong (...)
5096     } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5097       type = paren->getInnerType();
5098 
5099     // That's it for things we want to complain about.  In particular,
5100     // we do not want to look through typedefs, typeof(expr),
5101     // typeof(type), or any other way that the type is somehow
5102     // abstracted.
5103     } else {
5104 
5105       return false;
5106     }
5107   }
5108 }
5109 
5110 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5111 /// attribute on the specified type.
5112 ///
5113 /// Returns 'true' if the attribute was handled.
5114 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5115                                        AttributeList &attr,
5116                                        QualType &type) {
5117   bool NonObjCPointer = false;
5118 
5119   if (!type->isDependentType() && !type->isUndeducedType()) {
5120     if (const PointerType *ptr = type->getAs<PointerType>()) {
5121       QualType pointee = ptr->getPointeeType();
5122       if (pointee->isObjCRetainableType() || pointee->isPointerType())
5123         return false;
5124       // It is important not to lose the source info that there was an attribute
5125       // applied to non-objc pointer. We will create an attributed type but
5126       // its type will be the same as the original type.
5127       NonObjCPointer = true;
5128     } else if (!type->isObjCRetainableType()) {
5129       return false;
5130     }
5131 
5132     // Don't accept an ownership attribute in the declspec if it would
5133     // just be the return type of a block pointer.
5134     if (state.isProcessingDeclSpec()) {
5135       Declarator &D = state.getDeclarator();
5136       if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5137                                   /*onlyBlockPointers=*/true))
5138         return false;
5139     }
5140   }
5141 
5142   Sema &S = state.getSema();
5143   SourceLocation AttrLoc = attr.getLoc();
5144   if (AttrLoc.isMacroID())
5145     AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
5146 
5147   if (!attr.isArgIdent(0)) {
5148     S.Diag(AttrLoc, diag::err_attribute_argument_type)
5149       << attr.getName() << AANT_ArgumentString;
5150     attr.setInvalid();
5151     return true;
5152   }
5153 
5154   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5155   Qualifiers::ObjCLifetime lifetime;
5156   if (II->isStr("none"))
5157     lifetime = Qualifiers::OCL_ExplicitNone;
5158   else if (II->isStr("strong"))
5159     lifetime = Qualifiers::OCL_Strong;
5160   else if (II->isStr("weak"))
5161     lifetime = Qualifiers::OCL_Weak;
5162   else if (II->isStr("autoreleasing"))
5163     lifetime = Qualifiers::OCL_Autoreleasing;
5164   else {
5165     S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5166       << attr.getName() << II;
5167     attr.setInvalid();
5168     return true;
5169   }
5170 
5171   // Just ignore lifetime attributes other than __weak and __unsafe_unretained
5172   // outside of ARC mode.
5173   if (!S.getLangOpts().ObjCAutoRefCount &&
5174       lifetime != Qualifiers::OCL_Weak &&
5175       lifetime != Qualifiers::OCL_ExplicitNone) {
5176     return true;
5177   }
5178 
5179   SplitQualType underlyingType = type.split();
5180 
5181   // Check for redundant/conflicting ownership qualifiers.
5182   if (Qualifiers::ObjCLifetime previousLifetime
5183         = type.getQualifiers().getObjCLifetime()) {
5184     // If it's written directly, that's an error.
5185     if (hasDirectOwnershipQualifier(type)) {
5186       S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5187         << type;
5188       return true;
5189     }
5190 
5191     // Otherwise, if the qualifiers actually conflict, pull sugar off
5192     // until we reach a type that is directly qualified.
5193     if (previousLifetime != lifetime) {
5194       // This should always terminate: the canonical type is
5195       // qualified, so some bit of sugar must be hiding it.
5196       while (!underlyingType.Quals.hasObjCLifetime()) {
5197         underlyingType = underlyingType.getSingleStepDesugaredType();
5198       }
5199       underlyingType.Quals.removeObjCLifetime();
5200     }
5201   }
5202 
5203   underlyingType.Quals.addObjCLifetime(lifetime);
5204 
5205   if (NonObjCPointer) {
5206     StringRef name = attr.getName()->getName();
5207     switch (lifetime) {
5208     case Qualifiers::OCL_None:
5209     case Qualifiers::OCL_ExplicitNone:
5210       break;
5211     case Qualifiers::OCL_Strong: name = "__strong"; break;
5212     case Qualifiers::OCL_Weak: name = "__weak"; break;
5213     case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5214     }
5215     S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5216       << TDS_ObjCObjOrBlock << type;
5217   }
5218 
5219   // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
5220   // because having both 'T' and '__unsafe_unretained T' exist in the type
5221   // system causes unfortunate widespread consistency problems.  (For example,
5222   // they're not considered compatible types, and we mangle them identicially
5223   // as template arguments.)  These problems are all individually fixable,
5224   // but it's easier to just not add the qualifier and instead sniff it out
5225   // in specific places using isObjCInertUnsafeUnretainedType().
5226   //
5227   // Doing this does means we miss some trivial consistency checks that
5228   // would've triggered in ARC, but that's better than trying to solve all
5229   // the coexistence problems with __unsafe_unretained.
5230   if (!S.getLangOpts().ObjCAutoRefCount &&
5231       lifetime == Qualifiers::OCL_ExplicitNone) {
5232     type = S.Context.getAttributedType(
5233                              AttributedType::attr_objc_inert_unsafe_unretained,
5234                                        type, type);
5235     return true;
5236   }
5237 
5238   QualType origType = type;
5239   if (!NonObjCPointer)
5240     type = S.Context.getQualifiedType(underlyingType);
5241 
5242   // If we have a valid source location for the attribute, use an
5243   // AttributedType instead.
5244   if (AttrLoc.isValid())
5245     type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
5246                                        origType, type);
5247 
5248   auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
5249                             unsigned diagnostic, QualType type) {
5250     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
5251       S.DelayedDiagnostics.add(
5252           sema::DelayedDiagnostic::makeForbiddenType(
5253               S.getSourceManager().getExpansionLoc(loc),
5254               diagnostic, type, /*ignored*/ 0));
5255     } else {
5256       S.Diag(loc, diagnostic);
5257     }
5258   };
5259 
5260   // Sometimes, __weak isn't allowed.
5261   if (lifetime == Qualifiers::OCL_Weak &&
5262       !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
5263 
5264     // Use a specialized diagnostic if the runtime just doesn't support them.
5265     unsigned diagnostic =
5266       (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
5267                                        : diag::err_arc_weak_no_runtime);
5268 
5269     // In any case, delay the diagnostic until we know what we're parsing.
5270     diagnoseOrDelay(S, AttrLoc, diagnostic, type);
5271 
5272     attr.setInvalid();
5273     return true;
5274   }
5275 
5276   // Forbid __weak for class objects marked as
5277   // objc_arc_weak_reference_unavailable
5278   if (lifetime == Qualifiers::OCL_Weak) {
5279     if (const ObjCObjectPointerType *ObjT =
5280           type->getAs<ObjCObjectPointerType>()) {
5281       if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
5282         if (Class->isArcWeakrefUnavailable()) {
5283           S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
5284           S.Diag(ObjT->getInterfaceDecl()->getLocation(),
5285                   diag::note_class_declared);
5286         }
5287       }
5288     }
5289   }
5290 
5291   return true;
5292 }
5293 
5294 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
5295 /// attribute on the specified type.  Returns true to indicate that
5296 /// the attribute was handled, false to indicate that the type does
5297 /// not permit the attribute.
5298 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
5299                                  AttributeList &attr,
5300                                  QualType &type) {
5301   Sema &S = state.getSema();
5302 
5303   // Delay if this isn't some kind of pointer.
5304   if (!type->isPointerType() &&
5305       !type->isObjCObjectPointerType() &&
5306       !type->isBlockPointerType())
5307     return false;
5308 
5309   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
5310     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
5311     attr.setInvalid();
5312     return true;
5313   }
5314 
5315   // Check the attribute arguments.
5316   if (!attr.isArgIdent(0)) {
5317     S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
5318       << attr.getName() << AANT_ArgumentString;
5319     attr.setInvalid();
5320     return true;
5321   }
5322   Qualifiers::GC GCAttr;
5323   if (attr.getNumArgs() > 1) {
5324     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5325       << attr.getName() << 1;
5326     attr.setInvalid();
5327     return true;
5328   }
5329 
5330   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5331   if (II->isStr("weak"))
5332     GCAttr = Qualifiers::Weak;
5333   else if (II->isStr("strong"))
5334     GCAttr = Qualifiers::Strong;
5335   else {
5336     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
5337       << attr.getName() << II;
5338     attr.setInvalid();
5339     return true;
5340   }
5341 
5342   QualType origType = type;
5343   type = S.Context.getObjCGCQualType(origType, GCAttr);
5344 
5345   // Make an attributed type to preserve the source information.
5346   if (attr.getLoc().isValid())
5347     type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
5348                                        origType, type);
5349 
5350   return true;
5351 }
5352 
5353 namespace {
5354   /// A helper class to unwrap a type down to a function for the
5355   /// purposes of applying attributes there.
5356   ///
5357   /// Use:
5358   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
5359   ///   if (unwrapped.isFunctionType()) {
5360   ///     const FunctionType *fn = unwrapped.get();
5361   ///     // change fn somehow
5362   ///     T = unwrapped.wrap(fn);
5363   ///   }
5364   struct FunctionTypeUnwrapper {
5365     enum WrapKind {
5366       Desugar,
5367       Parens,
5368       Pointer,
5369       BlockPointer,
5370       Reference,
5371       MemberPointer
5372     };
5373 
5374     QualType Original;
5375     const FunctionType *Fn;
5376     SmallVector<unsigned char /*WrapKind*/, 8> Stack;
5377 
5378     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
5379       while (true) {
5380         const Type *Ty = T.getTypePtr();
5381         if (isa<FunctionType>(Ty)) {
5382           Fn = cast<FunctionType>(Ty);
5383           return;
5384         } else if (isa<ParenType>(Ty)) {
5385           T = cast<ParenType>(Ty)->getInnerType();
5386           Stack.push_back(Parens);
5387         } else if (isa<PointerType>(Ty)) {
5388           T = cast<PointerType>(Ty)->getPointeeType();
5389           Stack.push_back(Pointer);
5390         } else if (isa<BlockPointerType>(Ty)) {
5391           T = cast<BlockPointerType>(Ty)->getPointeeType();
5392           Stack.push_back(BlockPointer);
5393         } else if (isa<MemberPointerType>(Ty)) {
5394           T = cast<MemberPointerType>(Ty)->getPointeeType();
5395           Stack.push_back(MemberPointer);
5396         } else if (isa<ReferenceType>(Ty)) {
5397           T = cast<ReferenceType>(Ty)->getPointeeType();
5398           Stack.push_back(Reference);
5399         } else {
5400           const Type *DTy = Ty->getUnqualifiedDesugaredType();
5401           if (Ty == DTy) {
5402             Fn = nullptr;
5403             return;
5404           }
5405 
5406           T = QualType(DTy, 0);
5407           Stack.push_back(Desugar);
5408         }
5409       }
5410     }
5411 
5412     bool isFunctionType() const { return (Fn != nullptr); }
5413     const FunctionType *get() const { return Fn; }
5414 
5415     QualType wrap(Sema &S, const FunctionType *New) {
5416       // If T wasn't modified from the unwrapped type, do nothing.
5417       if (New == get()) return Original;
5418 
5419       Fn = New;
5420       return wrap(S.Context, Original, 0);
5421     }
5422 
5423   private:
5424     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
5425       if (I == Stack.size())
5426         return C.getQualifiedType(Fn, Old.getQualifiers());
5427 
5428       // Build up the inner type, applying the qualifiers from the old
5429       // type to the new type.
5430       SplitQualType SplitOld = Old.split();
5431 
5432       // As a special case, tail-recurse if there are no qualifiers.
5433       if (SplitOld.Quals.empty())
5434         return wrap(C, SplitOld.Ty, I);
5435       return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
5436     }
5437 
5438     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
5439       if (I == Stack.size()) return QualType(Fn, 0);
5440 
5441       switch (static_cast<WrapKind>(Stack[I++])) {
5442       case Desugar:
5443         // This is the point at which we potentially lose source
5444         // information.
5445         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
5446 
5447       case Parens: {
5448         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
5449         return C.getParenType(New);
5450       }
5451 
5452       case Pointer: {
5453         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
5454         return C.getPointerType(New);
5455       }
5456 
5457       case BlockPointer: {
5458         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
5459         return C.getBlockPointerType(New);
5460       }
5461 
5462       case MemberPointer: {
5463         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
5464         QualType New = wrap(C, OldMPT->getPointeeType(), I);
5465         return C.getMemberPointerType(New, OldMPT->getClass());
5466       }
5467 
5468       case Reference: {
5469         const ReferenceType *OldRef = cast<ReferenceType>(Old);
5470         QualType New = wrap(C, OldRef->getPointeeType(), I);
5471         if (isa<LValueReferenceType>(OldRef))
5472           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
5473         else
5474           return C.getRValueReferenceType(New);
5475       }
5476       }
5477 
5478       llvm_unreachable("unknown wrapping kind");
5479     }
5480   };
5481 } // end anonymous namespace
5482 
5483 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
5484                                              AttributeList &Attr,
5485                                              QualType &Type) {
5486   Sema &S = State.getSema();
5487 
5488   AttributeList::Kind Kind = Attr.getKind();
5489   QualType Desugared = Type;
5490   const AttributedType *AT = dyn_cast<AttributedType>(Type);
5491   while (AT) {
5492     AttributedType::Kind CurAttrKind = AT->getAttrKind();
5493 
5494     // You cannot specify duplicate type attributes, so if the attribute has
5495     // already been applied, flag it.
5496     if (getAttrListKind(CurAttrKind) == Kind) {
5497       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
5498         << Attr.getName();
5499       return true;
5500     }
5501 
5502     // You cannot have both __sptr and __uptr on the same type, nor can you
5503     // have __ptr32 and __ptr64.
5504     if ((CurAttrKind == AttributedType::attr_ptr32 &&
5505          Kind == AttributeList::AT_Ptr64) ||
5506         (CurAttrKind == AttributedType::attr_ptr64 &&
5507          Kind == AttributeList::AT_Ptr32)) {
5508       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5509         << "'__ptr32'" << "'__ptr64'";
5510       return true;
5511     } else if ((CurAttrKind == AttributedType::attr_sptr &&
5512                 Kind == AttributeList::AT_UPtr) ||
5513                (CurAttrKind == AttributedType::attr_uptr &&
5514                 Kind == AttributeList::AT_SPtr)) {
5515       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5516         << "'__sptr'" << "'__uptr'";
5517       return true;
5518     }
5519 
5520     Desugared = AT->getEquivalentType();
5521     AT = dyn_cast<AttributedType>(Desugared);
5522   }
5523 
5524   // Pointer type qualifiers can only operate on pointer types, but not
5525   // pointer-to-member types.
5526   if (!isa<PointerType>(Desugared)) {
5527     if (Type->isMemberPointerType())
5528       S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers)
5529           << Attr.getName();
5530     else
5531       S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
5532           << Attr.getName() << 0;
5533     return true;
5534   }
5535 
5536   AttributedType::Kind TAK;
5537   switch (Kind) {
5538   default: llvm_unreachable("Unknown attribute kind");
5539   case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
5540   case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
5541   case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
5542   case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
5543   }
5544 
5545   Type = S.Context.getAttributedType(TAK, Type, Type);
5546   return false;
5547 }
5548 
5549 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
5550                                          NullabilityKind nullability,
5551                                          SourceLocation nullabilityLoc,
5552                                          bool isContextSensitive) {
5553   // We saw a nullability type specifier. If this is the first one for
5554   // this file, note that.
5555   FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc);
5556   if (!file.isInvalid()) {
5557     FileNullability &fileNullability = NullabilityMap[file];
5558     if (!fileNullability.SawTypeNullability) {
5559       // If we have already seen a pointer declarator without a nullability
5560       // annotation, complain about it.
5561       if (fileNullability.PointerLoc.isValid()) {
5562         Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
5563           << static_cast<unsigned>(fileNullability.PointerKind);
5564       }
5565 
5566       fileNullability.SawTypeNullability = true;
5567     }
5568   }
5569 
5570   // Check for existing nullability attributes on the type.
5571   QualType desugared = type;
5572   while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
5573     // Check whether there is already a null
5574     if (auto existingNullability = attributed->getImmediateNullability()) {
5575       // Duplicated nullability.
5576       if (nullability == *existingNullability) {
5577         Diag(nullabilityLoc, diag::warn_nullability_duplicate)
5578           << DiagNullabilityKind(nullability, isContextSensitive)
5579           << FixItHint::CreateRemoval(nullabilityLoc);
5580 
5581         break;
5582       }
5583 
5584       // Conflicting nullability.
5585       Diag(nullabilityLoc, diag::err_nullability_conflicting)
5586         << DiagNullabilityKind(nullability, isContextSensitive)
5587         << DiagNullabilityKind(*existingNullability, false);
5588       return true;
5589     }
5590 
5591     desugared = attributed->getModifiedType();
5592   }
5593 
5594   // If there is already a different nullability specifier, complain.
5595   // This (unlike the code above) looks through typedefs that might
5596   // have nullability specifiers on them, which means we cannot
5597   // provide a useful Fix-It.
5598   if (auto existingNullability = desugared->getNullability(Context)) {
5599     if (nullability != *existingNullability) {
5600       Diag(nullabilityLoc, diag::err_nullability_conflicting)
5601         << DiagNullabilityKind(nullability, isContextSensitive)
5602         << DiagNullabilityKind(*existingNullability, false);
5603 
5604       // Try to find the typedef with the existing nullability specifier.
5605       if (auto typedefType = desugared->getAs<TypedefType>()) {
5606         TypedefNameDecl *typedefDecl = typedefType->getDecl();
5607         QualType underlyingType = typedefDecl->getUnderlyingType();
5608         if (auto typedefNullability
5609               = AttributedType::stripOuterNullability(underlyingType)) {
5610           if (*typedefNullability == *existingNullability) {
5611             Diag(typedefDecl->getLocation(), diag::note_nullability_here)
5612               << DiagNullabilityKind(*existingNullability, false);
5613           }
5614         }
5615       }
5616 
5617       return true;
5618     }
5619   }
5620 
5621   // If this definitely isn't a pointer type, reject the specifier.
5622   if (!desugared->canHaveNullability()) {
5623     Diag(nullabilityLoc, diag::err_nullability_nonpointer)
5624       << DiagNullabilityKind(nullability, isContextSensitive) << type;
5625     return true;
5626   }
5627 
5628   // For the context-sensitive keywords/Objective-C property
5629   // attributes, require that the type be a single-level pointer.
5630   if (isContextSensitive) {
5631     // Make sure that the pointee isn't itself a pointer type.
5632     QualType pointeeType = desugared->getPointeeType();
5633     if (pointeeType->isAnyPointerType() ||
5634         pointeeType->isObjCObjectPointerType() ||
5635         pointeeType->isMemberPointerType()) {
5636       Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
5637         << DiagNullabilityKind(nullability, true)
5638         << type;
5639       Diag(nullabilityLoc, diag::note_nullability_type_specifier)
5640         << DiagNullabilityKind(nullability, false)
5641         << type
5642         << FixItHint::CreateReplacement(nullabilityLoc,
5643                                         getNullabilitySpelling(nullability));
5644       return true;
5645     }
5646   }
5647 
5648   // Form the attributed type.
5649   type = Context.getAttributedType(
5650            AttributedType::getNullabilityAttrKind(nullability), type, type);
5651   return false;
5652 }
5653 
5654 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
5655   // Find out if it's an Objective-C object or object pointer type;
5656   const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
5657   const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
5658                                           : type->getAs<ObjCObjectType>();
5659 
5660   // If not, we can't apply __kindof.
5661   if (!objType) {
5662     // FIXME: Handle dependent types that aren't yet object types.
5663     Diag(loc, diag::err_objc_kindof_nonobject)
5664       << type;
5665     return true;
5666   }
5667 
5668   // Rebuild the "equivalent" type, which pushes __kindof down into
5669   // the object type.
5670   QualType equivType = Context.getObjCObjectType(objType->getBaseType(),
5671                                                  objType->getTypeArgsAsWritten(),
5672                                                  objType->getProtocols(),
5673                                                  /*isKindOf=*/true);
5674 
5675   // If we started with an object pointer type, rebuild it.
5676   if (ptrType) {
5677     equivType = Context.getObjCObjectPointerType(equivType);
5678     if (auto nullability = type->getNullability(Context)) {
5679       auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
5680       equivType = Context.getAttributedType(attrKind, equivType, equivType);
5681     }
5682   }
5683 
5684   // Build the attributed type to record where __kindof occurred.
5685   type = Context.getAttributedType(AttributedType::attr_objc_kindof,
5686                                    type,
5687                                    equivType);
5688 
5689   return false;
5690 }
5691 
5692 /// Map a nullability attribute kind to a nullability kind.
5693 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
5694   switch (kind) {
5695   case AttributeList::AT_TypeNonNull:
5696     return NullabilityKind::NonNull;
5697 
5698   case AttributeList::AT_TypeNullable:
5699     return NullabilityKind::Nullable;
5700 
5701   case AttributeList::AT_TypeNullUnspecified:
5702     return NullabilityKind::Unspecified;
5703 
5704   default:
5705     llvm_unreachable("not a nullability attribute kind");
5706   }
5707 }
5708 
5709 /// Distribute a nullability type attribute that cannot be applied to
5710 /// the type specifier to a pointer, block pointer, or member pointer
5711 /// declarator, complaining if necessary.
5712 ///
5713 /// \returns true if the nullability annotation was distributed, false
5714 /// otherwise.
5715 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
5716                                           QualType type,
5717                                           AttributeList &attr) {
5718   Declarator &declarator = state.getDeclarator();
5719 
5720   /// Attempt to move the attribute to the specified chunk.
5721   auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
5722     // If there is already a nullability attribute there, don't add
5723     // one.
5724     if (hasNullabilityAttr(chunk.getAttrListRef()))
5725       return false;
5726 
5727     // Complain about the nullability qualifier being in the wrong
5728     // place.
5729     enum {
5730       PK_Pointer,
5731       PK_BlockPointer,
5732       PK_MemberPointer,
5733       PK_FunctionPointer,
5734       PK_MemberFunctionPointer,
5735     } pointerKind
5736       = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
5737                                                              : PK_Pointer)
5738         : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
5739         : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
5740 
5741     auto diag = state.getSema().Diag(attr.getLoc(),
5742                                      diag::warn_nullability_declspec)
5743       << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
5744                              attr.isContextSensitiveKeywordAttribute())
5745       << type
5746       << static_cast<unsigned>(pointerKind);
5747 
5748     // FIXME: MemberPointer chunks don't carry the location of the *.
5749     if (chunk.Kind != DeclaratorChunk::MemberPointer) {
5750       diag << FixItHint::CreateRemoval(attr.getLoc())
5751            << FixItHint::CreateInsertion(
5752                 state.getSema().getPreprocessor()
5753                   .getLocForEndOfToken(chunk.Loc),
5754                 " " + attr.getName()->getName().str() + " ");
5755     }
5756 
5757     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
5758                            chunk.getAttrListRef());
5759     return true;
5760   };
5761 
5762   // Move it to the outermost pointer, member pointer, or block
5763   // pointer declarator.
5764   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
5765     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
5766     switch (chunk.Kind) {
5767     case DeclaratorChunk::Pointer:
5768     case DeclaratorChunk::BlockPointer:
5769     case DeclaratorChunk::MemberPointer:
5770       return moveToChunk(chunk, false);
5771 
5772     case DeclaratorChunk::Paren:
5773     case DeclaratorChunk::Array:
5774       continue;
5775 
5776     case DeclaratorChunk::Function:
5777       // Try to move past the return type to a function/block/member
5778       // function pointer.
5779       if (DeclaratorChunk *dest = maybeMovePastReturnType(
5780                                     declarator, i,
5781                                     /*onlyBlockPointers=*/false)) {
5782         return moveToChunk(*dest, true);
5783       }
5784 
5785       return false;
5786 
5787     // Don't walk through these.
5788     case DeclaratorChunk::Reference:
5789     case DeclaratorChunk::Pipe:
5790       return false;
5791     }
5792   }
5793 
5794   return false;
5795 }
5796 
5797 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
5798   assert(!Attr.isInvalid());
5799   switch (Attr.getKind()) {
5800   default:
5801     llvm_unreachable("not a calling convention attribute");
5802   case AttributeList::AT_CDecl:
5803     return AttributedType::attr_cdecl;
5804   case AttributeList::AT_FastCall:
5805     return AttributedType::attr_fastcall;
5806   case AttributeList::AT_StdCall:
5807     return AttributedType::attr_stdcall;
5808   case AttributeList::AT_ThisCall:
5809     return AttributedType::attr_thiscall;
5810   case AttributeList::AT_Pascal:
5811     return AttributedType::attr_pascal;
5812   case AttributeList::AT_VectorCall:
5813     return AttributedType::attr_vectorcall;
5814   case AttributeList::AT_Pcs: {
5815     // The attribute may have had a fixit applied where we treated an
5816     // identifier as a string literal.  The contents of the string are valid,
5817     // but the form may not be.
5818     StringRef Str;
5819     if (Attr.isArgExpr(0))
5820       Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
5821     else
5822       Str = Attr.getArgAsIdent(0)->Ident->getName();
5823     return llvm::StringSwitch<AttributedType::Kind>(Str)
5824         .Case("aapcs", AttributedType::attr_pcs)
5825         .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
5826   }
5827   case AttributeList::AT_IntelOclBicc:
5828     return AttributedType::attr_inteloclbicc;
5829   case AttributeList::AT_MSABI:
5830     return AttributedType::attr_ms_abi;
5831   case AttributeList::AT_SysVABI:
5832     return AttributedType::attr_sysv_abi;
5833   }
5834   llvm_unreachable("unexpected attribute kind!");
5835 }
5836 
5837 /// Process an individual function attribute.  Returns true to
5838 /// indicate that the attribute was handled, false if it wasn't.
5839 static bool handleFunctionTypeAttr(TypeProcessingState &state,
5840                                    AttributeList &attr,
5841                                    QualType &type) {
5842   Sema &S = state.getSema();
5843 
5844   FunctionTypeUnwrapper unwrapped(S, type);
5845 
5846   if (attr.getKind() == AttributeList::AT_NoReturn) {
5847     if (S.CheckNoReturnAttr(attr))
5848       return true;
5849 
5850     // Delay if this is not a function type.
5851     if (!unwrapped.isFunctionType())
5852       return false;
5853 
5854     // Otherwise we can process right away.
5855     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
5856     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5857     return true;
5858   }
5859 
5860   // ns_returns_retained is not always a type attribute, but if we got
5861   // here, we're treating it as one right now.
5862   if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
5863     assert(S.getLangOpts().ObjCAutoRefCount &&
5864            "ns_returns_retained treated as type attribute in non-ARC");
5865     if (attr.getNumArgs()) return true;
5866 
5867     // Delay if this is not a function type.
5868     if (!unwrapped.isFunctionType())
5869       return false;
5870 
5871     FunctionType::ExtInfo EI
5872       = unwrapped.get()->getExtInfo().withProducesResult(true);
5873     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5874     return true;
5875   }
5876 
5877   if (attr.getKind() == AttributeList::AT_Regparm) {
5878     unsigned value;
5879     if (S.CheckRegparmAttr(attr, value))
5880       return true;
5881 
5882     // Delay if this is not a function type.
5883     if (!unwrapped.isFunctionType())
5884       return false;
5885 
5886     // Diagnose regparm with fastcall.
5887     const FunctionType *fn = unwrapped.get();
5888     CallingConv CC = fn->getCallConv();
5889     if (CC == CC_X86FastCall) {
5890       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5891         << FunctionType::getNameForCallConv(CC)
5892         << "regparm";
5893       attr.setInvalid();
5894       return true;
5895     }
5896 
5897     FunctionType::ExtInfo EI =
5898       unwrapped.get()->getExtInfo().withRegParm(value);
5899     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5900     return true;
5901   }
5902 
5903   // Delay if the type didn't work out to a function.
5904   if (!unwrapped.isFunctionType()) return false;
5905 
5906   // Otherwise, a calling convention.
5907   CallingConv CC;
5908   if (S.CheckCallingConvAttr(attr, CC))
5909     return true;
5910 
5911   const FunctionType *fn = unwrapped.get();
5912   CallingConv CCOld = fn->getCallConv();
5913   AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
5914 
5915   if (CCOld != CC) {
5916     // Error out on when there's already an attribute on the type
5917     // and the CCs don't match.
5918     const AttributedType *AT = S.getCallingConvAttributedType(type);
5919     if (AT && AT->getAttrKind() != CCAttrKind) {
5920       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5921         << FunctionType::getNameForCallConv(CC)
5922         << FunctionType::getNameForCallConv(CCOld);
5923       attr.setInvalid();
5924       return true;
5925     }
5926   }
5927 
5928   // Diagnose use of callee-cleanup calling convention on variadic functions.
5929   if (!supportsVariadicCall(CC)) {
5930     const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
5931     if (FnP && FnP->isVariadic()) {
5932       unsigned DiagID = diag::err_cconv_varargs;
5933       // stdcall and fastcall are ignored with a warning for GCC and MS
5934       // compatibility.
5935       if (CC == CC_X86StdCall || CC == CC_X86FastCall)
5936         DiagID = diag::warn_cconv_varargs;
5937 
5938       S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
5939       attr.setInvalid();
5940       return true;
5941     }
5942   }
5943 
5944   // Also diagnose fastcall with regparm.
5945   if (CC == CC_X86FastCall && fn->getHasRegParm()) {
5946     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5947         << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
5948     attr.setInvalid();
5949     return true;
5950   }
5951 
5952   // Modify the CC from the wrapped function type, wrap it all back, and then
5953   // wrap the whole thing in an AttributedType as written.  The modified type
5954   // might have a different CC if we ignored the attribute.
5955   FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
5956   QualType Equivalent =
5957       unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5958   type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
5959   return true;
5960 }
5961 
5962 bool Sema::hasExplicitCallingConv(QualType &T) {
5963   QualType R = T.IgnoreParens();
5964   while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
5965     if (AT->isCallingConv())
5966       return true;
5967     R = AT->getModifiedType().IgnoreParens();
5968   }
5969   return false;
5970 }
5971 
5972 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
5973                                   SourceLocation Loc) {
5974   FunctionTypeUnwrapper Unwrapped(*this, T);
5975   const FunctionType *FT = Unwrapped.get();
5976   bool IsVariadic = (isa<FunctionProtoType>(FT) &&
5977                      cast<FunctionProtoType>(FT)->isVariadic());
5978   CallingConv CurCC = FT->getCallConv();
5979   CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
5980 
5981   if (CurCC == ToCC)
5982     return;
5983 
5984   // MS compiler ignores explicit calling convention attributes on structors. We
5985   // should do the same.
5986   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
5987     // Issue a warning on ignored calling convention -- except of __stdcall.
5988     // Again, this is what MS compiler does.
5989     if (CurCC != CC_X86StdCall)
5990       Diag(Loc, diag::warn_cconv_structors)
5991           << FunctionType::getNameForCallConv(CurCC);
5992   // Default adjustment.
5993   } else {
5994     // Only adjust types with the default convention.  For example, on Windows
5995     // we should adjust a __cdecl type to __thiscall for instance methods, and a
5996     // __thiscall type to __cdecl for static methods.
5997     CallingConv DefaultCC =
5998         Context.getDefaultCallingConvention(IsVariadic, IsStatic);
5999 
6000     if (CurCC != DefaultCC || DefaultCC == ToCC)
6001       return;
6002 
6003     if (hasExplicitCallingConv(T))
6004       return;
6005   }
6006 
6007   FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6008   QualType Wrapped = Unwrapped.wrap(*this, FT);
6009   T = Context.getAdjustedType(T, Wrapped);
6010 }
6011 
6012 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6013 /// and float scalars, although arrays, pointers, and function return values are
6014 /// allowed in conjunction with this construct. Aggregates with this attribute
6015 /// are invalid, even if they are of the same size as a corresponding scalar.
6016 /// The raw attribute should contain precisely 1 argument, the vector size for
6017 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6018 /// this routine will return a new vector type.
6019 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
6020                                  Sema &S) {
6021   // Check the attribute arguments.
6022   if (Attr.getNumArgs() != 1) {
6023     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6024       << Attr.getName() << 1;
6025     Attr.setInvalid();
6026     return;
6027   }
6028   Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6029   llvm::APSInt vecSize(32);
6030   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
6031       !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
6032     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6033       << Attr.getName() << AANT_ArgumentIntegerConstant
6034       << sizeExpr->getSourceRange();
6035     Attr.setInvalid();
6036     return;
6037   }
6038   // The base type must be integer (not Boolean or enumeration) or float, and
6039   // can't already be a vector.
6040   if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
6041       (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
6042     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6043     Attr.setInvalid();
6044     return;
6045   }
6046   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6047   // vecSize is specified in bytes - convert to bits.
6048   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
6049 
6050   // the vector size needs to be an integral multiple of the type size.
6051   if (vectorSize % typeSize) {
6052     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
6053       << sizeExpr->getSourceRange();
6054     Attr.setInvalid();
6055     return;
6056   }
6057   if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
6058     S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
6059       << sizeExpr->getSourceRange();
6060     Attr.setInvalid();
6061     return;
6062   }
6063   if (vectorSize == 0) {
6064     S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
6065       << sizeExpr->getSourceRange();
6066     Attr.setInvalid();
6067     return;
6068   }
6069 
6070   // Success! Instantiate the vector type, the number of elements is > 0, and
6071   // not required to be a power of 2, unlike GCC.
6072   CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
6073                                     VectorType::GenericVector);
6074 }
6075 
6076 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
6077 /// a type.
6078 static void HandleExtVectorTypeAttr(QualType &CurType,
6079                                     const AttributeList &Attr,
6080                                     Sema &S) {
6081   // check the attribute arguments.
6082   if (Attr.getNumArgs() != 1) {
6083     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6084       << Attr.getName() << 1;
6085     return;
6086   }
6087 
6088   Expr *sizeExpr;
6089 
6090   // Special case where the argument is a template id.
6091   if (Attr.isArgIdent(0)) {
6092     CXXScopeSpec SS;
6093     SourceLocation TemplateKWLoc;
6094     UnqualifiedId id;
6095     id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6096 
6097     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6098                                           id, false, false);
6099     if (Size.isInvalid())
6100       return;
6101 
6102     sizeExpr = Size.get();
6103   } else {
6104     sizeExpr = Attr.getArgAsExpr(0);
6105   }
6106 
6107   // Create the vector type.
6108   QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6109   if (!T.isNull())
6110     CurType = T;
6111 }
6112 
6113 static bool isPermittedNeonBaseType(QualType &Ty,
6114                                     VectorType::VectorKind VecKind, Sema &S) {
6115   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6116   if (!BTy)
6117     return false;
6118 
6119   llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6120 
6121   // Signed poly is mathematically wrong, but has been baked into some ABIs by
6122   // now.
6123   bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6124                         Triple.getArch() == llvm::Triple::aarch64_be;
6125   if (VecKind == VectorType::NeonPolyVector) {
6126     if (IsPolyUnsigned) {
6127       // AArch64 polynomial vectors are unsigned and support poly64.
6128       return BTy->getKind() == BuiltinType::UChar ||
6129              BTy->getKind() == BuiltinType::UShort ||
6130              BTy->getKind() == BuiltinType::ULong ||
6131              BTy->getKind() == BuiltinType::ULongLong;
6132     } else {
6133       // AArch32 polynomial vector are signed.
6134       return BTy->getKind() == BuiltinType::SChar ||
6135              BTy->getKind() == BuiltinType::Short;
6136     }
6137   }
6138 
6139   // Non-polynomial vector types: the usual suspects are allowed, as well as
6140   // float64_t on AArch64.
6141   bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6142                  Triple.getArch() == llvm::Triple::aarch64_be;
6143 
6144   if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6145     return true;
6146 
6147   return BTy->getKind() == BuiltinType::SChar ||
6148          BTy->getKind() == BuiltinType::UChar ||
6149          BTy->getKind() == BuiltinType::Short ||
6150          BTy->getKind() == BuiltinType::UShort ||
6151          BTy->getKind() == BuiltinType::Int ||
6152          BTy->getKind() == BuiltinType::UInt ||
6153          BTy->getKind() == BuiltinType::Long ||
6154          BTy->getKind() == BuiltinType::ULong ||
6155          BTy->getKind() == BuiltinType::LongLong ||
6156          BTy->getKind() == BuiltinType::ULongLong ||
6157          BTy->getKind() == BuiltinType::Float ||
6158          BTy->getKind() == BuiltinType::Half;
6159 }
6160 
6161 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6162 /// "neon_polyvector_type" attributes are used to create vector types that
6163 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
6164 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
6165 /// the argument to these Neon attributes is the number of vector elements,
6166 /// not the vector size in bytes.  The vector width and element type must
6167 /// match one of the standard Neon vector types.
6168 static void HandleNeonVectorTypeAttr(QualType& CurType,
6169                                      const AttributeList &Attr, Sema &S,
6170                                      VectorType::VectorKind VecKind) {
6171   // Target must have NEON
6172   if (!S.Context.getTargetInfo().hasFeature("neon")) {
6173     S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6174     Attr.setInvalid();
6175     return;
6176   }
6177   // Check the attribute arguments.
6178   if (Attr.getNumArgs() != 1) {
6179     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6180       << Attr.getName() << 1;
6181     Attr.setInvalid();
6182     return;
6183   }
6184   // The number of elements must be an ICE.
6185   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6186   llvm::APSInt numEltsInt(32);
6187   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6188       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6189     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6190       << Attr.getName() << AANT_ArgumentIntegerConstant
6191       << numEltsExpr->getSourceRange();
6192     Attr.setInvalid();
6193     return;
6194   }
6195   // Only certain element types are supported for Neon vectors.
6196   if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6197     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6198     Attr.setInvalid();
6199     return;
6200   }
6201 
6202   // The total size of the vector must be 64 or 128 bits.
6203   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6204   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6205   unsigned vecSize = typeSize * numElts;
6206   if (vecSize != 64 && vecSize != 128) {
6207     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6208     Attr.setInvalid();
6209     return;
6210   }
6211 
6212   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6213 }
6214 
6215 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
6216                              TypeAttrLocation TAL, AttributeList *attrs) {
6217   // Scan through and apply attributes to this type where it makes sense.  Some
6218   // attributes (such as __address_space__, __vector_size__, etc) apply to the
6219   // type, but others can be present in the type specifiers even though they
6220   // apply to the decl.  Here we apply type attributes and ignore the rest.
6221 
6222   bool hasOpenCLAddressSpace = false;
6223   while (attrs) {
6224     AttributeList &attr = *attrs;
6225     attrs = attr.getNext(); // reset to the next here due to early loop continue
6226                             // stmts
6227 
6228     // Skip attributes that were marked to be invalid.
6229     if (attr.isInvalid())
6230       continue;
6231 
6232     if (attr.isCXX11Attribute()) {
6233       // [[gnu::...]] attributes are treated as declaration attributes, so may
6234       // not appertain to a DeclaratorChunk, even if we handle them as type
6235       // attributes.
6236       if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
6237         if (TAL == TAL_DeclChunk) {
6238           state.getSema().Diag(attr.getLoc(),
6239                                diag::warn_cxx11_gnu_attribute_on_type)
6240               << attr.getName();
6241           continue;
6242         }
6243       } else if (TAL != TAL_DeclChunk) {
6244         // Otherwise, only consider type processing for a C++11 attribute if
6245         // it's actually been applied to a type.
6246         continue;
6247       }
6248     }
6249 
6250     // If this is an attribute we can handle, do so now,
6251     // otherwise, add it to the FnAttrs list for rechaining.
6252     switch (attr.getKind()) {
6253     default:
6254       // A C++11 attribute on a declarator chunk must appertain to a type.
6255       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
6256         state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
6257           << attr.getName();
6258         attr.setUsedAsTypeAttr();
6259       }
6260       break;
6261 
6262     case AttributeList::UnknownAttribute:
6263       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6264         state.getSema().Diag(attr.getLoc(),
6265                              diag::warn_unknown_attribute_ignored)
6266           << attr.getName();
6267       break;
6268 
6269     case AttributeList::IgnoredAttribute:
6270       break;
6271 
6272     case AttributeList::AT_MayAlias:
6273       // FIXME: This attribute needs to actually be handled, but if we ignore
6274       // it it breaks large amounts of Linux software.
6275       attr.setUsedAsTypeAttr();
6276       break;
6277     case AttributeList::AT_OpenCLPrivateAddressSpace:
6278     case AttributeList::AT_OpenCLGlobalAddressSpace:
6279     case AttributeList::AT_OpenCLLocalAddressSpace:
6280     case AttributeList::AT_OpenCLConstantAddressSpace:
6281     case AttributeList::AT_OpenCLGenericAddressSpace:
6282     case AttributeList::AT_AddressSpace:
6283       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
6284       attr.setUsedAsTypeAttr();
6285       hasOpenCLAddressSpace = true;
6286       break;
6287     OBJC_POINTER_TYPE_ATTRS_CASELIST:
6288       if (!handleObjCPointerTypeAttr(state, attr, type))
6289         distributeObjCPointerTypeAttr(state, attr, type);
6290       attr.setUsedAsTypeAttr();
6291       break;
6292     case AttributeList::AT_VectorSize:
6293       HandleVectorSizeAttr(type, attr, state.getSema());
6294       attr.setUsedAsTypeAttr();
6295       break;
6296     case AttributeList::AT_ExtVectorType:
6297       HandleExtVectorTypeAttr(type, attr, state.getSema());
6298       attr.setUsedAsTypeAttr();
6299       break;
6300     case AttributeList::AT_NeonVectorType:
6301       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6302                                VectorType::NeonVector);
6303       attr.setUsedAsTypeAttr();
6304       break;
6305     case AttributeList::AT_NeonPolyVectorType:
6306       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6307                                VectorType::NeonPolyVector);
6308       attr.setUsedAsTypeAttr();
6309       break;
6310     case AttributeList::AT_OpenCLImageAccess:
6311       // FIXME: there should be some type checking happening here, I would
6312       // imagine, but the original handler's checking was entirely superfluous.
6313       attr.setUsedAsTypeAttr();
6314       break;
6315 
6316     MS_TYPE_ATTRS_CASELIST:
6317       if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6318         attr.setUsedAsTypeAttr();
6319       break;
6320 
6321 
6322     NULLABILITY_TYPE_ATTRS_CASELIST:
6323       // Either add nullability here or try to distribute it.  We
6324       // don't want to distribute the nullability specifier past any
6325       // dependent type, because that complicates the user model.
6326       if (type->canHaveNullability() || type->isDependentType() ||
6327           !distributeNullabilityTypeAttr(state, type, attr)) {
6328         if (state.getSema().checkNullabilityTypeSpecifier(
6329               type,
6330               mapNullabilityAttrKind(attr.getKind()),
6331               attr.getLoc(),
6332               attr.isContextSensitiveKeywordAttribute())) {
6333           attr.setInvalid();
6334         }
6335 
6336         attr.setUsedAsTypeAttr();
6337       }
6338       break;
6339 
6340     case AttributeList::AT_ObjCKindOf:
6341       // '__kindof' must be part of the decl-specifiers.
6342       switch (TAL) {
6343       case TAL_DeclSpec:
6344         break;
6345 
6346       case TAL_DeclChunk:
6347       case TAL_DeclName:
6348         state.getSema().Diag(attr.getLoc(),
6349                              diag::err_objc_kindof_wrong_position)
6350           << FixItHint::CreateRemoval(attr.getLoc())
6351           << FixItHint::CreateInsertion(
6352                state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6353         break;
6354       }
6355 
6356       // Apply it regardless.
6357       if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6358         attr.setInvalid();
6359       attr.setUsedAsTypeAttr();
6360       break;
6361 
6362     case AttributeList::AT_NSReturnsRetained:
6363       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6364         break;
6365       // fallthrough into the function attrs
6366 
6367     FUNCTION_TYPE_ATTRS_CASELIST:
6368       attr.setUsedAsTypeAttr();
6369 
6370       // Never process function type attributes as part of the
6371       // declaration-specifiers.
6372       if (TAL == TAL_DeclSpec)
6373         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6374 
6375       // Otherwise, handle the possible delays.
6376       else if (!handleFunctionTypeAttr(state, attr, type))
6377         distributeFunctionTypeAttr(state, attr, type);
6378       break;
6379     }
6380   }
6381 
6382   // If address space is not set, OpenCL 2.0 defines non private default
6383   // address spaces for some cases:
6384   // OpenCL 2.0, section 6.5:
6385   // The address space for a variable at program scope or a static variable
6386   // inside a function can either be __global or __constant, but defaults to
6387   // __global if not specified.
6388   // (...)
6389   // Pointers that are declared without pointing to a named address space point
6390   // to the generic address space.
6391   if (state.getSema().getLangOpts().OpenCLVersion >= 200 &&
6392       !hasOpenCLAddressSpace && type.getAddressSpace() == 0 &&
6393       (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) {
6394     Declarator &D = state.getDeclarator();
6395     if (state.getCurrentChunkIndex() > 0 &&
6396         D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6397             DeclaratorChunk::Pointer) {
6398       type = state.getSema().Context.getAddrSpaceQualType(
6399           type, LangAS::opencl_generic);
6400     } else if (state.getCurrentChunkIndex() == 0 &&
6401                D.getContext() == Declarator::FileContext &&
6402                !D.isFunctionDeclarator() && !D.isFunctionDefinition() &&
6403                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6404                !type->isSamplerT())
6405       type = state.getSema().Context.getAddrSpaceQualType(
6406           type, LangAS::opencl_global);
6407     else if (state.getCurrentChunkIndex() == 0 &&
6408              D.getContext() == Declarator::BlockContext &&
6409              D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
6410       type = state.getSema().Context.getAddrSpaceQualType(
6411           type, LangAS::opencl_global);
6412   }
6413 }
6414 
6415 void Sema::completeExprArrayBound(Expr *E) {
6416   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6417     if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6418       if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
6419         SourceLocation PointOfInstantiation = E->getExprLoc();
6420 
6421         if (MemberSpecializationInfo *MSInfo =
6422                 Var->getMemberSpecializationInfo()) {
6423           // If we don't already have a point of instantiation, this is it.
6424           if (MSInfo->getPointOfInstantiation().isInvalid()) {
6425             MSInfo->setPointOfInstantiation(PointOfInstantiation);
6426 
6427             // This is a modification of an existing AST node. Notify
6428             // listeners.
6429             if (ASTMutationListener *L = getASTMutationListener())
6430               L->StaticDataMemberInstantiated(Var);
6431           }
6432         } else {
6433           VarTemplateSpecializationDecl *VarSpec =
6434               cast<VarTemplateSpecializationDecl>(Var);
6435           if (VarSpec->getPointOfInstantiation().isInvalid())
6436             VarSpec->setPointOfInstantiation(PointOfInstantiation);
6437         }
6438 
6439         InstantiateVariableDefinition(PointOfInstantiation, Var);
6440 
6441         // Update the type to the newly instantiated definition's type both
6442         // here and within the expression.
6443         if (VarDecl *Def = Var->getDefinition()) {
6444           DRE->setDecl(Def);
6445           QualType T = Def->getType();
6446           DRE->setType(T);
6447           // FIXME: Update the type on all intervening expressions.
6448           E->setType(T);
6449         }
6450 
6451         // We still go on to try to complete the type independently, as it
6452         // may also require instantiations or diagnostics if it remains
6453         // incomplete.
6454       }
6455     }
6456   }
6457 }
6458 
6459 /// \brief Ensure that the type of the given expression is complete.
6460 ///
6461 /// This routine checks whether the expression \p E has a complete type. If the
6462 /// expression refers to an instantiable construct, that instantiation is
6463 /// performed as needed to complete its type. Furthermore
6464 /// Sema::RequireCompleteType is called for the expression's type (or in the
6465 /// case of a reference type, the referred-to type).
6466 ///
6467 /// \param E The expression whose type is required to be complete.
6468 /// \param Diagnoser The object that will emit a diagnostic if the type is
6469 /// incomplete.
6470 ///
6471 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
6472 /// otherwise.
6473 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
6474   QualType T = E->getType();
6475 
6476   // Incomplete array types may be completed by the initializer attached to
6477   // their definitions. For static data members of class templates and for
6478   // variable templates, we need to instantiate the definition to get this
6479   // initializer and complete the type.
6480   if (T->isIncompleteArrayType()) {
6481     completeExprArrayBound(E);
6482     T = E->getType();
6483   }
6484 
6485   // FIXME: Are there other cases which require instantiating something other
6486   // than the type to complete the type of an expression?
6487 
6488   return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
6489 }
6490 
6491 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
6492   BoundTypeDiagnoser<> Diagnoser(DiagID);
6493   return RequireCompleteExprType(E, Diagnoser);
6494 }
6495 
6496 /// @brief Ensure that the type T is a complete type.
6497 ///
6498 /// This routine checks whether the type @p T is complete in any
6499 /// context where a complete type is required. If @p T is a complete
6500 /// type, returns false. If @p T is a class template specialization,
6501 /// this routine then attempts to perform class template
6502 /// instantiation. If instantiation fails, or if @p T is incomplete
6503 /// and cannot be completed, issues the diagnostic @p diag (giving it
6504 /// the type @p T) and returns true.
6505 ///
6506 /// @param Loc  The location in the source that the incomplete type
6507 /// diagnostic should refer to.
6508 ///
6509 /// @param T  The type that this routine is examining for completeness.
6510 ///
6511 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
6512 /// @c false otherwise.
6513 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6514                                TypeDiagnoser &Diagnoser) {
6515   if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
6516     return true;
6517   if (const TagType *Tag = T->getAs<TagType>()) {
6518     if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
6519       Tag->getDecl()->setCompleteDefinitionRequired();
6520       Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
6521     }
6522   }
6523   return false;
6524 }
6525 
6526 /// \brief Determine whether there is any declaration of \p D that was ever a
6527 ///        definition (perhaps before module merging) and is currently visible.
6528 /// \param D The definition of the entity.
6529 /// \param Suggested Filled in with the declaration that should be made visible
6530 ///        in order to provide a definition of this entity.
6531 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
6532 ///        not defined. This only matters for enums with a fixed underlying
6533 ///        type, since in all other cases, a type is complete if and only if it
6534 ///        is defined.
6535 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
6536                                 bool OnlyNeedComplete) {
6537   // Easy case: if we don't have modules, all declarations are visible.
6538   if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
6539     return true;
6540 
6541   // If this definition was instantiated from a template, map back to the
6542   // pattern from which it was instantiated.
6543   if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
6544     // We're in the middle of defining it; this definition should be treated
6545     // as visible.
6546     return true;
6547   } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6548     if (auto *Pattern = RD->getTemplateInstantiationPattern())
6549       RD = Pattern;
6550     D = RD->getDefinition();
6551   } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
6552     while (auto *NewED = ED->getInstantiatedFromMemberEnum())
6553       ED = NewED;
6554     if (OnlyNeedComplete && ED->isFixed()) {
6555       // If the enum has a fixed underlying type, and we're only looking for a
6556       // complete type (not a definition), any visible declaration of it will
6557       // do.
6558       *Suggested = nullptr;
6559       for (auto *Redecl : ED->redecls()) {
6560         if (isVisible(Redecl))
6561           return true;
6562         if (Redecl->isThisDeclarationADefinition() ||
6563             (Redecl->isCanonicalDecl() && !*Suggested))
6564           *Suggested = Redecl;
6565       }
6566       return false;
6567     }
6568     D = ED->getDefinition();
6569   }
6570   assert(D && "missing definition for pattern of instantiated definition");
6571 
6572   *Suggested = D;
6573   if (isVisible(D))
6574     return true;
6575 
6576   // The external source may have additional definitions of this type that are
6577   // visible, so complete the redeclaration chain now and ask again.
6578   if (auto *Source = Context.getExternalSource()) {
6579     Source->CompleteRedeclChain(D);
6580     return isVisible(D);
6581   }
6582 
6583   return false;
6584 }
6585 
6586 /// Locks in the inheritance model for the given class and all of its bases.
6587 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
6588   RD = RD->getMostRecentDecl();
6589   if (!RD->hasAttr<MSInheritanceAttr>()) {
6590     MSInheritanceAttr::Spelling IM;
6591 
6592     switch (S.MSPointerToMemberRepresentationMethod) {
6593     case LangOptions::PPTMK_BestCase:
6594       IM = RD->calculateInheritanceModel();
6595       break;
6596     case LangOptions::PPTMK_FullGeneralitySingleInheritance:
6597       IM = MSInheritanceAttr::Keyword_single_inheritance;
6598       break;
6599     case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
6600       IM = MSInheritanceAttr::Keyword_multiple_inheritance;
6601       break;
6602     case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
6603       IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
6604       break;
6605     }
6606 
6607     RD->addAttr(MSInheritanceAttr::CreateImplicit(
6608         S.getASTContext(), IM,
6609         /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
6610             LangOptions::PPTMK_BestCase,
6611         S.ImplicitMSInheritanceAttrLoc.isValid()
6612             ? S.ImplicitMSInheritanceAttrLoc
6613             : RD->getSourceRange()));
6614     S.Consumer.AssignInheritanceModel(RD);
6615   }
6616 }
6617 
6618 /// \brief The implementation of RequireCompleteType
6619 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
6620                                    TypeDiagnoser *Diagnoser) {
6621   // FIXME: Add this assertion to make sure we always get instantiation points.
6622   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
6623   // FIXME: Add this assertion to help us flush out problems with
6624   // checking for dependent types and type-dependent expressions.
6625   //
6626   //  assert(!T->isDependentType() &&
6627   //         "Can't ask whether a dependent type is complete");
6628 
6629   // We lock in the inheritance model once somebody has asked us to ensure
6630   // that a pointer-to-member type is complete.
6631   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6632     if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
6633       if (!MPTy->getClass()->isDependentType()) {
6634         (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
6635         assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
6636       }
6637     }
6638   }
6639 
6640   // If we have a complete type, we're done.
6641   NamedDecl *Def = nullptr;
6642   if (!T->isIncompleteType(&Def)) {
6643     // If we know about the definition but it is not visible, complain.
6644     NamedDecl *SuggestedDef = nullptr;
6645     if (Def &&
6646         !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
6647       // If the user is going to see an error here, recover by making the
6648       // definition visible.
6649       bool TreatAsComplete = Diagnoser && !isSFINAEContext();
6650       if (Diagnoser)
6651         diagnoseMissingImport(Loc, SuggestedDef, /*NeedDefinition*/true,
6652                               /*Recover*/TreatAsComplete);
6653       return !TreatAsComplete;
6654     }
6655 
6656     return false;
6657   }
6658 
6659   const TagType *Tag = T->getAs<TagType>();
6660   const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
6661 
6662   // If there's an unimported definition of this type in a module (for
6663   // instance, because we forward declared it, then imported the definition),
6664   // import that definition now.
6665   //
6666   // FIXME: What about other cases where an import extends a redeclaration
6667   // chain for a declaration that can be accessed through a mechanism other
6668   // than name lookup (eg, referenced in a template, or a variable whose type
6669   // could be completed by the module)?
6670   //
6671   // FIXME: Should we map through to the base array element type before
6672   // checking for a tag type?
6673   if (Tag || IFace) {
6674     NamedDecl *D =
6675         Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
6676 
6677     // Avoid diagnosing invalid decls as incomplete.
6678     if (D->isInvalidDecl())
6679       return true;
6680 
6681     // Give the external AST source a chance to complete the type.
6682     if (auto *Source = Context.getExternalSource()) {
6683       if (Tag)
6684         Source->CompleteType(Tag->getDecl());
6685       else
6686         Source->CompleteType(IFace->getDecl());
6687 
6688       // If the external source completed the type, go through the motions
6689       // again to ensure we're allowed to use the completed type.
6690       if (!T->isIncompleteType())
6691         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
6692     }
6693   }
6694 
6695   // If we have a class template specialization or a class member of a
6696   // class template specialization, or an array with known size of such,
6697   // try to instantiate it.
6698   QualType MaybeTemplate = T;
6699   while (const ConstantArrayType *Array
6700            = Context.getAsConstantArrayType(MaybeTemplate))
6701     MaybeTemplate = Array->getElementType();
6702   if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
6703     bool Instantiated = false;
6704     bool Diagnosed = false;
6705     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
6706           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
6707       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
6708         Diagnosed = InstantiateClassTemplateSpecialization(
6709             Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
6710             /*Complain=*/Diagnoser);
6711         Instantiated = true;
6712       }
6713     } else if (CXXRecordDecl *Rec
6714                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
6715       CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
6716       if (!Rec->isBeingDefined() && Pattern) {
6717         MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
6718         assert(MSI && "Missing member specialization information?");
6719         // This record was instantiated from a class within a template.
6720         if (MSI->getTemplateSpecializationKind() !=
6721             TSK_ExplicitSpecialization) {
6722           Diagnosed = InstantiateClass(Loc, Rec, Pattern,
6723                                        getTemplateInstantiationArgs(Rec),
6724                                        TSK_ImplicitInstantiation,
6725                                        /*Complain=*/Diagnoser);
6726           Instantiated = true;
6727         }
6728       }
6729     }
6730 
6731     if (Instantiated) {
6732       // Instantiate* might have already complained that the template is not
6733       // defined, if we asked it to.
6734       if (Diagnoser && Diagnosed)
6735         return true;
6736       // If we instantiated a definition, check that it's usable, even if
6737       // instantiation produced an error, so that repeated calls to this
6738       // function give consistent answers.
6739       if (!T->isIncompleteType())
6740         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
6741     }
6742   }
6743 
6744   if (!Diagnoser)
6745     return true;
6746 
6747   // We have an incomplete type. Produce a diagnostic.
6748   if (Ident___float128 &&
6749       T == Context.getTypeDeclType(Context.getFloat128StubType())) {
6750     Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
6751     return true;
6752   }
6753 
6754   Diagnoser->diagnose(*this, Loc, T);
6755 
6756   // If the type was a forward declaration of a class/struct/union
6757   // type, produce a note.
6758   if (Tag && !Tag->getDecl()->isInvalidDecl())
6759     Diag(Tag->getDecl()->getLocation(),
6760          Tag->isBeingDefined() ? diag::note_type_being_defined
6761                                : diag::note_forward_declaration)
6762       << QualType(Tag, 0);
6763 
6764   // If the Objective-C class was a forward declaration, produce a note.
6765   if (IFace && !IFace->getDecl()->isInvalidDecl())
6766     Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
6767 
6768   // If we have external information that we can use to suggest a fix,
6769   // produce a note.
6770   if (ExternalSource)
6771     ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
6772 
6773   return true;
6774 }
6775 
6776 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6777                                unsigned DiagID) {
6778   BoundTypeDiagnoser<> Diagnoser(DiagID);
6779   return RequireCompleteType(Loc, T, Diagnoser);
6780 }
6781 
6782 /// \brief Get diagnostic %select index for tag kind for
6783 /// literal type diagnostic message.
6784 /// WARNING: Indexes apply to particular diagnostics only!
6785 ///
6786 /// \returns diagnostic %select index.
6787 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
6788   switch (Tag) {
6789   case TTK_Struct: return 0;
6790   case TTK_Interface: return 1;
6791   case TTK_Class:  return 2;
6792   default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
6793   }
6794 }
6795 
6796 /// @brief Ensure that the type T is a literal type.
6797 ///
6798 /// This routine checks whether the type @p T is a literal type. If @p T is an
6799 /// incomplete type, an attempt is made to complete it. If @p T is a literal
6800 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
6801 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
6802 /// it the type @p T), along with notes explaining why the type is not a
6803 /// literal type, and returns true.
6804 ///
6805 /// @param Loc  The location in the source that the non-literal type
6806 /// diagnostic should refer to.
6807 ///
6808 /// @param T  The type that this routine is examining for literalness.
6809 ///
6810 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
6811 ///
6812 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
6813 /// @c false otherwise.
6814 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
6815                               TypeDiagnoser &Diagnoser) {
6816   assert(!T->isDependentType() && "type should not be dependent");
6817 
6818   QualType ElemType = Context.getBaseElementType(T);
6819   if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
6820       T->isLiteralType(Context))
6821     return false;
6822 
6823   Diagnoser.diagnose(*this, Loc, T);
6824 
6825   if (T->isVariableArrayType())
6826     return true;
6827 
6828   const RecordType *RT = ElemType->getAs<RecordType>();
6829   if (!RT)
6830     return true;
6831 
6832   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6833 
6834   // A partially-defined class type can't be a literal type, because a literal
6835   // class type must have a trivial destructor (which can't be checked until
6836   // the class definition is complete).
6837   if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
6838     return true;
6839 
6840   // If the class has virtual base classes, then it's not an aggregate, and
6841   // cannot have any constexpr constructors or a trivial default constructor,
6842   // so is non-literal. This is better to diagnose than the resulting absence
6843   // of constexpr constructors.
6844   if (RD->getNumVBases()) {
6845     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
6846       << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
6847     for (const auto &I : RD->vbases())
6848       Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
6849           << I.getSourceRange();
6850   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
6851              !RD->hasTrivialDefaultConstructor()) {
6852     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
6853   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
6854     for (const auto &I : RD->bases()) {
6855       if (!I.getType()->isLiteralType(Context)) {
6856         Diag(I.getLocStart(),
6857              diag::note_non_literal_base_class)
6858           << RD << I.getType() << I.getSourceRange();
6859         return true;
6860       }
6861     }
6862     for (const auto *I : RD->fields()) {
6863       if (!I->getType()->isLiteralType(Context) ||
6864           I->getType().isVolatileQualified()) {
6865         Diag(I->getLocation(), diag::note_non_literal_field)
6866           << RD << I << I->getType()
6867           << I->getType().isVolatileQualified();
6868         return true;
6869       }
6870     }
6871   } else if (!RD->hasTrivialDestructor()) {
6872     // All fields and bases are of literal types, so have trivial destructors.
6873     // If this class's destructor is non-trivial it must be user-declared.
6874     CXXDestructorDecl *Dtor = RD->getDestructor();
6875     assert(Dtor && "class has literal fields and bases but no dtor?");
6876     if (!Dtor)
6877       return true;
6878 
6879     Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
6880          diag::note_non_literal_user_provided_dtor :
6881          diag::note_non_literal_nontrivial_dtor) << RD;
6882     if (!Dtor->isUserProvided())
6883       SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
6884   }
6885 
6886   return true;
6887 }
6888 
6889 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
6890   BoundTypeDiagnoser<> Diagnoser(DiagID);
6891   return RequireLiteralType(Loc, T, Diagnoser);
6892 }
6893 
6894 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
6895 /// and qualified by the nested-name-specifier contained in SS.
6896 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
6897                                  const CXXScopeSpec &SS, QualType T) {
6898   if (T.isNull())
6899     return T;
6900   NestedNameSpecifier *NNS;
6901   if (SS.isValid())
6902     NNS = SS.getScopeRep();
6903   else {
6904     if (Keyword == ETK_None)
6905       return T;
6906     NNS = nullptr;
6907   }
6908   return Context.getElaboratedType(Keyword, NNS, T);
6909 }
6910 
6911 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
6912   ExprResult ER = CheckPlaceholderExpr(E);
6913   if (ER.isInvalid()) return QualType();
6914   E = ER.get();
6915 
6916   if (!getLangOpts().CPlusPlus && E->refersToBitField())
6917     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
6918 
6919   if (!E->isTypeDependent()) {
6920     QualType T = E->getType();
6921     if (const TagType *TT = T->getAs<TagType>())
6922       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
6923   }
6924   return Context.getTypeOfExprType(E);
6925 }
6926 
6927 /// getDecltypeForExpr - Given an expr, will return the decltype for
6928 /// that expression, according to the rules in C++11
6929 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
6930 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
6931   if (E->isTypeDependent())
6932     return S.Context.DependentTy;
6933 
6934   // C++11 [dcl.type.simple]p4:
6935   //   The type denoted by decltype(e) is defined as follows:
6936   //
6937   //     - if e is an unparenthesized id-expression or an unparenthesized class
6938   //       member access (5.2.5), decltype(e) is the type of the entity named
6939   //       by e. If there is no such entity, or if e names a set of overloaded
6940   //       functions, the program is ill-formed;
6941   //
6942   // We apply the same rules for Objective-C ivar and property references.
6943   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6944     if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
6945       return VD->getType();
6946   } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6947     if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
6948       return FD->getType();
6949   } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
6950     return IR->getDecl()->getType();
6951   } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
6952     if (PR->isExplicitProperty())
6953       return PR->getExplicitProperty()->getType();
6954   } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
6955     return PE->getType();
6956   }
6957 
6958   // C++11 [expr.lambda.prim]p18:
6959   //   Every occurrence of decltype((x)) where x is a possibly
6960   //   parenthesized id-expression that names an entity of automatic
6961   //   storage duration is treated as if x were transformed into an
6962   //   access to a corresponding data member of the closure type that
6963   //   would have been declared if x were an odr-use of the denoted
6964   //   entity.
6965   using namespace sema;
6966   if (S.getCurLambda()) {
6967     if (isa<ParenExpr>(E)) {
6968       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6969         if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6970           QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
6971           if (!T.isNull())
6972             return S.Context.getLValueReferenceType(T);
6973         }
6974       }
6975     }
6976   }
6977 
6978 
6979   // C++11 [dcl.type.simple]p4:
6980   //   [...]
6981   QualType T = E->getType();
6982   switch (E->getValueKind()) {
6983   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6984   //       type of e;
6985   case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
6986   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6987   //       type of e;
6988   case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
6989   //  - otherwise, decltype(e) is the type of e.
6990   case VK_RValue: break;
6991   }
6992 
6993   return T;
6994 }
6995 
6996 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
6997                                  bool AsUnevaluated) {
6998   ExprResult ER = CheckPlaceholderExpr(E);
6999   if (ER.isInvalid()) return QualType();
7000   E = ER.get();
7001 
7002   if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
7003       E->HasSideEffects(Context, false)) {
7004     // The expression operand for decltype is in an unevaluated expression
7005     // context, so side effects could result in unintended consequences.
7006     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7007   }
7008 
7009   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
7010 }
7011 
7012 QualType Sema::BuildUnaryTransformType(QualType BaseType,
7013                                        UnaryTransformType::UTTKind UKind,
7014                                        SourceLocation Loc) {
7015   switch (UKind) {
7016   case UnaryTransformType::EnumUnderlyingType:
7017     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
7018       Diag(Loc, diag::err_only_enums_have_underlying_types);
7019       return QualType();
7020     } else {
7021       QualType Underlying = BaseType;
7022       if (!BaseType->isDependentType()) {
7023         // The enum could be incomplete if we're parsing its definition or
7024         // recovering from an error.
7025         NamedDecl *FwdDecl = nullptr;
7026         if (BaseType->isIncompleteType(&FwdDecl)) {
7027           Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
7028           Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
7029           return QualType();
7030         }
7031 
7032         EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
7033         assert(ED && "EnumType has no EnumDecl");
7034 
7035         DiagnoseUseOfDecl(ED, Loc);
7036 
7037         Underlying = ED->getIntegerType();
7038         assert(!Underlying.isNull());
7039       }
7040       return Context.getUnaryTransformType(BaseType, Underlying,
7041                                         UnaryTransformType::EnumUnderlyingType);
7042     }
7043   }
7044   llvm_unreachable("unknown unary transform type");
7045 }
7046 
7047 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
7048   if (!T->isDependentType()) {
7049     // FIXME: It isn't entirely clear whether incomplete atomic types
7050     // are allowed or not; for simplicity, ban them for the moment.
7051     if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
7052       return QualType();
7053 
7054     int DisallowedKind = -1;
7055     if (T->isArrayType())
7056       DisallowedKind = 1;
7057     else if (T->isFunctionType())
7058       DisallowedKind = 2;
7059     else if (T->isReferenceType())
7060       DisallowedKind = 3;
7061     else if (T->isAtomicType())
7062       DisallowedKind = 4;
7063     else if (T.hasQualifiers())
7064       DisallowedKind = 5;
7065     else if (!T.isTriviallyCopyableType(Context))
7066       // Some other non-trivially-copyable type (probably a C++ class)
7067       DisallowedKind = 6;
7068 
7069     if (DisallowedKind != -1) {
7070       Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
7071       return QualType();
7072     }
7073 
7074     // FIXME: Do we need any handling for ARC here?
7075   }
7076 
7077   // Build the pointer type.
7078   return Context.getAtomicType(T);
7079 }
7080