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