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