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