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