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