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