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