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