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 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1004                                       SourceLocation ProtocolLAngleLoc,
1005                                       ArrayRef<ObjCProtocolDecl *> Protocols,
1006                                       ArrayRef<SourceLocation> ProtocolLocs,
1007                                       SourceLocation ProtocolRAngleLoc,
1008                                       bool FailOnError) {
1009   QualType Result = QualType(Decl->getTypeForDecl(), 0);
1010   if (!Protocols.empty()) {
1011     bool HasError;
1012     Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1013                                                  HasError);
1014     if (HasError) {
1015       Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1016         << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1017       if (FailOnError) Result = QualType();
1018     }
1019     if (FailOnError && Result.isNull())
1020       return QualType();
1021   }
1022 
1023   return Result;
1024 }
1025 
1026 QualType Sema::BuildObjCObjectType(QualType BaseType,
1027                                    SourceLocation Loc,
1028                                    SourceLocation TypeArgsLAngleLoc,
1029                                    ArrayRef<TypeSourceInfo *> TypeArgs,
1030                                    SourceLocation TypeArgsRAngleLoc,
1031                                    SourceLocation ProtocolLAngleLoc,
1032                                    ArrayRef<ObjCProtocolDecl *> Protocols,
1033                                    ArrayRef<SourceLocation> ProtocolLocs,
1034                                    SourceLocation ProtocolRAngleLoc,
1035                                    bool FailOnError) {
1036   QualType Result = BaseType;
1037   if (!TypeArgs.empty()) {
1038     Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1039                                SourceRange(TypeArgsLAngleLoc,
1040                                            TypeArgsRAngleLoc),
1041                                FailOnError);
1042     if (FailOnError && Result.isNull())
1043       return QualType();
1044   }
1045 
1046   if (!Protocols.empty()) {
1047     bool HasError;
1048     Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1049                                                  HasError);
1050     if (HasError) {
1051       Diag(Loc, diag::err_invalid_protocol_qualifiers)
1052         << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1053       if (FailOnError) Result = QualType();
1054     }
1055     if (FailOnError && Result.isNull())
1056       return QualType();
1057   }
1058 
1059   return Result;
1060 }
1061 
1062 TypeResult Sema::actOnObjCProtocolQualifierType(
1063              SourceLocation lAngleLoc,
1064              ArrayRef<Decl *> protocols,
1065              ArrayRef<SourceLocation> protocolLocs,
1066              SourceLocation rAngleLoc) {
1067   // Form id<protocol-list>.
1068   QualType Result = Context.getObjCObjectType(
1069                       Context.ObjCBuiltinIdTy, { },
1070                       llvm::makeArrayRef(
1071                         (ObjCProtocolDecl * const *)protocols.data(),
1072                         protocols.size()),
1073                       false);
1074   Result = Context.getObjCObjectPointerType(Result);
1075 
1076   TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1077   TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1078 
1079   auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1080   ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1081 
1082   auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1083                         .castAs<ObjCObjectTypeLoc>();
1084   ObjCObjectTL.setHasBaseTypeAsWritten(false);
1085   ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1086 
1087   // No type arguments.
1088   ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1089   ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1090 
1091   // Fill in protocol qualifiers.
1092   ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1093   ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1094   for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1095     ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1096 
1097   // We're done. Return the completed type to the parser.
1098   return CreateParsedType(Result, ResultTInfo);
1099 }
1100 
1101 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1102              Scope *S,
1103              SourceLocation Loc,
1104              ParsedType BaseType,
1105              SourceLocation TypeArgsLAngleLoc,
1106              ArrayRef<ParsedType> TypeArgs,
1107              SourceLocation TypeArgsRAngleLoc,
1108              SourceLocation ProtocolLAngleLoc,
1109              ArrayRef<Decl *> Protocols,
1110              ArrayRef<SourceLocation> ProtocolLocs,
1111              SourceLocation ProtocolRAngleLoc) {
1112   TypeSourceInfo *BaseTypeInfo = nullptr;
1113   QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1114   if (T.isNull())
1115     return true;
1116 
1117   // Handle missing type-source info.
1118   if (!BaseTypeInfo)
1119     BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1120 
1121   // Extract type arguments.
1122   SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1123   for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1124     TypeSourceInfo *TypeArgInfo = nullptr;
1125     QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1126     if (TypeArg.isNull()) {
1127       ActualTypeArgInfos.clear();
1128       break;
1129     }
1130 
1131     assert(TypeArgInfo && "No type source info?");
1132     ActualTypeArgInfos.push_back(TypeArgInfo);
1133   }
1134 
1135   // Build the object type.
1136   QualType Result = BuildObjCObjectType(
1137       T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1138       TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1139       ProtocolLAngleLoc,
1140       llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1141                          Protocols.size()),
1142       ProtocolLocs, ProtocolRAngleLoc,
1143       /*FailOnError=*/false);
1144 
1145   if (Result == T)
1146     return BaseType;
1147 
1148   // Create source information for this type.
1149   TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1150   TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1151 
1152   // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1153   // object pointer type. Fill in source information for it.
1154   if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1155     // The '*' is implicit.
1156     ObjCObjectPointerTL.setStarLoc(SourceLocation());
1157     ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1158   }
1159 
1160   if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1161     // Protocol qualifier information.
1162     if (OTPTL.getNumProtocols() > 0) {
1163       assert(OTPTL.getNumProtocols() == Protocols.size());
1164       OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1165       OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1166       for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1167         OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1168     }
1169 
1170     // We're done. Return the completed type to the parser.
1171     return CreateParsedType(Result, ResultTInfo);
1172   }
1173 
1174   auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1175 
1176   // Type argument information.
1177   if (ObjCObjectTL.getNumTypeArgs() > 0) {
1178     assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1179     ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1180     ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1181     for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1182       ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1183   } else {
1184     ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1185     ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1186   }
1187 
1188   // Protocol qualifier information.
1189   if (ObjCObjectTL.getNumProtocols() > 0) {
1190     assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1191     ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1192     ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1193     for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1194       ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1195   } else {
1196     ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1197     ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1198   }
1199 
1200   // Base type.
1201   ObjCObjectTL.setHasBaseTypeAsWritten(true);
1202   if (ObjCObjectTL.getType() == T)
1203     ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1204   else
1205     ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1206 
1207   // We're done. Return the completed type to the parser.
1208   return CreateParsedType(Result, ResultTInfo);
1209 }
1210 
1211 static StringRef getImageAccessAttrStr(AttributeList *attrs) {
1212   if (attrs) {
1213 
1214     AttributeList *Next;
1215     do {
1216       AttributeList &Attr = *attrs;
1217       Next = Attr.getNext();
1218       if (Attr.getKind() == AttributeList::AT_OpenCLAccess) {
1219         return Attr.getName()->getName();
1220       }
1221     } while (Next);
1222   }
1223   return "";
1224 }
1225 
1226 /// \brief Convert the specified declspec to the appropriate type
1227 /// object.
1228 /// \param state Specifies the declarator containing the declaration specifier
1229 /// to be converted, along with other associated processing state.
1230 /// \returns The type described by the declaration specifiers.  This function
1231 /// never returns null.
1232 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1233   // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1234   // checking.
1235 
1236   Sema &S = state.getSema();
1237   Declarator &declarator = state.getDeclarator();
1238   const DeclSpec &DS = declarator.getDeclSpec();
1239   SourceLocation DeclLoc = declarator.getIdentifierLoc();
1240   if (DeclLoc.isInvalid())
1241     DeclLoc = DS.getLocStart();
1242 
1243   ASTContext &Context = S.Context;
1244 
1245   QualType Result;
1246   switch (DS.getTypeSpecType()) {
1247   case DeclSpec::TST_void:
1248     Result = Context.VoidTy;
1249     break;
1250   case DeclSpec::TST_char:
1251     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1252       Result = Context.CharTy;
1253     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1254       Result = Context.SignedCharTy;
1255     else {
1256       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1257              "Unknown TSS value");
1258       Result = Context.UnsignedCharTy;
1259     }
1260     break;
1261   case DeclSpec::TST_wchar:
1262     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1263       Result = Context.WCharTy;
1264     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1265       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1266         << DS.getSpecifierName(DS.getTypeSpecType(),
1267                                Context.getPrintingPolicy());
1268       Result = Context.getSignedWCharType();
1269     } else {
1270       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1271         "Unknown TSS value");
1272       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1273         << DS.getSpecifierName(DS.getTypeSpecType(),
1274                                Context.getPrintingPolicy());
1275       Result = Context.getUnsignedWCharType();
1276     }
1277     break;
1278   case DeclSpec::TST_char16:
1279       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1280         "Unknown TSS value");
1281       Result = Context.Char16Ty;
1282     break;
1283   case DeclSpec::TST_char32:
1284       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1285         "Unknown TSS value");
1286       Result = Context.Char32Ty;
1287     break;
1288   case DeclSpec::TST_unspecified:
1289     // If this is a missing declspec in a block literal return context, then it
1290     // is inferred from the return statements inside the block.
1291     // The declspec is always missing in a lambda expr context; it is either
1292     // specified with a trailing return type or inferred.
1293     if (S.getLangOpts().CPlusPlus14 &&
1294         declarator.getContext() == Declarator::LambdaExprContext) {
1295       // In C++1y, a lambda's implicit return type is 'auto'.
1296       Result = Context.getAutoDeductType();
1297       break;
1298     } else if (declarator.getContext() == Declarator::LambdaExprContext ||
1299                checkOmittedBlockReturnType(S, declarator,
1300                                            Context.DependentTy)) {
1301       Result = Context.DependentTy;
1302       break;
1303     }
1304 
1305     // Unspecified typespec defaults to int in C90.  However, the C90 grammar
1306     // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1307     // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
1308     // Note that the one exception to this is function definitions, which are
1309     // allowed to be completely missing a declspec.  This is handled in the
1310     // parser already though by it pretending to have seen an 'int' in this
1311     // case.
1312     if (S.getLangOpts().ImplicitInt) {
1313       // In C89 mode, we only warn if there is a completely missing declspec
1314       // when one is not allowed.
1315       if (DS.isEmpty()) {
1316         S.Diag(DeclLoc, diag::ext_missing_declspec)
1317           << DS.getSourceRange()
1318         << FixItHint::CreateInsertion(DS.getLocStart(), "int");
1319       }
1320     } else if (!DS.hasTypeSpecifier()) {
1321       // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
1322       // "At least one type specifier shall be given in the declaration
1323       // specifiers in each declaration, and in the specifier-qualifier list in
1324       // each struct declaration and type name."
1325       if (S.getLangOpts().CPlusPlus) {
1326         S.Diag(DeclLoc, diag::err_missing_type_specifier)
1327           << DS.getSourceRange();
1328 
1329         // When this occurs in C++ code, often something is very broken with the
1330         // value being declared, poison it as invalid so we don't get chains of
1331         // errors.
1332         declarator.setInvalidType(true);
1333       } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1334         S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1335           << DS.getSourceRange();
1336         declarator.setInvalidType(true);
1337       } else {
1338         S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1339           << DS.getSourceRange();
1340       }
1341     }
1342 
1343     // FALL THROUGH.
1344   case DeclSpec::TST_int: {
1345     if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
1346       switch (DS.getTypeSpecWidth()) {
1347       case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1348       case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
1349       case DeclSpec::TSW_long:        Result = Context.LongTy; break;
1350       case DeclSpec::TSW_longlong:
1351         Result = Context.LongLongTy;
1352 
1353         // 'long long' is a C99 or C++11 feature.
1354         if (!S.getLangOpts().C99) {
1355           if (S.getLangOpts().CPlusPlus)
1356             S.Diag(DS.getTypeSpecWidthLoc(),
1357                    S.getLangOpts().CPlusPlus11 ?
1358                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1359           else
1360             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1361         }
1362         break;
1363       }
1364     } else {
1365       switch (DS.getTypeSpecWidth()) {
1366       case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1367       case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
1368       case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
1369       case DeclSpec::TSW_longlong:
1370         Result = Context.UnsignedLongLongTy;
1371 
1372         // 'long long' is a C99 or C++11 feature.
1373         if (!S.getLangOpts().C99) {
1374           if (S.getLangOpts().CPlusPlus)
1375             S.Diag(DS.getTypeSpecWidthLoc(),
1376                    S.getLangOpts().CPlusPlus11 ?
1377                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1378           else
1379             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1380         }
1381         break;
1382       }
1383     }
1384     break;
1385   }
1386   case DeclSpec::TST_int128:
1387     if (!S.Context.getTargetInfo().hasInt128Type())
1388       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1389         << "__int128";
1390     if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1391       Result = Context.UnsignedInt128Ty;
1392     else
1393       Result = Context.Int128Ty;
1394     break;
1395   case DeclSpec::TST_half: Result = Context.HalfTy; break;
1396   case DeclSpec::TST_float: Result = Context.FloatTy; break;
1397   case DeclSpec::TST_double:
1398     if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1399       Result = Context.LongDoubleTy;
1400     else
1401       Result = Context.DoubleTy;
1402 
1403     if (S.getLangOpts().OpenCL &&
1404         !((S.getLangOpts().OpenCLVersion >= 120) ||
1405           S.getOpenCLOptions().cl_khr_fp64)) {
1406       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1407           << Result << "cl_khr_fp64";
1408       declarator.setInvalidType(true);
1409     }
1410     break;
1411   case DeclSpec::TST_float128:
1412     if (!S.Context.getTargetInfo().hasFloat128Type())
1413       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1414         << "__float128";
1415     Result = Context.Float128Ty;
1416     break;
1417   case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1418     break;
1419   case DeclSpec::TST_decimal32:    // _Decimal32
1420   case DeclSpec::TST_decimal64:    // _Decimal64
1421   case DeclSpec::TST_decimal128:   // _Decimal128
1422     S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1423     Result = Context.IntTy;
1424     declarator.setInvalidType(true);
1425     break;
1426   case DeclSpec::TST_class:
1427   case DeclSpec::TST_enum:
1428   case DeclSpec::TST_union:
1429   case DeclSpec::TST_struct:
1430   case DeclSpec::TST_interface: {
1431     TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
1432     if (!D) {
1433       // This can happen in C++ with ambiguous lookups.
1434       Result = Context.IntTy;
1435       declarator.setInvalidType(true);
1436       break;
1437     }
1438 
1439     // If the type is deprecated or unavailable, diagnose it.
1440     S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1441 
1442     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1443            DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1444 
1445     // TypeQuals handled by caller.
1446     Result = Context.getTypeDeclType(D);
1447 
1448     // In both C and C++, make an ElaboratedType.
1449     ElaboratedTypeKeyword Keyword
1450       = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1451     Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
1452     break;
1453   }
1454   case DeclSpec::TST_typename: {
1455     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1456            DS.getTypeSpecSign() == 0 &&
1457            "Can't handle qualifiers on typedef names yet!");
1458     Result = S.GetTypeFromParser(DS.getRepAsType());
1459     if (Result.isNull()) {
1460       declarator.setInvalidType(true);
1461     } else if (S.getLangOpts().OpenCL) {
1462       if (Result->getAs<AtomicType>()) {
1463         StringRef TypeName = Result.getBaseTypeIdentifier()->getName();
1464         bool NoExtTypes =
1465             llvm::StringSwitch<bool>(TypeName)
1466                 .Cases("atomic_int", "atomic_uint", "atomic_float",
1467                        "atomic_flag", true)
1468                 .Default(false);
1469         if (!S.getOpenCLOptions().cl_khr_int64_base_atomics && !NoExtTypes) {
1470           S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1471               << Result << "cl_khr_int64_base_atomics";
1472           declarator.setInvalidType(true);
1473         }
1474         if (!S.getOpenCLOptions().cl_khr_int64_extended_atomics &&
1475             !NoExtTypes) {
1476           S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1477               << Result << "cl_khr_int64_extended_atomics";
1478           declarator.setInvalidType(true);
1479         }
1480         if (!S.getOpenCLOptions().cl_khr_fp64 &&
1481             !TypeName.compare("atomic_double")) {
1482           S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1483               << Result << "cl_khr_fp64";
1484           declarator.setInvalidType(true);
1485         }
1486       } else if (!S.getOpenCLOptions().cl_khr_gl_msaa_sharing &&
1487                  (Result->isOCLImage2dArrayMSAADepthROType() ||
1488                   Result->isOCLImage2dArrayMSAADepthWOType() ||
1489                   Result->isOCLImage2dArrayMSAADepthRWType() ||
1490                   Result->isOCLImage2dArrayMSAAROType() ||
1491                   Result->isOCLImage2dArrayMSAARWType() ||
1492                   Result->isOCLImage2dArrayMSAAWOType() ||
1493                   Result->isOCLImage2dMSAADepthROType() ||
1494                   Result->isOCLImage2dMSAADepthRWType() ||
1495                   Result->isOCLImage2dMSAADepthWOType() ||
1496                   Result->isOCLImage2dMSAAROType() ||
1497                   Result->isOCLImage2dMSAARWType() ||
1498                   Result->isOCLImage2dMSAAWOType())) {
1499         S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1500             << Result << "cl_khr_gl_msaa_sharing";
1501         declarator.setInvalidType(true);
1502       }
1503     }
1504 
1505     // TypeQuals handled by caller.
1506     break;
1507   }
1508   case DeclSpec::TST_typeofType:
1509     // FIXME: Preserve type source info.
1510     Result = S.GetTypeFromParser(DS.getRepAsType());
1511     assert(!Result.isNull() && "Didn't get a type for typeof?");
1512     if (!Result->isDependentType())
1513       if (const TagType *TT = Result->getAs<TagType>())
1514         S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1515     // TypeQuals handled by caller.
1516     Result = Context.getTypeOfType(Result);
1517     break;
1518   case DeclSpec::TST_typeofExpr: {
1519     Expr *E = DS.getRepAsExpr();
1520     assert(E && "Didn't get an expression for typeof?");
1521     // TypeQuals handled by caller.
1522     Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1523     if (Result.isNull()) {
1524       Result = Context.IntTy;
1525       declarator.setInvalidType(true);
1526     }
1527     break;
1528   }
1529   case DeclSpec::TST_decltype: {
1530     Expr *E = DS.getRepAsExpr();
1531     assert(E && "Didn't get an expression for decltype?");
1532     // TypeQuals handled by caller.
1533     Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1534     if (Result.isNull()) {
1535       Result = Context.IntTy;
1536       declarator.setInvalidType(true);
1537     }
1538     break;
1539   }
1540   case DeclSpec::TST_underlyingType:
1541     Result = S.GetTypeFromParser(DS.getRepAsType());
1542     assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1543     Result = S.BuildUnaryTransformType(Result,
1544                                        UnaryTransformType::EnumUnderlyingType,
1545                                        DS.getTypeSpecTypeLoc());
1546     if (Result.isNull()) {
1547       Result = Context.IntTy;
1548       declarator.setInvalidType(true);
1549     }
1550     break;
1551 
1552   case DeclSpec::TST_auto:
1553     // TypeQuals handled by caller.
1554     // If auto is mentioned in a lambda parameter context, convert it to a
1555     // template parameter type immediately, with the appropriate depth and
1556     // index, and update sema's state (LambdaScopeInfo) for the current lambda
1557     // being analyzed (which tracks the invented type template parameter).
1558     if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1559       sema::LambdaScopeInfo *LSI = S.getCurLambda();
1560       assert(LSI && "No LambdaScopeInfo on the stack!");
1561       const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1562       const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1563       const bool IsParameterPack = declarator.hasEllipsis();
1564 
1565       // Turns out we must create the TemplateTypeParmDecl here to
1566       // retrieve the corresponding template parameter type.
1567       TemplateTypeParmDecl *CorrespondingTemplateParam =
1568         TemplateTypeParmDecl::Create(Context,
1569         // Temporarily add to the TranslationUnit DeclContext.  When the
1570         // associated TemplateParameterList is attached to a template
1571         // declaration (such as FunctionTemplateDecl), the DeclContext
1572         // for each template parameter gets updated appropriately via
1573         // a call to AdoptTemplateParameterList.
1574         Context.getTranslationUnitDecl(),
1575         /*KeyLoc*/ SourceLocation(),
1576         /*NameLoc*/ declarator.getLocStart(),
1577         TemplateParameterDepth,
1578         AutoParameterPosition,  // our template param index
1579         /* Identifier*/ nullptr, false, IsParameterPack);
1580       LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1581       // Replace the 'auto' in the function parameter with this invented
1582       // template type parameter.
1583       Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1584     } else {
1585       // If auto appears in the declaration of a template parameter, treat
1586       // the parameter as type-dependent.
1587       bool IsDependent =
1588         S.getLangOpts().CPlusPlus1z &&
1589         declarator.getContext() == Declarator::TemplateParamContext;
1590       Result = Context.getAutoType(QualType(),
1591                                    AutoTypeKeyword::Auto,
1592                                    IsDependent);
1593     }
1594     break;
1595 
1596   case DeclSpec::TST_auto_type:
1597     Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1598     break;
1599 
1600   case DeclSpec::TST_decltype_auto:
1601     Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1602                                  /*IsDependent*/ false);
1603     break;
1604 
1605   case DeclSpec::TST_unknown_anytype:
1606     Result = Context.UnknownAnyTy;
1607     break;
1608 
1609   case DeclSpec::TST_atomic:
1610     Result = S.GetTypeFromParser(DS.getRepAsType());
1611     assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1612     Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1613     if (Result.isNull()) {
1614       Result = Context.IntTy;
1615       declarator.setInvalidType(true);
1616     }
1617     break;
1618 
1619 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1620   case DeclSpec::TST_##ImgType##_t: \
1621     Result = llvm::StringSwitch<QualType>( \
1622                  getImageAccessAttrStr(DS.getAttributes().getList())) \
1623                  .Cases("write_only", "__write_only", Context.Id##WOTy) \
1624                  .Cases("read_write", "__read_write", Context.Id##RWTy) \
1625                  .Default(Context.Id##ROTy); \
1626     break;
1627 #include "clang/Basic/OpenCLImageTypes.def"
1628 
1629   case DeclSpec::TST_error:
1630     Result = Context.IntTy;
1631     declarator.setInvalidType(true);
1632     break;
1633   }
1634 
1635   // Handle complex types.
1636   if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1637     if (S.getLangOpts().Freestanding)
1638       S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1639     Result = Context.getComplexType(Result);
1640   } else if (DS.isTypeAltiVecVector()) {
1641     unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1642     assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1643     VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1644     if (DS.isTypeAltiVecPixel())
1645       VecKind = VectorType::AltiVecPixel;
1646     else if (DS.isTypeAltiVecBool())
1647       VecKind = VectorType::AltiVecBool;
1648     Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1649   }
1650 
1651   // FIXME: Imaginary.
1652   if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1653     S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1654 
1655   // Before we process any type attributes, synthesize a block literal
1656   // function declarator if necessary.
1657   if (declarator.getContext() == Declarator::BlockLiteralContext)
1658     maybeSynthesizeBlockSignature(state, Result);
1659 
1660   // Apply any type attributes from the decl spec.  This may cause the
1661   // list of type attributes to be temporarily saved while the type
1662   // attributes are pushed around.
1663   // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1664   if (!DS.isTypeSpecPipe())
1665       processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList());
1666 
1667   // Apply const/volatile/restrict qualifiers to T.
1668   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1669     // Warn about CV qualifiers on function types.
1670     // C99 6.7.3p8:
1671     //   If the specification of a function type includes any type qualifiers,
1672     //   the behavior is undefined.
1673     // C++11 [dcl.fct]p7:
1674     //   The effect of a cv-qualifier-seq in a function declarator is not the
1675     //   same as adding cv-qualification on top of the function type. In the
1676     //   latter case, the cv-qualifiers are ignored.
1677     if (TypeQuals && Result->isFunctionType()) {
1678       diagnoseAndRemoveTypeQualifiers(
1679           S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1680           S.getLangOpts().CPlusPlus
1681               ? diag::warn_typecheck_function_qualifiers_ignored
1682               : diag::warn_typecheck_function_qualifiers_unspecified);
1683       // No diagnostic for 'restrict' or '_Atomic' applied to a
1684       // function type; we'll diagnose those later, in BuildQualifiedType.
1685     }
1686 
1687     // C++11 [dcl.ref]p1:
1688     //   Cv-qualified references are ill-formed except when the
1689     //   cv-qualifiers are introduced through the use of a typedef-name
1690     //   or decltype-specifier, in which case the cv-qualifiers are ignored.
1691     //
1692     // There don't appear to be any other contexts in which a cv-qualified
1693     // reference type could be formed, so the 'ill-formed' clause here appears
1694     // to never happen.
1695     if (TypeQuals && Result->isReferenceType()) {
1696       diagnoseAndRemoveTypeQualifiers(
1697           S, DS, TypeQuals, Result,
1698           DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1699           diag::warn_typecheck_reference_qualifiers);
1700     }
1701 
1702     // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1703     // than once in the same specifier-list or qualifier-list, either directly
1704     // or via one or more typedefs."
1705     if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1706         && TypeQuals & Result.getCVRQualifiers()) {
1707       if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1708         S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1709           << "const";
1710       }
1711 
1712       if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1713         S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1714           << "volatile";
1715       }
1716 
1717       // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1718       // produce a warning in this case.
1719     }
1720 
1721     QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1722 
1723     // If adding qualifiers fails, just use the unqualified type.
1724     if (Qualified.isNull())
1725       declarator.setInvalidType(true);
1726     else
1727       Result = Qualified;
1728   }
1729 
1730   assert(!Result.isNull() && "This function should not return a null type");
1731   return Result;
1732 }
1733 
1734 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1735   if (Entity)
1736     return Entity.getAsString();
1737 
1738   return "type name";
1739 }
1740 
1741 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1742                                   Qualifiers Qs, const DeclSpec *DS) {
1743   if (T.isNull())
1744     return QualType();
1745 
1746   // Ignore any attempt to form a cv-qualified reference.
1747   if (T->isReferenceType()) {
1748     Qs.removeConst();
1749     Qs.removeVolatile();
1750   }
1751 
1752   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1753   // object or incomplete types shall not be restrict-qualified."
1754   if (Qs.hasRestrict()) {
1755     unsigned DiagID = 0;
1756     QualType ProblemTy;
1757 
1758     if (T->isAnyPointerType() || T->isReferenceType() ||
1759         T->isMemberPointerType()) {
1760       QualType EltTy;
1761       if (T->isObjCObjectPointerType())
1762         EltTy = T;
1763       else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1764         EltTy = PTy->getPointeeType();
1765       else
1766         EltTy = T->getPointeeType();
1767 
1768       // If we have a pointer or reference, the pointee must have an object
1769       // incomplete type.
1770       if (!EltTy->isIncompleteOrObjectType()) {
1771         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1772         ProblemTy = EltTy;
1773       }
1774     } else if (!T->isDependentType()) {
1775       DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1776       ProblemTy = T;
1777     }
1778 
1779     if (DiagID) {
1780       Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1781       Qs.removeRestrict();
1782     }
1783   }
1784 
1785   return Context.getQualifiedType(T, Qs);
1786 }
1787 
1788 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1789                                   unsigned CVRAU, const DeclSpec *DS) {
1790   if (T.isNull())
1791     return QualType();
1792 
1793   // Ignore any attempt to form a cv-qualified reference.
1794   if (T->isReferenceType())
1795     CVRAU &=
1796         ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1797 
1798   // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1799   // TQ_unaligned;
1800   unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1801 
1802   // C11 6.7.3/5:
1803   //   If the same qualifier appears more than once in the same
1804   //   specifier-qualifier-list, either directly or via one or more typedefs,
1805   //   the behavior is the same as if it appeared only once.
1806   //
1807   // It's not specified what happens when the _Atomic qualifier is applied to
1808   // a type specified with the _Atomic specifier, but we assume that this
1809   // should be treated as if the _Atomic qualifier appeared multiple times.
1810   if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1811     // C11 6.7.3/5:
1812     //   If other qualifiers appear along with the _Atomic qualifier in a
1813     //   specifier-qualifier-list, the resulting type is the so-qualified
1814     //   atomic type.
1815     //
1816     // Don't need to worry about array types here, since _Atomic can't be
1817     // applied to such types.
1818     SplitQualType Split = T.getSplitUnqualifiedType();
1819     T = BuildAtomicType(QualType(Split.Ty, 0),
1820                         DS ? DS->getAtomicSpecLoc() : Loc);
1821     if (T.isNull())
1822       return T;
1823     Split.Quals.addCVRQualifiers(CVR);
1824     return BuildQualifiedType(T, Loc, Split.Quals);
1825   }
1826 
1827   Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1828   Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1829   return BuildQualifiedType(T, Loc, Q, DS);
1830 }
1831 
1832 /// \brief Build a paren type including \p T.
1833 QualType Sema::BuildParenType(QualType T) {
1834   return Context.getParenType(T);
1835 }
1836 
1837 /// Given that we're building a pointer or reference to the given
1838 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1839                                            SourceLocation loc,
1840                                            bool isReference) {
1841   // Bail out if retention is unrequired or already specified.
1842   if (!type->isObjCLifetimeType() ||
1843       type.getObjCLifetime() != Qualifiers::OCL_None)
1844     return type;
1845 
1846   Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1847 
1848   // If the object type is const-qualified, we can safely use
1849   // __unsafe_unretained.  This is safe (because there are no read
1850   // barriers), and it'll be safe to coerce anything but __weak* to
1851   // the resulting type.
1852   if (type.isConstQualified()) {
1853     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1854 
1855   // Otherwise, check whether the static type does not require
1856   // retaining.  This currently only triggers for Class (possibly
1857   // protocol-qualifed, and arrays thereof).
1858   } else if (type->isObjCARCImplicitlyUnretainedType()) {
1859     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1860 
1861   // If we are in an unevaluated context, like sizeof, skip adding a
1862   // qualification.
1863   } else if (S.isUnevaluatedContext()) {
1864     return type;
1865 
1866   // If that failed, give an error and recover using __strong.  __strong
1867   // is the option most likely to prevent spurious second-order diagnostics,
1868   // like when binding a reference to a field.
1869   } else {
1870     // These types can show up in private ivars in system headers, so
1871     // we need this to not be an error in those cases.  Instead we
1872     // want to delay.
1873     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1874       S.DelayedDiagnostics.add(
1875           sema::DelayedDiagnostic::makeForbiddenType(loc,
1876               diag::err_arc_indirect_no_ownership, type, isReference));
1877     } else {
1878       S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1879     }
1880     implicitLifetime = Qualifiers::OCL_Strong;
1881   }
1882   assert(implicitLifetime && "didn't infer any lifetime!");
1883 
1884   Qualifiers qs;
1885   qs.addObjCLifetime(implicitLifetime);
1886   return S.Context.getQualifiedType(type, qs);
1887 }
1888 
1889 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1890   std::string Quals =
1891     Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1892 
1893   switch (FnTy->getRefQualifier()) {
1894   case RQ_None:
1895     break;
1896 
1897   case RQ_LValue:
1898     if (!Quals.empty())
1899       Quals += ' ';
1900     Quals += '&';
1901     break;
1902 
1903   case RQ_RValue:
1904     if (!Quals.empty())
1905       Quals += ' ';
1906     Quals += "&&";
1907     break;
1908   }
1909 
1910   return Quals;
1911 }
1912 
1913 namespace {
1914 /// Kinds of declarator that cannot contain a qualified function type.
1915 ///
1916 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1917 ///     a function type with a cv-qualifier or a ref-qualifier can only appear
1918 ///     at the topmost level of a type.
1919 ///
1920 /// Parens and member pointers are permitted. We don't diagnose array and
1921 /// function declarators, because they don't allow function types at all.
1922 ///
1923 /// The values of this enum are used in diagnostics.
1924 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1925 } // end anonymous namespace
1926 
1927 /// Check whether the type T is a qualified function type, and if it is,
1928 /// diagnose that it cannot be contained within the given kind of declarator.
1929 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1930                                    QualifiedFunctionKind QFK) {
1931   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1932   const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1933   if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1934     return false;
1935 
1936   S.Diag(Loc, diag::err_compound_qualified_function_type)
1937     << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1938     << getFunctionQualifiersAsString(FPT);
1939   return true;
1940 }
1941 
1942 /// \brief Build a pointer type.
1943 ///
1944 /// \param T The type to which we'll be building a pointer.
1945 ///
1946 /// \param Loc The location of the entity whose type involves this
1947 /// pointer type or, if there is no such entity, the location of the
1948 /// type that will have pointer type.
1949 ///
1950 /// \param Entity The name of the entity that involves the pointer
1951 /// type, if known.
1952 ///
1953 /// \returns A suitable pointer type, if there are no
1954 /// errors. Otherwise, returns a NULL type.
1955 QualType Sema::BuildPointerType(QualType T,
1956                                 SourceLocation Loc, DeclarationName Entity) {
1957   if (T->isReferenceType()) {
1958     // C++ 8.3.2p4: There shall be no ... pointers to references ...
1959     Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1960       << getPrintableNameForEntity(Entity) << T;
1961     return QualType();
1962   }
1963 
1964   if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1965     return QualType();
1966 
1967   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1968 
1969   // In ARC, it is forbidden to build pointers to unqualified pointers.
1970   if (getLangOpts().ObjCAutoRefCount)
1971     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1972 
1973   // Build the pointer type.
1974   return Context.getPointerType(T);
1975 }
1976 
1977 /// \brief Build a reference type.
1978 ///
1979 /// \param T The type to which we'll be building a reference.
1980 ///
1981 /// \param Loc The location of the entity whose type involves this
1982 /// reference type or, if there is no such entity, the location of the
1983 /// type that will have reference type.
1984 ///
1985 /// \param Entity The name of the entity that involves the reference
1986 /// type, if known.
1987 ///
1988 /// \returns A suitable reference type, if there are no
1989 /// errors. Otherwise, returns a NULL type.
1990 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1991                                   SourceLocation Loc,
1992                                   DeclarationName Entity) {
1993   assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1994          "Unresolved overloaded function type");
1995 
1996   // C++0x [dcl.ref]p6:
1997   //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1998   //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1999   //   type T, an attempt to create the type "lvalue reference to cv TR" creates
2000   //   the type "lvalue reference to T", while an attempt to create the type
2001   //   "rvalue reference to cv TR" creates the type TR.
2002   bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
2003 
2004   // C++ [dcl.ref]p4: There shall be no references to references.
2005   //
2006   // According to C++ DR 106, references to references are only
2007   // diagnosed when they are written directly (e.g., "int & &"),
2008   // but not when they happen via a typedef:
2009   //
2010   //   typedef int& intref;
2011   //   typedef intref& intref2;
2012   //
2013   // Parser::ParseDeclaratorInternal diagnoses the case where
2014   // references are written directly; here, we handle the
2015   // collapsing of references-to-references as described in C++0x.
2016   // DR 106 and 540 introduce reference-collapsing into C++98/03.
2017 
2018   // C++ [dcl.ref]p1:
2019   //   A declarator that specifies the type "reference to cv void"
2020   //   is ill-formed.
2021   if (T->isVoidType()) {
2022     Diag(Loc, diag::err_reference_to_void);
2023     return QualType();
2024   }
2025 
2026   if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2027     return QualType();
2028 
2029   // In ARC, it is forbidden to build references to unqualified pointers.
2030   if (getLangOpts().ObjCAutoRefCount)
2031     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2032 
2033   // Handle restrict on references.
2034   if (LValueRef)
2035     return Context.getLValueReferenceType(T, SpelledAsLValue);
2036   return Context.getRValueReferenceType(T);
2037 }
2038 
2039 /// \brief Build a Pipe type.
2040 ///
2041 /// \param T The type to which we'll be building a Pipe.
2042 ///
2043 /// \param Loc We do not use it for now.
2044 ///
2045 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2046 /// NULL type.
2047 QualType Sema::BuildPipeType(QualType T, SourceLocation Loc) {
2048   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2049 
2050   // Build the pipe type.
2051   return Context.getPipeType(T);
2052 }
2053 
2054 /// Check whether the specified array size makes the array type a VLA.  If so,
2055 /// return true, if not, return the size of the array in SizeVal.
2056 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
2057   // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2058   // (like gnu99, but not c99) accept any evaluatable value as an extension.
2059   class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2060   public:
2061     VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
2062 
2063     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
2064     }
2065 
2066     void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
2067       S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2068     }
2069   } Diagnoser;
2070 
2071   return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2072                                            S.LangOpts.GNUMode ||
2073                                            S.LangOpts.OpenCL).isInvalid();
2074 }
2075 
2076 /// \brief Build an array type.
2077 ///
2078 /// \param T The type of each element in the array.
2079 ///
2080 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2081 ///
2082 /// \param ArraySize Expression describing the size of the array.
2083 ///
2084 /// \param Brackets The range from the opening '[' to the closing ']'.
2085 ///
2086 /// \param Entity The name of the entity that involves the array
2087 /// type, if known.
2088 ///
2089 /// \returns A suitable array type, if there are no errors. Otherwise,
2090 /// returns a NULL type.
2091 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2092                               Expr *ArraySize, unsigned Quals,
2093                               SourceRange Brackets, DeclarationName Entity) {
2094 
2095   SourceLocation Loc = Brackets.getBegin();
2096   if (getLangOpts().CPlusPlus) {
2097     // C++ [dcl.array]p1:
2098     //   T is called the array element type; this type shall not be a reference
2099     //   type, the (possibly cv-qualified) type void, a function type or an
2100     //   abstract class type.
2101     //
2102     // C++ [dcl.array]p3:
2103     //   When several "array of" specifications are adjacent, [...] only the
2104     //   first of the constant expressions that specify the bounds of the arrays
2105     //   may be omitted.
2106     //
2107     // Note: function types are handled in the common path with C.
2108     if (T->isReferenceType()) {
2109       Diag(Loc, diag::err_illegal_decl_array_of_references)
2110       << getPrintableNameForEntity(Entity) << T;
2111       return QualType();
2112     }
2113 
2114     if (T->isVoidType() || T->isIncompleteArrayType()) {
2115       Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2116       return QualType();
2117     }
2118 
2119     if (RequireNonAbstractType(Brackets.getBegin(), T,
2120                                diag::err_array_of_abstract_type))
2121       return QualType();
2122 
2123     // Mentioning a member pointer type for an array type causes us to lock in
2124     // an inheritance model, even if it's inside an unused typedef.
2125     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2126       if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2127         if (!MPTy->getClass()->isDependentType())
2128           (void)isCompleteType(Loc, T);
2129 
2130   } else {
2131     // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2132     // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2133     if (RequireCompleteType(Loc, T,
2134                             diag::err_illegal_decl_array_incomplete_type))
2135       return QualType();
2136   }
2137 
2138   if (T->isFunctionType()) {
2139     Diag(Loc, diag::err_illegal_decl_array_of_functions)
2140       << getPrintableNameForEntity(Entity) << T;
2141     return QualType();
2142   }
2143 
2144   if (const RecordType *EltTy = T->getAs<RecordType>()) {
2145     // If the element type is a struct or union that contains a variadic
2146     // array, accept it as a GNU extension: C99 6.7.2.1p2.
2147     if (EltTy->getDecl()->hasFlexibleArrayMember())
2148       Diag(Loc, diag::ext_flexible_array_in_array) << T;
2149   } else if (T->isObjCObjectType()) {
2150     Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2151     return QualType();
2152   }
2153 
2154   // Do placeholder conversions on the array size expression.
2155   if (ArraySize && ArraySize->hasPlaceholderType()) {
2156     ExprResult Result = CheckPlaceholderExpr(ArraySize);
2157     if (Result.isInvalid()) return QualType();
2158     ArraySize = Result.get();
2159   }
2160 
2161   // Do lvalue-to-rvalue conversions on the array size expression.
2162   if (ArraySize && !ArraySize->isRValue()) {
2163     ExprResult Result = DefaultLvalueConversion(ArraySize);
2164     if (Result.isInvalid())
2165       return QualType();
2166 
2167     ArraySize = Result.get();
2168   }
2169 
2170   // C99 6.7.5.2p1: The size expression shall have integer type.
2171   // C++11 allows contextual conversions to such types.
2172   if (!getLangOpts().CPlusPlus11 &&
2173       ArraySize && !ArraySize->isTypeDependent() &&
2174       !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2175     Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2176       << ArraySize->getType() << ArraySize->getSourceRange();
2177     return QualType();
2178   }
2179 
2180   llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2181   if (!ArraySize) {
2182     if (ASM == ArrayType::Star)
2183       T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2184     else
2185       T = Context.getIncompleteArrayType(T, ASM, Quals);
2186   } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2187     T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2188   } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2189               !T->isConstantSizeType()) ||
2190              isArraySizeVLA(*this, ArraySize, ConstVal)) {
2191     // Even in C++11, don't allow contextual conversions in the array bound
2192     // of a VLA.
2193     if (getLangOpts().CPlusPlus11 &&
2194         !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2195       Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2196         << ArraySize->getType() << ArraySize->getSourceRange();
2197       return QualType();
2198     }
2199 
2200     // C99: an array with an element type that has a non-constant-size is a VLA.
2201     // C99: an array with a non-ICE size is a VLA.  We accept any expression
2202     // that we can fold to a non-zero positive value as an extension.
2203     T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2204   } else {
2205     // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2206     // have a value greater than zero.
2207     if (ConstVal.isSigned() && ConstVal.isNegative()) {
2208       if (Entity)
2209         Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2210           << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2211       else
2212         Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2213           << ArraySize->getSourceRange();
2214       return QualType();
2215     }
2216     if (ConstVal == 0) {
2217       // GCC accepts zero sized static arrays. We allow them when
2218       // we're not in a SFINAE context.
2219       Diag(ArraySize->getLocStart(),
2220            isSFINAEContext()? diag::err_typecheck_zero_array_size
2221                             : diag::ext_typecheck_zero_array_size)
2222         << ArraySize->getSourceRange();
2223 
2224       if (ASM == ArrayType::Static) {
2225         Diag(ArraySize->getLocStart(),
2226              diag::warn_typecheck_zero_static_array_size)
2227           << ArraySize->getSourceRange();
2228         ASM = ArrayType::Normal;
2229       }
2230     } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2231                !T->isIncompleteType() && !T->isUndeducedType()) {
2232       // Is the array too large?
2233       unsigned ActiveSizeBits
2234         = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2235       if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2236         Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2237           << ConstVal.toString(10)
2238           << ArraySize->getSourceRange();
2239         return QualType();
2240       }
2241     }
2242 
2243     T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2244   }
2245 
2246   // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2247   if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2248     Diag(Loc, diag::err_opencl_vla);
2249     return QualType();
2250   }
2251   // CUDA device code doesn't support VLAs.
2252   if (getLangOpts().CUDA && T->isVariableArrayType() && !CheckCUDAVLA(Loc))
2253     return QualType();
2254 
2255   // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2256   if (!getLangOpts().C99) {
2257     if (T->isVariableArrayType()) {
2258       // Prohibit the use of VLAs during template argument deduction.
2259       if (isSFINAEContext()) {
2260         Diag(Loc, diag::err_vla_in_sfinae);
2261         return QualType();
2262       }
2263       // Just extwarn about VLAs.
2264       else
2265         Diag(Loc, diag::ext_vla);
2266     } else if (ASM != ArrayType::Normal || Quals != 0)
2267       Diag(Loc,
2268            getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2269                                   : diag::ext_c99_array_usage) << ASM;
2270   }
2271 
2272   if (T->isVariableArrayType()) {
2273     // Warn about VLAs for -Wvla.
2274     Diag(Loc, diag::warn_vla_used);
2275   }
2276 
2277   // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2278   // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2279   // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2280   if (getLangOpts().OpenCL) {
2281     const QualType ArrType = Context.getBaseElementType(T);
2282     if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2283         ArrType->isSamplerT() || ArrType->isImageType()) {
2284       Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2285       return QualType();
2286     }
2287   }
2288 
2289   return T;
2290 }
2291 
2292 /// \brief Build an ext-vector type.
2293 ///
2294 /// Run the required checks for the extended vector type.
2295 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2296                                   SourceLocation AttrLoc) {
2297   // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2298   // in conjunction with complex types (pointers, arrays, functions, etc.).
2299   //
2300   // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2301   // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2302   // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2303   // of bool aren't allowed.
2304   if ((!T->isDependentType() && !T->isIntegerType() &&
2305        !T->isRealFloatingType()) ||
2306       T->isBooleanType()) {
2307     Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2308     return QualType();
2309   }
2310 
2311   if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2312     llvm::APSInt vecSize(32);
2313     if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2314       Diag(AttrLoc, diag::err_attribute_argument_type)
2315         << "ext_vector_type" << AANT_ArgumentIntegerConstant
2316         << ArraySize->getSourceRange();
2317       return QualType();
2318     }
2319 
2320     // Unlike gcc's vector_size attribute, the size is specified as the
2321     // number of elements, not the number of bytes.
2322     unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2323 
2324     if (vectorSize == 0) {
2325       Diag(AttrLoc, diag::err_attribute_zero_size)
2326       << ArraySize->getSourceRange();
2327       return QualType();
2328     }
2329 
2330     if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2331       Diag(AttrLoc, diag::err_attribute_size_too_large)
2332         << ArraySize->getSourceRange();
2333       return QualType();
2334     }
2335 
2336     return Context.getExtVectorType(T, vectorSize);
2337   }
2338 
2339   return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2340 }
2341 
2342 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2343   if (T->isArrayType() || T->isFunctionType()) {
2344     Diag(Loc, diag::err_func_returning_array_function)
2345       << T->isFunctionType() << T;
2346     return true;
2347   }
2348 
2349   // Functions cannot return half FP.
2350   if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2351     Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2352       FixItHint::CreateInsertion(Loc, "*");
2353     return true;
2354   }
2355 
2356   // Methods cannot return interface types. All ObjC objects are
2357   // passed by reference.
2358   if (T->isObjCObjectType()) {
2359     Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
2360     return 0;
2361   }
2362 
2363   return false;
2364 }
2365 
2366 /// Check the extended parameter information.  Most of the necessary
2367 /// checking should occur when applying the parameter attribute; the
2368 /// only other checks required are positional restrictions.
2369 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2370                     const FunctionProtoType::ExtProtoInfo &EPI,
2371                     llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2372   assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2373 
2374   bool hasCheckedSwiftCall = false;
2375   auto checkForSwiftCC = [&](unsigned paramIndex) {
2376     // Only do this once.
2377     if (hasCheckedSwiftCall) return;
2378     hasCheckedSwiftCall = true;
2379     if (EPI.ExtInfo.getCC() == CC_Swift) return;
2380     S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2381       << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2382   };
2383 
2384   for (size_t paramIndex = 0, numParams = paramTypes.size();
2385           paramIndex != numParams; ++paramIndex) {
2386     switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2387     // Nothing interesting to check for orindary-ABI parameters.
2388     case ParameterABI::Ordinary:
2389       continue;
2390 
2391     // swift_indirect_result parameters must be a prefix of the function
2392     // arguments.
2393     case ParameterABI::SwiftIndirectResult:
2394       checkForSwiftCC(paramIndex);
2395       if (paramIndex != 0 &&
2396           EPI.ExtParameterInfos[paramIndex - 1].getABI()
2397             != ParameterABI::SwiftIndirectResult) {
2398         S.Diag(getParamLoc(paramIndex),
2399                diag::err_swift_indirect_result_not_first);
2400       }
2401       continue;
2402 
2403     // swift_context parameters must be the last parameter except for
2404     // a possible swift_error parameter.
2405     case ParameterABI::SwiftContext:
2406       checkForSwiftCC(paramIndex);
2407       if (!(paramIndex == numParams - 1 ||
2408             (paramIndex == numParams - 2 &&
2409              EPI.ExtParameterInfos[numParams - 1].getABI()
2410                == ParameterABI::SwiftErrorResult))) {
2411         S.Diag(getParamLoc(paramIndex),
2412                diag::err_swift_context_not_before_swift_error_result);
2413       }
2414       continue;
2415 
2416     // swift_error parameters must be the last parameter.
2417     case ParameterABI::SwiftErrorResult:
2418       checkForSwiftCC(paramIndex);
2419       if (paramIndex != numParams - 1) {
2420         S.Diag(getParamLoc(paramIndex),
2421                diag::err_swift_error_result_not_last);
2422       } else if (paramIndex == 0 ||
2423                  EPI.ExtParameterInfos[paramIndex - 1].getABI()
2424                    != ParameterABI::SwiftContext) {
2425         S.Diag(getParamLoc(paramIndex),
2426                diag::err_swift_error_result_not_after_swift_context);
2427       }
2428       continue;
2429     }
2430     llvm_unreachable("bad ABI kind");
2431   }
2432 }
2433 
2434 QualType Sema::BuildFunctionType(QualType T,
2435                                  MutableArrayRef<QualType> ParamTypes,
2436                                  SourceLocation Loc, DeclarationName Entity,
2437                                  const FunctionProtoType::ExtProtoInfo &EPI) {
2438   bool Invalid = false;
2439 
2440   Invalid |= CheckFunctionReturnType(T, Loc);
2441 
2442   for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2443     // FIXME: Loc is too inprecise here, should use proper locations for args.
2444     QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2445     if (ParamType->isVoidType()) {
2446       Diag(Loc, diag::err_param_with_void_type);
2447       Invalid = true;
2448     } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2449       // Disallow half FP arguments.
2450       Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2451         FixItHint::CreateInsertion(Loc, "*");
2452       Invalid = true;
2453     }
2454 
2455     ParamTypes[Idx] = ParamType;
2456   }
2457 
2458   if (EPI.ExtParameterInfos) {
2459     checkExtParameterInfos(*this, ParamTypes, EPI,
2460                            [=](unsigned i) { return Loc; });
2461   }
2462 
2463   if (Invalid)
2464     return QualType();
2465 
2466   return Context.getFunctionType(T, ParamTypes, EPI);
2467 }
2468 
2469 /// \brief Build a member pointer type \c T Class::*.
2470 ///
2471 /// \param T the type to which the member pointer refers.
2472 /// \param Class the class type into which the member pointer points.
2473 /// \param Loc the location where this type begins
2474 /// \param Entity the name of the entity that will have this member pointer type
2475 ///
2476 /// \returns a member pointer type, if successful, or a NULL type if there was
2477 /// an error.
2478 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2479                                       SourceLocation Loc,
2480                                       DeclarationName Entity) {
2481   // Verify that we're not building a pointer to pointer to function with
2482   // exception specification.
2483   if (CheckDistantExceptionSpec(T)) {
2484     Diag(Loc, diag::err_distant_exception_spec);
2485     return QualType();
2486   }
2487 
2488   // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2489   //   with reference type, or "cv void."
2490   if (T->isReferenceType()) {
2491     Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2492       << getPrintableNameForEntity(Entity) << T;
2493     return QualType();
2494   }
2495 
2496   if (T->isVoidType()) {
2497     Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2498       << getPrintableNameForEntity(Entity);
2499     return QualType();
2500   }
2501 
2502   if (!Class->isDependentType() && !Class->isRecordType()) {
2503     Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2504     return QualType();
2505   }
2506 
2507   // Adjust the default free function calling convention to the default method
2508   // calling convention.
2509   bool IsCtorOrDtor =
2510       (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2511       (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2512   if (T->isFunctionType())
2513     adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2514 
2515   return Context.getMemberPointerType(T, Class.getTypePtr());
2516 }
2517 
2518 /// \brief Build a block pointer type.
2519 ///
2520 /// \param T The type to which we'll be building a block pointer.
2521 ///
2522 /// \param Loc The source location, used for diagnostics.
2523 ///
2524 /// \param Entity The name of the entity that involves the block pointer
2525 /// type, if known.
2526 ///
2527 /// \returns A suitable block pointer type, if there are no
2528 /// errors. Otherwise, returns a NULL type.
2529 QualType Sema::BuildBlockPointerType(QualType T,
2530                                      SourceLocation Loc,
2531                                      DeclarationName Entity) {
2532   if (!T->isFunctionType()) {
2533     Diag(Loc, diag::err_nonfunction_block_type);
2534     return QualType();
2535   }
2536 
2537   if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2538     return QualType();
2539 
2540   return Context.getBlockPointerType(T);
2541 }
2542 
2543 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2544   QualType QT = Ty.get();
2545   if (QT.isNull()) {
2546     if (TInfo) *TInfo = nullptr;
2547     return QualType();
2548   }
2549 
2550   TypeSourceInfo *DI = nullptr;
2551   if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2552     QT = LIT->getType();
2553     DI = LIT->getTypeSourceInfo();
2554   }
2555 
2556   if (TInfo) *TInfo = DI;
2557   return QT;
2558 }
2559 
2560 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2561                                             Qualifiers::ObjCLifetime ownership,
2562                                             unsigned chunkIndex);
2563 
2564 /// Given that this is the declaration of a parameter under ARC,
2565 /// attempt to infer attributes and such for pointer-to-whatever
2566 /// types.
2567 static void inferARCWriteback(TypeProcessingState &state,
2568                               QualType &declSpecType) {
2569   Sema &S = state.getSema();
2570   Declarator &declarator = state.getDeclarator();
2571 
2572   // TODO: should we care about decl qualifiers?
2573 
2574   // Check whether the declarator has the expected form.  We walk
2575   // from the inside out in order to make the block logic work.
2576   unsigned outermostPointerIndex = 0;
2577   bool isBlockPointer = false;
2578   unsigned numPointers = 0;
2579   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2580     unsigned chunkIndex = i;
2581     DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2582     switch (chunk.Kind) {
2583     case DeclaratorChunk::Paren:
2584       // Ignore parens.
2585       break;
2586 
2587     case DeclaratorChunk::Reference:
2588     case DeclaratorChunk::Pointer:
2589       // Count the number of pointers.  Treat references
2590       // interchangeably as pointers; if they're mis-ordered, normal
2591       // type building will discover that.
2592       outermostPointerIndex = chunkIndex;
2593       numPointers++;
2594       break;
2595 
2596     case DeclaratorChunk::BlockPointer:
2597       // If we have a pointer to block pointer, that's an acceptable
2598       // indirect reference; anything else is not an application of
2599       // the rules.
2600       if (numPointers != 1) return;
2601       numPointers++;
2602       outermostPointerIndex = chunkIndex;
2603       isBlockPointer = true;
2604 
2605       // We don't care about pointer structure in return values here.
2606       goto done;
2607 
2608     case DeclaratorChunk::Array: // suppress if written (id[])?
2609     case DeclaratorChunk::Function:
2610     case DeclaratorChunk::MemberPointer:
2611     case DeclaratorChunk::Pipe:
2612       return;
2613     }
2614   }
2615  done:
2616 
2617   // If we have *one* pointer, then we want to throw the qualifier on
2618   // the declaration-specifiers, which means that it needs to be a
2619   // retainable object type.
2620   if (numPointers == 1) {
2621     // If it's not a retainable object type, the rule doesn't apply.
2622     if (!declSpecType->isObjCRetainableType()) return;
2623 
2624     // If it already has lifetime, don't do anything.
2625     if (declSpecType.getObjCLifetime()) return;
2626 
2627     // Otherwise, modify the type in-place.
2628     Qualifiers qs;
2629 
2630     if (declSpecType->isObjCARCImplicitlyUnretainedType())
2631       qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2632     else
2633       qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2634     declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2635 
2636   // If we have *two* pointers, then we want to throw the qualifier on
2637   // the outermost pointer.
2638   } else if (numPointers == 2) {
2639     // If we don't have a block pointer, we need to check whether the
2640     // declaration-specifiers gave us something that will turn into a
2641     // retainable object pointer after we slap the first pointer on it.
2642     if (!isBlockPointer && !declSpecType->isObjCObjectType())
2643       return;
2644 
2645     // Look for an explicit lifetime attribute there.
2646     DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2647     if (chunk.Kind != DeclaratorChunk::Pointer &&
2648         chunk.Kind != DeclaratorChunk::BlockPointer)
2649       return;
2650     for (const AttributeList *attr = chunk.getAttrs(); attr;
2651            attr = attr->getNext())
2652       if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2653         return;
2654 
2655     transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2656                                           outermostPointerIndex);
2657 
2658   // Any other number of pointers/references does not trigger the rule.
2659   } else return;
2660 
2661   // TODO: mark whether we did this inference?
2662 }
2663 
2664 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2665                                      SourceLocation FallbackLoc,
2666                                      SourceLocation ConstQualLoc,
2667                                      SourceLocation VolatileQualLoc,
2668                                      SourceLocation RestrictQualLoc,
2669                                      SourceLocation AtomicQualLoc,
2670                                      SourceLocation UnalignedQualLoc) {
2671   if (!Quals)
2672     return;
2673 
2674   struct Qual {
2675     const char *Name;
2676     unsigned Mask;
2677     SourceLocation Loc;
2678   } const QualKinds[5] = {
2679     { "const", DeclSpec::TQ_const, ConstQualLoc },
2680     { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2681     { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2682     { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2683     { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2684   };
2685 
2686   SmallString<32> QualStr;
2687   unsigned NumQuals = 0;
2688   SourceLocation Loc;
2689   FixItHint FixIts[5];
2690 
2691   // Build a string naming the redundant qualifiers.
2692   for (auto &E : QualKinds) {
2693     if (Quals & E.Mask) {
2694       if (!QualStr.empty()) QualStr += ' ';
2695       QualStr += E.Name;
2696 
2697       // If we have a location for the qualifier, offer a fixit.
2698       SourceLocation QualLoc = E.Loc;
2699       if (QualLoc.isValid()) {
2700         FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2701         if (Loc.isInvalid() ||
2702             getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2703           Loc = QualLoc;
2704       }
2705 
2706       ++NumQuals;
2707     }
2708   }
2709 
2710   Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2711     << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2712 }
2713 
2714 // Diagnose pointless type qualifiers on the return type of a function.
2715 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2716                                                   Declarator &D,
2717                                                   unsigned FunctionChunkIndex) {
2718   if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2719     // FIXME: TypeSourceInfo doesn't preserve location information for
2720     // qualifiers.
2721     S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2722                                 RetTy.getLocalCVRQualifiers(),
2723                                 D.getIdentifierLoc());
2724     return;
2725   }
2726 
2727   for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2728                 End = D.getNumTypeObjects();
2729        OuterChunkIndex != End; ++OuterChunkIndex) {
2730     DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2731     switch (OuterChunk.Kind) {
2732     case DeclaratorChunk::Paren:
2733       continue;
2734 
2735     case DeclaratorChunk::Pointer: {
2736       DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2737       S.diagnoseIgnoredQualifiers(
2738           diag::warn_qual_return_type,
2739           PTI.TypeQuals,
2740           SourceLocation(),
2741           SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2742           SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2743           SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2744           SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
2745           SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
2746       return;
2747     }
2748 
2749     case DeclaratorChunk::Function:
2750     case DeclaratorChunk::BlockPointer:
2751     case DeclaratorChunk::Reference:
2752     case DeclaratorChunk::Array:
2753     case DeclaratorChunk::MemberPointer:
2754     case DeclaratorChunk::Pipe:
2755       // FIXME: We can't currently provide an accurate source location and a
2756       // fix-it hint for these.
2757       unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2758       S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2759                                   RetTy.getCVRQualifiers() | AtomicQual,
2760                                   D.getIdentifierLoc());
2761       return;
2762     }
2763 
2764     llvm_unreachable("unknown declarator chunk kind");
2765   }
2766 
2767   // If the qualifiers come from a conversion function type, don't diagnose
2768   // them -- they're not necessarily redundant, since such a conversion
2769   // operator can be explicitly called as "x.operator const int()".
2770   if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2771     return;
2772 
2773   // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2774   // which are present there.
2775   S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2776                               D.getDeclSpec().getTypeQualifiers(),
2777                               D.getIdentifierLoc(),
2778                               D.getDeclSpec().getConstSpecLoc(),
2779                               D.getDeclSpec().getVolatileSpecLoc(),
2780                               D.getDeclSpec().getRestrictSpecLoc(),
2781                               D.getDeclSpec().getAtomicSpecLoc(),
2782                               D.getDeclSpec().getUnalignedSpecLoc());
2783 }
2784 
2785 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2786                                              TypeSourceInfo *&ReturnTypeInfo) {
2787   Sema &SemaRef = state.getSema();
2788   Declarator &D = state.getDeclarator();
2789   QualType T;
2790   ReturnTypeInfo = nullptr;
2791 
2792   // The TagDecl owned by the DeclSpec.
2793   TagDecl *OwnedTagDecl = nullptr;
2794 
2795   switch (D.getName().getKind()) {
2796   case UnqualifiedId::IK_ImplicitSelfParam:
2797   case UnqualifiedId::IK_OperatorFunctionId:
2798   case UnqualifiedId::IK_Identifier:
2799   case UnqualifiedId::IK_LiteralOperatorId:
2800   case UnqualifiedId::IK_TemplateId:
2801     T = ConvertDeclSpecToType(state);
2802 
2803     if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2804       OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2805       // Owned declaration is embedded in declarator.
2806       OwnedTagDecl->setEmbeddedInDeclarator(true);
2807     }
2808     break;
2809 
2810   case UnqualifiedId::IK_ConstructorName:
2811   case UnqualifiedId::IK_ConstructorTemplateId:
2812   case UnqualifiedId::IK_DestructorName:
2813     // Constructors and destructors don't have return types. Use
2814     // "void" instead.
2815     T = SemaRef.Context.VoidTy;
2816     processTypeAttrs(state, T, TAL_DeclSpec,
2817                      D.getDeclSpec().getAttributes().getList());
2818     break;
2819 
2820   case UnqualifiedId::IK_ConversionFunctionId:
2821     // The result type of a conversion function is the type that it
2822     // converts to.
2823     T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2824                                   &ReturnTypeInfo);
2825     break;
2826   }
2827 
2828   if (D.getAttributes())
2829     distributeTypeAttrsFromDeclarator(state, T);
2830 
2831   // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2832   if (D.getDeclSpec().containsPlaceholderType()) {
2833     int Error = -1;
2834 
2835     switch (D.getContext()) {
2836     case Declarator::LambdaExprContext:
2837       llvm_unreachable("Can't specify a type specifier in lambda grammar");
2838     case Declarator::ObjCParameterContext:
2839     case Declarator::ObjCResultContext:
2840     case Declarator::PrototypeContext:
2841       Error = 0;
2842       break;
2843     case Declarator::LambdaExprParameterContext:
2844       // In C++14, generic lambdas allow 'auto' in their parameters.
2845       if (!(SemaRef.getLangOpts().CPlusPlus14
2846               && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2847         Error = 16;
2848       break;
2849     case Declarator::MemberContext: {
2850       if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2851           D.isFunctionDeclarator())
2852         break;
2853       bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2854       switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2855       case TTK_Enum: llvm_unreachable("unhandled tag kind");
2856       case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2857       case TTK_Union:  Error = Cxx ? 3 : 4; /* Union member */ break;
2858       case TTK_Class:  Error = 5; /* Class member */ break;
2859       case TTK_Interface: Error = 6; /* Interface member */ break;
2860       }
2861       break;
2862     }
2863     case Declarator::CXXCatchContext:
2864     case Declarator::ObjCCatchContext:
2865       Error = 7; // Exception declaration
2866       break;
2867     case Declarator::TemplateParamContext:
2868       if (!SemaRef.getLangOpts().CPlusPlus1z)
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     QualType pointeeType = desugared->getPointeeType();
5905     if (pointeeType->isAnyPointerType() ||
5906         pointeeType->isObjCObjectPointerType() ||
5907         pointeeType->isMemberPointerType()) {
5908       Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
5909         << DiagNullabilityKind(nullability, true)
5910         << type;
5911       Diag(nullabilityLoc, diag::note_nullability_type_specifier)
5912         << DiagNullabilityKind(nullability, false)
5913         << type
5914         << FixItHint::CreateReplacement(nullabilityLoc,
5915                                         getNullabilitySpelling(nullability));
5916       return true;
5917     }
5918   }
5919 
5920   // Form the attributed type.
5921   type = Context.getAttributedType(
5922            AttributedType::getNullabilityAttrKind(nullability), type, type);
5923   return false;
5924 }
5925 
5926 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
5927   if (isa<ObjCTypeParamType>(type)) {
5928     // Build the attributed type to record where __kindof occurred.
5929     type = Context.getAttributedType(AttributedType::attr_objc_kindof,
5930                                      type, type);
5931     return false;
5932   }
5933 
5934   // Find out if it's an Objective-C object or object pointer type;
5935   const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
5936   const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
5937                                           : type->getAs<ObjCObjectType>();
5938 
5939   // If not, we can't apply __kindof.
5940   if (!objType) {
5941     // FIXME: Handle dependent types that aren't yet object types.
5942     Diag(loc, diag::err_objc_kindof_nonobject)
5943       << type;
5944     return true;
5945   }
5946 
5947   // Rebuild the "equivalent" type, which pushes __kindof down into
5948   // the object type.
5949   // There is no need to apply kindof on an unqualified id type.
5950   QualType equivType = Context.getObjCObjectType(
5951       objType->getBaseType(), objType->getTypeArgsAsWritten(),
5952       objType->getProtocols(),
5953       /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
5954 
5955   // If we started with an object pointer type, rebuild it.
5956   if (ptrType) {
5957     equivType = Context.getObjCObjectPointerType(equivType);
5958     if (auto nullability = type->getNullability(Context)) {
5959       auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
5960       equivType = Context.getAttributedType(attrKind, equivType, equivType);
5961     }
5962   }
5963 
5964   // Build the attributed type to record where __kindof occurred.
5965   type = Context.getAttributedType(AttributedType::attr_objc_kindof,
5966                                    type,
5967                                    equivType);
5968 
5969   return false;
5970 }
5971 
5972 /// Map a nullability attribute kind to a nullability kind.
5973 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
5974   switch (kind) {
5975   case AttributeList::AT_TypeNonNull:
5976     return NullabilityKind::NonNull;
5977 
5978   case AttributeList::AT_TypeNullable:
5979     return NullabilityKind::Nullable;
5980 
5981   case AttributeList::AT_TypeNullUnspecified:
5982     return NullabilityKind::Unspecified;
5983 
5984   default:
5985     llvm_unreachable("not a nullability attribute kind");
5986   }
5987 }
5988 
5989 /// Distribute a nullability type attribute that cannot be applied to
5990 /// the type specifier to a pointer, block pointer, or member pointer
5991 /// declarator, complaining if necessary.
5992 ///
5993 /// \returns true if the nullability annotation was distributed, false
5994 /// otherwise.
5995 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
5996                                           QualType type,
5997                                           AttributeList &attr) {
5998   Declarator &declarator = state.getDeclarator();
5999 
6000   /// Attempt to move the attribute to the specified chunk.
6001   auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
6002     // If there is already a nullability attribute there, don't add
6003     // one.
6004     if (hasNullabilityAttr(chunk.getAttrListRef()))
6005       return false;
6006 
6007     // Complain about the nullability qualifier being in the wrong
6008     // place.
6009     enum {
6010       PK_Pointer,
6011       PK_BlockPointer,
6012       PK_MemberPointer,
6013       PK_FunctionPointer,
6014       PK_MemberFunctionPointer,
6015     } pointerKind
6016       = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
6017                                                              : PK_Pointer)
6018         : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
6019         : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
6020 
6021     auto diag = state.getSema().Diag(attr.getLoc(),
6022                                      diag::warn_nullability_declspec)
6023       << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
6024                              attr.isContextSensitiveKeywordAttribute())
6025       << type
6026       << static_cast<unsigned>(pointerKind);
6027 
6028     // FIXME: MemberPointer chunks don't carry the location of the *.
6029     if (chunk.Kind != DeclaratorChunk::MemberPointer) {
6030       diag << FixItHint::CreateRemoval(attr.getLoc())
6031            << FixItHint::CreateInsertion(
6032                 state.getSema().getPreprocessor()
6033                   .getLocForEndOfToken(chunk.Loc),
6034                 " " + attr.getName()->getName().str() + " ");
6035     }
6036 
6037     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
6038                            chunk.getAttrListRef());
6039     return true;
6040   };
6041 
6042   // Move it to the outermost pointer, member pointer, or block
6043   // pointer declarator.
6044   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
6045     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6046     switch (chunk.Kind) {
6047     case DeclaratorChunk::Pointer:
6048     case DeclaratorChunk::BlockPointer:
6049     case DeclaratorChunk::MemberPointer:
6050       return moveToChunk(chunk, false);
6051 
6052     case DeclaratorChunk::Paren:
6053     case DeclaratorChunk::Array:
6054       continue;
6055 
6056     case DeclaratorChunk::Function:
6057       // Try to move past the return type to a function/block/member
6058       // function pointer.
6059       if (DeclaratorChunk *dest = maybeMovePastReturnType(
6060                                     declarator, i,
6061                                     /*onlyBlockPointers=*/false)) {
6062         return moveToChunk(*dest, true);
6063       }
6064 
6065       return false;
6066 
6067     // Don't walk through these.
6068     case DeclaratorChunk::Reference:
6069     case DeclaratorChunk::Pipe:
6070       return false;
6071     }
6072   }
6073 
6074   return false;
6075 }
6076 
6077 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
6078   assert(!Attr.isInvalid());
6079   switch (Attr.getKind()) {
6080   default:
6081     llvm_unreachable("not a calling convention attribute");
6082   case AttributeList::AT_CDecl:
6083     return AttributedType::attr_cdecl;
6084   case AttributeList::AT_FastCall:
6085     return AttributedType::attr_fastcall;
6086   case AttributeList::AT_StdCall:
6087     return AttributedType::attr_stdcall;
6088   case AttributeList::AT_ThisCall:
6089     return AttributedType::attr_thiscall;
6090   case AttributeList::AT_Pascal:
6091     return AttributedType::attr_pascal;
6092   case AttributeList::AT_SwiftCall:
6093     return AttributedType::attr_swiftcall;
6094   case AttributeList::AT_VectorCall:
6095     return AttributedType::attr_vectorcall;
6096   case AttributeList::AT_Pcs: {
6097     // The attribute may have had a fixit applied where we treated an
6098     // identifier as a string literal.  The contents of the string are valid,
6099     // but the form may not be.
6100     StringRef Str;
6101     if (Attr.isArgExpr(0))
6102       Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6103     else
6104       Str = Attr.getArgAsIdent(0)->Ident->getName();
6105     return llvm::StringSwitch<AttributedType::Kind>(Str)
6106         .Case("aapcs", AttributedType::attr_pcs)
6107         .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
6108   }
6109   case AttributeList::AT_IntelOclBicc:
6110     return AttributedType::attr_inteloclbicc;
6111   case AttributeList::AT_MSABI:
6112     return AttributedType::attr_ms_abi;
6113   case AttributeList::AT_SysVABI:
6114     return AttributedType::attr_sysv_abi;
6115   case AttributeList::AT_PreserveMost:
6116     return AttributedType::attr_preserve_most;
6117   case AttributeList::AT_PreserveAll:
6118     return AttributedType::attr_preserve_all;
6119   }
6120   llvm_unreachable("unexpected attribute kind!");
6121 }
6122 
6123 /// Process an individual function attribute.  Returns true to
6124 /// indicate that the attribute was handled, false if it wasn't.
6125 static bool handleFunctionTypeAttr(TypeProcessingState &state,
6126                                    AttributeList &attr,
6127                                    QualType &type) {
6128   Sema &S = state.getSema();
6129 
6130   FunctionTypeUnwrapper unwrapped(S, type);
6131 
6132   if (attr.getKind() == AttributeList::AT_NoReturn) {
6133     if (S.CheckNoReturnAttr(attr))
6134       return true;
6135 
6136     // Delay if this is not a function type.
6137     if (!unwrapped.isFunctionType())
6138       return false;
6139 
6140     // Otherwise we can process right away.
6141     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6142     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6143     return true;
6144   }
6145 
6146   // ns_returns_retained is not always a type attribute, but if we got
6147   // here, we're treating it as one right now.
6148   if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
6149     assert(S.getLangOpts().ObjCAutoRefCount &&
6150            "ns_returns_retained treated as type attribute in non-ARC");
6151     if (attr.getNumArgs()) return true;
6152 
6153     // Delay if this is not a function type.
6154     if (!unwrapped.isFunctionType())
6155       return false;
6156 
6157     FunctionType::ExtInfo EI
6158       = unwrapped.get()->getExtInfo().withProducesResult(true);
6159     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6160     return true;
6161   }
6162 
6163   if (attr.getKind() == AttributeList::AT_Regparm) {
6164     unsigned value;
6165     if (S.CheckRegparmAttr(attr, value))
6166       return true;
6167 
6168     // Delay if this is not a function type.
6169     if (!unwrapped.isFunctionType())
6170       return false;
6171 
6172     // Diagnose regparm with fastcall.
6173     const FunctionType *fn = unwrapped.get();
6174     CallingConv CC = fn->getCallConv();
6175     if (CC == CC_X86FastCall) {
6176       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6177         << FunctionType::getNameForCallConv(CC)
6178         << "regparm";
6179       attr.setInvalid();
6180       return true;
6181     }
6182 
6183     FunctionType::ExtInfo EI =
6184       unwrapped.get()->getExtInfo().withRegParm(value);
6185     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6186     return true;
6187   }
6188 
6189   // Delay if the type didn't work out to a function.
6190   if (!unwrapped.isFunctionType()) return false;
6191 
6192   // Otherwise, a calling convention.
6193   CallingConv CC;
6194   if (S.CheckCallingConvAttr(attr, CC))
6195     return true;
6196 
6197   const FunctionType *fn = unwrapped.get();
6198   CallingConv CCOld = fn->getCallConv();
6199   AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
6200 
6201   if (CCOld != CC) {
6202     // Error out on when there's already an attribute on the type
6203     // and the CCs don't match.
6204     const AttributedType *AT = S.getCallingConvAttributedType(type);
6205     if (AT && AT->getAttrKind() != CCAttrKind) {
6206       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6207         << FunctionType::getNameForCallConv(CC)
6208         << FunctionType::getNameForCallConv(CCOld);
6209       attr.setInvalid();
6210       return true;
6211     }
6212   }
6213 
6214   // Diagnose use of variadic functions with calling conventions that
6215   // don't support them (e.g. because they're callee-cleanup).
6216   // We delay warning about this on unprototyped function declarations
6217   // until after redeclaration checking, just in case we pick up a
6218   // prototype that way.  And apparently we also "delay" warning about
6219   // unprototyped function types in general, despite not necessarily having
6220   // much ability to diagnose it later.
6221   if (!supportsVariadicCall(CC)) {
6222     const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6223     if (FnP && FnP->isVariadic()) {
6224       unsigned DiagID = diag::err_cconv_varargs;
6225 
6226       // stdcall and fastcall are ignored with a warning for GCC and MS
6227       // compatibility.
6228       bool IsInvalid = true;
6229       if (CC == CC_X86StdCall || CC == CC_X86FastCall) {
6230         DiagID = diag::warn_cconv_varargs;
6231         IsInvalid = false;
6232       }
6233 
6234       S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
6235       if (IsInvalid) attr.setInvalid();
6236       return true;
6237     }
6238   }
6239 
6240   // Also diagnose fastcall with regparm.
6241   if (CC == CC_X86FastCall && fn->getHasRegParm()) {
6242     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6243         << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
6244     attr.setInvalid();
6245     return true;
6246   }
6247 
6248   // Modify the CC from the wrapped function type, wrap it all back, and then
6249   // wrap the whole thing in an AttributedType as written.  The modified type
6250   // might have a different CC if we ignored the attribute.
6251   QualType Equivalent;
6252   if (CCOld == CC) {
6253     Equivalent = type;
6254   } else {
6255     auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
6256     Equivalent =
6257       unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6258   }
6259   type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
6260   return true;
6261 }
6262 
6263 bool Sema::hasExplicitCallingConv(QualType &T) {
6264   QualType R = T.IgnoreParens();
6265   while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
6266     if (AT->isCallingConv())
6267       return true;
6268     R = AT->getModifiedType().IgnoreParens();
6269   }
6270   return false;
6271 }
6272 
6273 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
6274                                   SourceLocation Loc) {
6275   FunctionTypeUnwrapper Unwrapped(*this, T);
6276   const FunctionType *FT = Unwrapped.get();
6277   bool IsVariadic = (isa<FunctionProtoType>(FT) &&
6278                      cast<FunctionProtoType>(FT)->isVariadic());
6279   CallingConv CurCC = FT->getCallConv();
6280   CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
6281 
6282   if (CurCC == ToCC)
6283     return;
6284 
6285   // MS compiler ignores explicit calling convention attributes on structors. We
6286   // should do the same.
6287   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
6288     // Issue a warning on ignored calling convention -- except of __stdcall.
6289     // Again, this is what MS compiler does.
6290     if (CurCC != CC_X86StdCall)
6291       Diag(Loc, diag::warn_cconv_structors)
6292           << FunctionType::getNameForCallConv(CurCC);
6293   // Default adjustment.
6294   } else {
6295     // Only adjust types with the default convention.  For example, on Windows
6296     // we should adjust a __cdecl type to __thiscall for instance methods, and a
6297     // __thiscall type to __cdecl for static methods.
6298     CallingConv DefaultCC =
6299         Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6300 
6301     if (CurCC != DefaultCC || DefaultCC == ToCC)
6302       return;
6303 
6304     if (hasExplicitCallingConv(T))
6305       return;
6306   }
6307 
6308   FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6309   QualType Wrapped = Unwrapped.wrap(*this, FT);
6310   T = Context.getAdjustedType(T, Wrapped);
6311 }
6312 
6313 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6314 /// and float scalars, although arrays, pointers, and function return values are
6315 /// allowed in conjunction with this construct. Aggregates with this attribute
6316 /// are invalid, even if they are of the same size as a corresponding scalar.
6317 /// The raw attribute should contain precisely 1 argument, the vector size for
6318 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6319 /// this routine will return a new vector type.
6320 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
6321                                  Sema &S) {
6322   // Check the attribute arguments.
6323   if (Attr.getNumArgs() != 1) {
6324     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6325       << Attr.getName() << 1;
6326     Attr.setInvalid();
6327     return;
6328   }
6329   Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6330   llvm::APSInt vecSize(32);
6331   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
6332       !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
6333     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6334       << Attr.getName() << AANT_ArgumentIntegerConstant
6335       << sizeExpr->getSourceRange();
6336     Attr.setInvalid();
6337     return;
6338   }
6339   // The base type must be integer (not Boolean or enumeration) or float, and
6340   // can't already be a vector.
6341   if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
6342       (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
6343     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6344     Attr.setInvalid();
6345     return;
6346   }
6347   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6348   // vecSize is specified in bytes - convert to bits.
6349   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
6350 
6351   // the vector size needs to be an integral multiple of the type size.
6352   if (vectorSize % typeSize) {
6353     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
6354       << sizeExpr->getSourceRange();
6355     Attr.setInvalid();
6356     return;
6357   }
6358   if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
6359     S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
6360       << sizeExpr->getSourceRange();
6361     Attr.setInvalid();
6362     return;
6363   }
6364   if (vectorSize == 0) {
6365     S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
6366       << sizeExpr->getSourceRange();
6367     Attr.setInvalid();
6368     return;
6369   }
6370 
6371   // Success! Instantiate the vector type, the number of elements is > 0, and
6372   // not required to be a power of 2, unlike GCC.
6373   CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
6374                                     VectorType::GenericVector);
6375 }
6376 
6377 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
6378 /// a type.
6379 static void HandleExtVectorTypeAttr(QualType &CurType,
6380                                     const AttributeList &Attr,
6381                                     Sema &S) {
6382   // check the attribute arguments.
6383   if (Attr.getNumArgs() != 1) {
6384     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6385       << Attr.getName() << 1;
6386     return;
6387   }
6388 
6389   Expr *sizeExpr;
6390 
6391   // Special case where the argument is a template id.
6392   if (Attr.isArgIdent(0)) {
6393     CXXScopeSpec SS;
6394     SourceLocation TemplateKWLoc;
6395     UnqualifiedId id;
6396     id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6397 
6398     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6399                                           id, false, false);
6400     if (Size.isInvalid())
6401       return;
6402 
6403     sizeExpr = Size.get();
6404   } else {
6405     sizeExpr = Attr.getArgAsExpr(0);
6406   }
6407 
6408   // Create the vector type.
6409   QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6410   if (!T.isNull())
6411     CurType = T;
6412 }
6413 
6414 static bool isPermittedNeonBaseType(QualType &Ty,
6415                                     VectorType::VectorKind VecKind, Sema &S) {
6416   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6417   if (!BTy)
6418     return false;
6419 
6420   llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6421 
6422   // Signed poly is mathematically wrong, but has been baked into some ABIs by
6423   // now.
6424   bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6425                         Triple.getArch() == llvm::Triple::aarch64_be;
6426   if (VecKind == VectorType::NeonPolyVector) {
6427     if (IsPolyUnsigned) {
6428       // AArch64 polynomial vectors are unsigned and support poly64.
6429       return BTy->getKind() == BuiltinType::UChar ||
6430              BTy->getKind() == BuiltinType::UShort ||
6431              BTy->getKind() == BuiltinType::ULong ||
6432              BTy->getKind() == BuiltinType::ULongLong;
6433     } else {
6434       // AArch32 polynomial vector are signed.
6435       return BTy->getKind() == BuiltinType::SChar ||
6436              BTy->getKind() == BuiltinType::Short;
6437     }
6438   }
6439 
6440   // Non-polynomial vector types: the usual suspects are allowed, as well as
6441   // float64_t on AArch64.
6442   bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6443                  Triple.getArch() == llvm::Triple::aarch64_be;
6444 
6445   if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6446     return true;
6447 
6448   return BTy->getKind() == BuiltinType::SChar ||
6449          BTy->getKind() == BuiltinType::UChar ||
6450          BTy->getKind() == BuiltinType::Short ||
6451          BTy->getKind() == BuiltinType::UShort ||
6452          BTy->getKind() == BuiltinType::Int ||
6453          BTy->getKind() == BuiltinType::UInt ||
6454          BTy->getKind() == BuiltinType::Long ||
6455          BTy->getKind() == BuiltinType::ULong ||
6456          BTy->getKind() == BuiltinType::LongLong ||
6457          BTy->getKind() == BuiltinType::ULongLong ||
6458          BTy->getKind() == BuiltinType::Float ||
6459          BTy->getKind() == BuiltinType::Half;
6460 }
6461 
6462 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6463 /// "neon_polyvector_type" attributes are used to create vector types that
6464 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
6465 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
6466 /// the argument to these Neon attributes is the number of vector elements,
6467 /// not the vector size in bytes.  The vector width and element type must
6468 /// match one of the standard Neon vector types.
6469 static void HandleNeonVectorTypeAttr(QualType& CurType,
6470                                      const AttributeList &Attr, Sema &S,
6471                                      VectorType::VectorKind VecKind) {
6472   // Target must have NEON
6473   if (!S.Context.getTargetInfo().hasFeature("neon")) {
6474     S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6475     Attr.setInvalid();
6476     return;
6477   }
6478   // Check the attribute arguments.
6479   if (Attr.getNumArgs() != 1) {
6480     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6481       << Attr.getName() << 1;
6482     Attr.setInvalid();
6483     return;
6484   }
6485   // The number of elements must be an ICE.
6486   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6487   llvm::APSInt numEltsInt(32);
6488   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6489       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6490     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6491       << Attr.getName() << AANT_ArgumentIntegerConstant
6492       << numEltsExpr->getSourceRange();
6493     Attr.setInvalid();
6494     return;
6495   }
6496   // Only certain element types are supported for Neon vectors.
6497   if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6498     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6499     Attr.setInvalid();
6500     return;
6501   }
6502 
6503   // The total size of the vector must be 64 or 128 bits.
6504   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6505   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6506   unsigned vecSize = typeSize * numElts;
6507   if (vecSize != 64 && vecSize != 128) {
6508     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6509     Attr.setInvalid();
6510     return;
6511   }
6512 
6513   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6514 }
6515 
6516 /// Handle OpenCL Access Qualifier Attribute.
6517 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr,
6518                                    Sema &S) {
6519   // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
6520   if (!(CurType->isImageType() || CurType->isPipeType())) {
6521     S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
6522     Attr.setInvalid();
6523     return;
6524   }
6525 
6526   if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
6527     QualType PointeeTy = TypedefTy->desugar();
6528     S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
6529 
6530     std::string PrevAccessQual;
6531     switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) {
6532       #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6533     case BuiltinType::Id:                                          \
6534       PrevAccessQual = #Access;                                    \
6535       break;
6536       #include "clang/Basic/OpenCLImageTypes.def"
6537     default:
6538       assert(0 && "Unable to find corresponding image type.");
6539     }
6540 
6541     S.Diag(TypedefTy->getDecl()->getLocStart(),
6542        diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
6543   }
6544 }
6545 
6546 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
6547                              TypeAttrLocation TAL, AttributeList *attrs) {
6548   // Scan through and apply attributes to this type where it makes sense.  Some
6549   // attributes (such as __address_space__, __vector_size__, etc) apply to the
6550   // type, but others can be present in the type specifiers even though they
6551   // apply to the decl.  Here we apply type attributes and ignore the rest.
6552 
6553   bool hasOpenCLAddressSpace = false;
6554   while (attrs) {
6555     AttributeList &attr = *attrs;
6556     attrs = attr.getNext(); // reset to the next here due to early loop continue
6557                             // stmts
6558 
6559     // Skip attributes that were marked to be invalid.
6560     if (attr.isInvalid())
6561       continue;
6562 
6563     if (attr.isCXX11Attribute()) {
6564       // [[gnu::...]] attributes are treated as declaration attributes, so may
6565       // not appertain to a DeclaratorChunk, even if we handle them as type
6566       // attributes.
6567       if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
6568         if (TAL == TAL_DeclChunk) {
6569           state.getSema().Diag(attr.getLoc(),
6570                                diag::warn_cxx11_gnu_attribute_on_type)
6571               << attr.getName();
6572           continue;
6573         }
6574       } else if (TAL != TAL_DeclChunk) {
6575         // Otherwise, only consider type processing for a C++11 attribute if
6576         // it's actually been applied to a type.
6577         continue;
6578       }
6579     }
6580 
6581     // If this is an attribute we can handle, do so now,
6582     // otherwise, add it to the FnAttrs list for rechaining.
6583     switch (attr.getKind()) {
6584     default:
6585       // A C++11 attribute on a declarator chunk must appertain to a type.
6586       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
6587         state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
6588           << attr.getName();
6589         attr.setUsedAsTypeAttr();
6590       }
6591       break;
6592 
6593     case AttributeList::UnknownAttribute:
6594       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6595         state.getSema().Diag(attr.getLoc(),
6596                              diag::warn_unknown_attribute_ignored)
6597           << attr.getName();
6598       break;
6599 
6600     case AttributeList::IgnoredAttribute:
6601       break;
6602 
6603     case AttributeList::AT_MayAlias:
6604       // FIXME: This attribute needs to actually be handled, but if we ignore
6605       // it it breaks large amounts of Linux software.
6606       attr.setUsedAsTypeAttr();
6607       break;
6608     case AttributeList::AT_OpenCLPrivateAddressSpace:
6609     case AttributeList::AT_OpenCLGlobalAddressSpace:
6610     case AttributeList::AT_OpenCLLocalAddressSpace:
6611     case AttributeList::AT_OpenCLConstantAddressSpace:
6612     case AttributeList::AT_OpenCLGenericAddressSpace:
6613     case AttributeList::AT_AddressSpace:
6614       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
6615       attr.setUsedAsTypeAttr();
6616       hasOpenCLAddressSpace = true;
6617       break;
6618     OBJC_POINTER_TYPE_ATTRS_CASELIST:
6619       if (!handleObjCPointerTypeAttr(state, attr, type))
6620         distributeObjCPointerTypeAttr(state, attr, type);
6621       attr.setUsedAsTypeAttr();
6622       break;
6623     case AttributeList::AT_VectorSize:
6624       HandleVectorSizeAttr(type, attr, state.getSema());
6625       attr.setUsedAsTypeAttr();
6626       break;
6627     case AttributeList::AT_ExtVectorType:
6628       HandleExtVectorTypeAttr(type, attr, state.getSema());
6629       attr.setUsedAsTypeAttr();
6630       break;
6631     case AttributeList::AT_NeonVectorType:
6632       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6633                                VectorType::NeonVector);
6634       attr.setUsedAsTypeAttr();
6635       break;
6636     case AttributeList::AT_NeonPolyVectorType:
6637       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6638                                VectorType::NeonPolyVector);
6639       attr.setUsedAsTypeAttr();
6640       break;
6641     case AttributeList::AT_OpenCLAccess:
6642       HandleOpenCLAccessAttr(type, attr, state.getSema());
6643       attr.setUsedAsTypeAttr();
6644       break;
6645 
6646     MS_TYPE_ATTRS_CASELIST:
6647       if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6648         attr.setUsedAsTypeAttr();
6649       break;
6650 
6651 
6652     NULLABILITY_TYPE_ATTRS_CASELIST:
6653       // Either add nullability here or try to distribute it.  We
6654       // don't want to distribute the nullability specifier past any
6655       // dependent type, because that complicates the user model.
6656       if (type->canHaveNullability() || type->isDependentType() ||
6657           !distributeNullabilityTypeAttr(state, type, attr)) {
6658         if (state.getSema().checkNullabilityTypeSpecifier(
6659               type,
6660               mapNullabilityAttrKind(attr.getKind()),
6661               attr.getLoc(),
6662               attr.isContextSensitiveKeywordAttribute())) {
6663           attr.setInvalid();
6664         }
6665 
6666         attr.setUsedAsTypeAttr();
6667       }
6668       break;
6669 
6670     case AttributeList::AT_ObjCKindOf:
6671       // '__kindof' must be part of the decl-specifiers.
6672       switch (TAL) {
6673       case TAL_DeclSpec:
6674         break;
6675 
6676       case TAL_DeclChunk:
6677       case TAL_DeclName:
6678         state.getSema().Diag(attr.getLoc(),
6679                              diag::err_objc_kindof_wrong_position)
6680           << FixItHint::CreateRemoval(attr.getLoc())
6681           << FixItHint::CreateInsertion(
6682                state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6683         break;
6684       }
6685 
6686       // Apply it regardless.
6687       if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6688         attr.setInvalid();
6689       attr.setUsedAsTypeAttr();
6690       break;
6691 
6692     case AttributeList::AT_NSReturnsRetained:
6693       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6694         break;
6695       // fallthrough into the function attrs
6696 
6697     FUNCTION_TYPE_ATTRS_CASELIST:
6698       attr.setUsedAsTypeAttr();
6699 
6700       // Never process function type attributes as part of the
6701       // declaration-specifiers.
6702       if (TAL == TAL_DeclSpec)
6703         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6704 
6705       // Otherwise, handle the possible delays.
6706       else if (!handleFunctionTypeAttr(state, attr, type))
6707         distributeFunctionTypeAttr(state, attr, type);
6708       break;
6709     }
6710   }
6711 
6712   // If address space is not set, OpenCL 2.0 defines non private default
6713   // address spaces for some cases:
6714   // OpenCL 2.0, section 6.5:
6715   // The address space for a variable at program scope or a static variable
6716   // inside a function can either be __global or __constant, but defaults to
6717   // __global if not specified.
6718   // (...)
6719   // Pointers that are declared without pointing to a named address space point
6720   // to the generic address space.
6721   if (state.getSema().getLangOpts().OpenCLVersion >= 200 &&
6722       !hasOpenCLAddressSpace && type.getAddressSpace() == 0 &&
6723       (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) {
6724     Declarator &D = state.getDeclarator();
6725     if (state.getCurrentChunkIndex() > 0 &&
6726         D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6727             DeclaratorChunk::Pointer) {
6728       type = state.getSema().Context.getAddrSpaceQualType(
6729           type, LangAS::opencl_generic);
6730     } else if (state.getCurrentChunkIndex() == 0 &&
6731                D.getContext() == Declarator::FileContext &&
6732                !D.isFunctionDeclarator() && !D.isFunctionDefinition() &&
6733                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6734                !type->isSamplerT())
6735       type = state.getSema().Context.getAddrSpaceQualType(
6736           type, LangAS::opencl_global);
6737     else if (state.getCurrentChunkIndex() == 0 &&
6738              D.getContext() == Declarator::BlockContext &&
6739              D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
6740       type = state.getSema().Context.getAddrSpaceQualType(
6741           type, LangAS::opencl_global);
6742   }
6743 }
6744 
6745 void Sema::completeExprArrayBound(Expr *E) {
6746   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6747     if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6748       if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
6749         SourceLocation PointOfInstantiation = E->getExprLoc();
6750 
6751         if (MemberSpecializationInfo *MSInfo =
6752                 Var->getMemberSpecializationInfo()) {
6753           // If we don't already have a point of instantiation, this is it.
6754           if (MSInfo->getPointOfInstantiation().isInvalid()) {
6755             MSInfo->setPointOfInstantiation(PointOfInstantiation);
6756 
6757             // This is a modification of an existing AST node. Notify
6758             // listeners.
6759             if (ASTMutationListener *L = getASTMutationListener())
6760               L->StaticDataMemberInstantiated(Var);
6761           }
6762         } else {
6763           VarTemplateSpecializationDecl *VarSpec =
6764               cast<VarTemplateSpecializationDecl>(Var);
6765           if (VarSpec->getPointOfInstantiation().isInvalid())
6766             VarSpec->setPointOfInstantiation(PointOfInstantiation);
6767         }
6768 
6769         InstantiateVariableDefinition(PointOfInstantiation, Var);
6770 
6771         // Update the type to the newly instantiated definition's type both
6772         // here and within the expression.
6773         if (VarDecl *Def = Var->getDefinition()) {
6774           DRE->setDecl(Def);
6775           QualType T = Def->getType();
6776           DRE->setType(T);
6777           // FIXME: Update the type on all intervening expressions.
6778           E->setType(T);
6779         }
6780 
6781         // We still go on to try to complete the type independently, as it
6782         // may also require instantiations or diagnostics if it remains
6783         // incomplete.
6784       }
6785     }
6786   }
6787 }
6788 
6789 /// \brief Ensure that the type of the given expression is complete.
6790 ///
6791 /// This routine checks whether the expression \p E has a complete type. If the
6792 /// expression refers to an instantiable construct, that instantiation is
6793 /// performed as needed to complete its type. Furthermore
6794 /// Sema::RequireCompleteType is called for the expression's type (or in the
6795 /// case of a reference type, the referred-to type).
6796 ///
6797 /// \param E The expression whose type is required to be complete.
6798 /// \param Diagnoser The object that will emit a diagnostic if the type is
6799 /// incomplete.
6800 ///
6801 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
6802 /// otherwise.
6803 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
6804   QualType T = E->getType();
6805 
6806   // Incomplete array types may be completed by the initializer attached to
6807   // their definitions. For static data members of class templates and for
6808   // variable templates, we need to instantiate the definition to get this
6809   // initializer and complete the type.
6810   if (T->isIncompleteArrayType()) {
6811     completeExprArrayBound(E);
6812     T = E->getType();
6813   }
6814 
6815   // FIXME: Are there other cases which require instantiating something other
6816   // than the type to complete the type of an expression?
6817 
6818   return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
6819 }
6820 
6821 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
6822   BoundTypeDiagnoser<> Diagnoser(DiagID);
6823   return RequireCompleteExprType(E, Diagnoser);
6824 }
6825 
6826 /// @brief Ensure that the type T is a complete type.
6827 ///
6828 /// This routine checks whether the type @p T is complete in any
6829 /// context where a complete type is required. If @p T is a complete
6830 /// type, returns false. If @p T is a class template specialization,
6831 /// this routine then attempts to perform class template
6832 /// instantiation. If instantiation fails, or if @p T is incomplete
6833 /// and cannot be completed, issues the diagnostic @p diag (giving it
6834 /// the type @p T) and returns true.
6835 ///
6836 /// @param Loc  The location in the source that the incomplete type
6837 /// diagnostic should refer to.
6838 ///
6839 /// @param T  The type that this routine is examining for completeness.
6840 ///
6841 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
6842 /// @c false otherwise.
6843 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6844                                TypeDiagnoser &Diagnoser) {
6845   if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
6846     return true;
6847   if (const TagType *Tag = T->getAs<TagType>()) {
6848     if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
6849       Tag->getDecl()->setCompleteDefinitionRequired();
6850       Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
6851     }
6852   }
6853   return false;
6854 }
6855 
6856 /// \brief Determine whether there is any declaration of \p D that was ever a
6857 ///        definition (perhaps before module merging) and is currently visible.
6858 /// \param D The definition of the entity.
6859 /// \param Suggested Filled in with the declaration that should be made visible
6860 ///        in order to provide a definition of this entity.
6861 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
6862 ///        not defined. This only matters for enums with a fixed underlying
6863 ///        type, since in all other cases, a type is complete if and only if it
6864 ///        is defined.
6865 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
6866                                 bool OnlyNeedComplete) {
6867   // Easy case: if we don't have modules, all declarations are visible.
6868   if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
6869     return true;
6870 
6871   // If this definition was instantiated from a template, map back to the
6872   // pattern from which it was instantiated.
6873   if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
6874     // We're in the middle of defining it; this definition should be treated
6875     // as visible.
6876     return true;
6877   } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6878     if (auto *Pattern = RD->getTemplateInstantiationPattern())
6879       RD = Pattern;
6880     D = RD->getDefinition();
6881   } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
6882     if (auto *Pattern = ED->getTemplateInstantiationPattern())
6883       ED = Pattern;
6884     if (OnlyNeedComplete && ED->isFixed()) {
6885       // If the enum has a fixed underlying type, and we're only looking for a
6886       // complete type (not a definition), any visible declaration of it will
6887       // do.
6888       *Suggested = nullptr;
6889       for (auto *Redecl : ED->redecls()) {
6890         if (isVisible(Redecl))
6891           return true;
6892         if (Redecl->isThisDeclarationADefinition() ||
6893             (Redecl->isCanonicalDecl() && !*Suggested))
6894           *Suggested = Redecl;
6895       }
6896       return false;
6897     }
6898     D = ED->getDefinition();
6899   } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6900     if (auto *Pattern = FD->getTemplateInstantiationPattern())
6901       FD = Pattern;
6902     D = FD->getDefinition();
6903   } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6904     if (auto *Pattern = VD->getTemplateInstantiationPattern())
6905       VD = Pattern;
6906     D = VD->getDefinition();
6907   }
6908   assert(D && "missing definition for pattern of instantiated definition");
6909 
6910   *Suggested = D;
6911   if (isVisible(D))
6912     return true;
6913 
6914   // The external source may have additional definitions of this entity that are
6915   // visible, so complete the redeclaration chain now and ask again.
6916   if (auto *Source = Context.getExternalSource()) {
6917     Source->CompleteRedeclChain(D);
6918     return isVisible(D);
6919   }
6920 
6921   return false;
6922 }
6923 
6924 /// Locks in the inheritance model for the given class and all of its bases.
6925 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
6926   RD = RD->getMostRecentDecl();
6927   if (!RD->hasAttr<MSInheritanceAttr>()) {
6928     MSInheritanceAttr::Spelling IM;
6929 
6930     switch (S.MSPointerToMemberRepresentationMethod) {
6931     case LangOptions::PPTMK_BestCase:
6932       IM = RD->calculateInheritanceModel();
6933       break;
6934     case LangOptions::PPTMK_FullGeneralitySingleInheritance:
6935       IM = MSInheritanceAttr::Keyword_single_inheritance;
6936       break;
6937     case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
6938       IM = MSInheritanceAttr::Keyword_multiple_inheritance;
6939       break;
6940     case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
6941       IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
6942       break;
6943     }
6944 
6945     RD->addAttr(MSInheritanceAttr::CreateImplicit(
6946         S.getASTContext(), IM,
6947         /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
6948             LangOptions::PPTMK_BestCase,
6949         S.ImplicitMSInheritanceAttrLoc.isValid()
6950             ? S.ImplicitMSInheritanceAttrLoc
6951             : RD->getSourceRange()));
6952     S.Consumer.AssignInheritanceModel(RD);
6953   }
6954 }
6955 
6956 /// \brief The implementation of RequireCompleteType
6957 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
6958                                    TypeDiagnoser *Diagnoser) {
6959   // FIXME: Add this assertion to make sure we always get instantiation points.
6960   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
6961   // FIXME: Add this assertion to help us flush out problems with
6962   // checking for dependent types and type-dependent expressions.
6963   //
6964   //  assert(!T->isDependentType() &&
6965   //         "Can't ask whether a dependent type is complete");
6966 
6967   // We lock in the inheritance model once somebody has asked us to ensure
6968   // that a pointer-to-member type is complete.
6969   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6970     if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
6971       if (!MPTy->getClass()->isDependentType()) {
6972         (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
6973         assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
6974       }
6975     }
6976   }
6977 
6978   NamedDecl *Def = nullptr;
6979   bool Incomplete = T->isIncompleteType(&Def);
6980 
6981   // Check that any necessary explicit specializations are visible. For an
6982   // enum, we just need the declaration, so don't check this.
6983   if (Def && !isa<EnumDecl>(Def))
6984     checkSpecializationVisibility(Loc, Def);
6985 
6986   // If we have a complete type, we're done.
6987   if (!Incomplete) {
6988     // If we know about the definition but it is not visible, complain.
6989     NamedDecl *SuggestedDef = nullptr;
6990     if (Def &&
6991         !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
6992       // If the user is going to see an error here, recover by making the
6993       // definition visible.
6994       bool TreatAsComplete = Diagnoser && !isSFINAEContext();
6995       if (Diagnoser)
6996         diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
6997                               /*Recover*/TreatAsComplete);
6998       return !TreatAsComplete;
6999     }
7000 
7001     return false;
7002   }
7003 
7004   const TagType *Tag = T->getAs<TagType>();
7005   const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
7006 
7007   // If there's an unimported definition of this type in a module (for
7008   // instance, because we forward declared it, then imported the definition),
7009   // import that definition now.
7010   //
7011   // FIXME: What about other cases where an import extends a redeclaration
7012   // chain for a declaration that can be accessed through a mechanism other
7013   // than name lookup (eg, referenced in a template, or a variable whose type
7014   // could be completed by the module)?
7015   //
7016   // FIXME: Should we map through to the base array element type before
7017   // checking for a tag type?
7018   if (Tag || IFace) {
7019     NamedDecl *D =
7020         Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
7021 
7022     // Avoid diagnosing invalid decls as incomplete.
7023     if (D->isInvalidDecl())
7024       return true;
7025 
7026     // Give the external AST source a chance to complete the type.
7027     if (auto *Source = Context.getExternalSource()) {
7028       if (Tag)
7029         Source->CompleteType(Tag->getDecl());
7030       else
7031         Source->CompleteType(IFace->getDecl());
7032 
7033       // If the external source completed the type, go through the motions
7034       // again to ensure we're allowed to use the completed type.
7035       if (!T->isIncompleteType())
7036         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7037     }
7038   }
7039 
7040   // If we have a class template specialization or a class member of a
7041   // class template specialization, or an array with known size of such,
7042   // try to instantiate it.
7043   QualType MaybeTemplate = T;
7044   while (const ConstantArrayType *Array
7045            = Context.getAsConstantArrayType(MaybeTemplate))
7046     MaybeTemplate = Array->getElementType();
7047   if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
7048     bool Instantiated = false;
7049     bool Diagnosed = false;
7050     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
7051           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
7052       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
7053         Diagnosed = InstantiateClassTemplateSpecialization(
7054             Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
7055             /*Complain=*/Diagnoser);
7056         Instantiated = true;
7057       }
7058     } else if (CXXRecordDecl *Rec
7059                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
7060       CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
7061       if (!Rec->isBeingDefined() && Pattern) {
7062         MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
7063         assert(MSI && "Missing member specialization information?");
7064         // This record was instantiated from a class within a template.
7065         if (MSI->getTemplateSpecializationKind() !=
7066             TSK_ExplicitSpecialization) {
7067           Diagnosed = InstantiateClass(Loc, Rec, Pattern,
7068                                        getTemplateInstantiationArgs(Rec),
7069                                        TSK_ImplicitInstantiation,
7070                                        /*Complain=*/Diagnoser);
7071           Instantiated = true;
7072         }
7073       }
7074     }
7075 
7076     if (Instantiated) {
7077       // Instantiate* might have already complained that the template is not
7078       // defined, if we asked it to.
7079       if (Diagnoser && Diagnosed)
7080         return true;
7081       // If we instantiated a definition, check that it's usable, even if
7082       // instantiation produced an error, so that repeated calls to this
7083       // function give consistent answers.
7084       if (!T->isIncompleteType())
7085         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7086     }
7087   }
7088 
7089   // FIXME: If we didn't instantiate a definition because of an explicit
7090   // specialization declaration, check that it's visible.
7091 
7092   if (!Diagnoser)
7093     return true;
7094 
7095   Diagnoser->diagnose(*this, Loc, T);
7096 
7097   // If the type was a forward declaration of a class/struct/union
7098   // type, produce a note.
7099   if (Tag && !Tag->getDecl()->isInvalidDecl())
7100     Diag(Tag->getDecl()->getLocation(),
7101          Tag->isBeingDefined() ? diag::note_type_being_defined
7102                                : diag::note_forward_declaration)
7103       << QualType(Tag, 0);
7104 
7105   // If the Objective-C class was a forward declaration, produce a note.
7106   if (IFace && !IFace->getDecl()->isInvalidDecl())
7107     Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
7108 
7109   // If we have external information that we can use to suggest a fix,
7110   // produce a note.
7111   if (ExternalSource)
7112     ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
7113 
7114   return true;
7115 }
7116 
7117 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7118                                unsigned DiagID) {
7119   BoundTypeDiagnoser<> Diagnoser(DiagID);
7120   return RequireCompleteType(Loc, T, Diagnoser);
7121 }
7122 
7123 /// \brief Get diagnostic %select index for tag kind for
7124 /// literal type diagnostic message.
7125 /// WARNING: Indexes apply to particular diagnostics only!
7126 ///
7127 /// \returns diagnostic %select index.
7128 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
7129   switch (Tag) {
7130   case TTK_Struct: return 0;
7131   case TTK_Interface: return 1;
7132   case TTK_Class:  return 2;
7133   default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
7134   }
7135 }
7136 
7137 /// @brief Ensure that the type T is a literal type.
7138 ///
7139 /// This routine checks whether the type @p T is a literal type. If @p T is an
7140 /// incomplete type, an attempt is made to complete it. If @p T is a literal
7141 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
7142 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
7143 /// it the type @p T), along with notes explaining why the type is not a
7144 /// literal type, and returns true.
7145 ///
7146 /// @param Loc  The location in the source that the non-literal type
7147 /// diagnostic should refer to.
7148 ///
7149 /// @param T  The type that this routine is examining for literalness.
7150 ///
7151 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
7152 ///
7153 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
7154 /// @c false otherwise.
7155 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
7156                               TypeDiagnoser &Diagnoser) {
7157   assert(!T->isDependentType() && "type should not be dependent");
7158 
7159   QualType ElemType = Context.getBaseElementType(T);
7160   if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
7161       T->isLiteralType(Context))
7162     return false;
7163 
7164   Diagnoser.diagnose(*this, Loc, T);
7165 
7166   if (T->isVariableArrayType())
7167     return true;
7168 
7169   const RecordType *RT = ElemType->getAs<RecordType>();
7170   if (!RT)
7171     return true;
7172 
7173   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7174 
7175   // A partially-defined class type can't be a literal type, because a literal
7176   // class type must have a trivial destructor (which can't be checked until
7177   // the class definition is complete).
7178   if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
7179     return true;
7180 
7181   // If the class has virtual base classes, then it's not an aggregate, and
7182   // cannot have any constexpr constructors or a trivial default constructor,
7183   // so is non-literal. This is better to diagnose than the resulting absence
7184   // of constexpr constructors.
7185   if (RD->getNumVBases()) {
7186     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
7187       << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
7188     for (const auto &I : RD->vbases())
7189       Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
7190           << I.getSourceRange();
7191   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
7192              !RD->hasTrivialDefaultConstructor()) {
7193     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
7194   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
7195     for (const auto &I : RD->bases()) {
7196       if (!I.getType()->isLiteralType(Context)) {
7197         Diag(I.getLocStart(),
7198              diag::note_non_literal_base_class)
7199           << RD << I.getType() << I.getSourceRange();
7200         return true;
7201       }
7202     }
7203     for (const auto *I : RD->fields()) {
7204       if (!I->getType()->isLiteralType(Context) ||
7205           I->getType().isVolatileQualified()) {
7206         Diag(I->getLocation(), diag::note_non_literal_field)
7207           << RD << I << I->getType()
7208           << I->getType().isVolatileQualified();
7209         return true;
7210       }
7211     }
7212   } else if (!RD->hasTrivialDestructor()) {
7213     // All fields and bases are of literal types, so have trivial destructors.
7214     // If this class's destructor is non-trivial it must be user-declared.
7215     CXXDestructorDecl *Dtor = RD->getDestructor();
7216     assert(Dtor && "class has literal fields and bases but no dtor?");
7217     if (!Dtor)
7218       return true;
7219 
7220     Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
7221          diag::note_non_literal_user_provided_dtor :
7222          diag::note_non_literal_nontrivial_dtor) << RD;
7223     if (!Dtor->isUserProvided())
7224       SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
7225   }
7226 
7227   return true;
7228 }
7229 
7230 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
7231   BoundTypeDiagnoser<> Diagnoser(DiagID);
7232   return RequireLiteralType(Loc, T, Diagnoser);
7233 }
7234 
7235 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
7236 /// and qualified by the nested-name-specifier contained in SS.
7237 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
7238                                  const CXXScopeSpec &SS, QualType T) {
7239   if (T.isNull())
7240     return T;
7241   NestedNameSpecifier *NNS;
7242   if (SS.isValid())
7243     NNS = SS.getScopeRep();
7244   else {
7245     if (Keyword == ETK_None)
7246       return T;
7247     NNS = nullptr;
7248   }
7249   return Context.getElaboratedType(Keyword, NNS, T);
7250 }
7251 
7252 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
7253   ExprResult ER = CheckPlaceholderExpr(E);
7254   if (ER.isInvalid()) return QualType();
7255   E = ER.get();
7256 
7257   if (!getLangOpts().CPlusPlus && E->refersToBitField())
7258     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
7259 
7260   if (!E->isTypeDependent()) {
7261     QualType T = E->getType();
7262     if (const TagType *TT = T->getAs<TagType>())
7263       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
7264   }
7265   return Context.getTypeOfExprType(E);
7266 }
7267 
7268 /// getDecltypeForExpr - Given an expr, will return the decltype for
7269 /// that expression, according to the rules in C++11
7270 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
7271 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
7272   if (E->isTypeDependent())
7273     return S.Context.DependentTy;
7274 
7275   // C++11 [dcl.type.simple]p4:
7276   //   The type denoted by decltype(e) is defined as follows:
7277   //
7278   //     - if e is an unparenthesized id-expression or an unparenthesized class
7279   //       member access (5.2.5), decltype(e) is the type of the entity named
7280   //       by e. If there is no such entity, or if e names a set of overloaded
7281   //       functions, the program is ill-formed;
7282   //
7283   // We apply the same rules for Objective-C ivar and property references.
7284   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7285     if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
7286       return VD->getType();
7287   } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7288     if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
7289       return FD->getType();
7290   } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
7291     return IR->getDecl()->getType();
7292   } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
7293     if (PR->isExplicitProperty())
7294       return PR->getExplicitProperty()->getType();
7295   } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
7296     return PE->getType();
7297   }
7298 
7299   // C++11 [expr.lambda.prim]p18:
7300   //   Every occurrence of decltype((x)) where x is a possibly
7301   //   parenthesized id-expression that names an entity of automatic
7302   //   storage duration is treated as if x were transformed into an
7303   //   access to a corresponding data member of the closure type that
7304   //   would have been declared if x were an odr-use of the denoted
7305   //   entity.
7306   using namespace sema;
7307   if (S.getCurLambda()) {
7308     if (isa<ParenExpr>(E)) {
7309       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7310         if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7311           QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
7312           if (!T.isNull())
7313             return S.Context.getLValueReferenceType(T);
7314         }
7315       }
7316     }
7317   }
7318 
7319 
7320   // C++11 [dcl.type.simple]p4:
7321   //   [...]
7322   QualType T = E->getType();
7323   switch (E->getValueKind()) {
7324   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
7325   //       type of e;
7326   case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
7327   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
7328   //       type of e;
7329   case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
7330   //  - otherwise, decltype(e) is the type of e.
7331   case VK_RValue: break;
7332   }
7333 
7334   return T;
7335 }
7336 
7337 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
7338                                  bool AsUnevaluated) {
7339   ExprResult ER = CheckPlaceholderExpr(E);
7340   if (ER.isInvalid()) return QualType();
7341   E = ER.get();
7342 
7343   if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
7344       E->HasSideEffects(Context, false)) {
7345     // The expression operand for decltype is in an unevaluated expression
7346     // context, so side effects could result in unintended consequences.
7347     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7348   }
7349 
7350   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
7351 }
7352 
7353 QualType Sema::BuildUnaryTransformType(QualType BaseType,
7354                                        UnaryTransformType::UTTKind UKind,
7355                                        SourceLocation Loc) {
7356   switch (UKind) {
7357   case UnaryTransformType::EnumUnderlyingType:
7358     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
7359       Diag(Loc, diag::err_only_enums_have_underlying_types);
7360       return QualType();
7361     } else {
7362       QualType Underlying = BaseType;
7363       if (!BaseType->isDependentType()) {
7364         // The enum could be incomplete if we're parsing its definition or
7365         // recovering from an error.
7366         NamedDecl *FwdDecl = nullptr;
7367         if (BaseType->isIncompleteType(&FwdDecl)) {
7368           Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
7369           Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
7370           return QualType();
7371         }
7372 
7373         EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
7374         assert(ED && "EnumType has no EnumDecl");
7375 
7376         DiagnoseUseOfDecl(ED, Loc);
7377 
7378         Underlying = ED->getIntegerType();
7379         assert(!Underlying.isNull());
7380       }
7381       return Context.getUnaryTransformType(BaseType, Underlying,
7382                                         UnaryTransformType::EnumUnderlyingType);
7383     }
7384   }
7385   llvm_unreachable("unknown unary transform type");
7386 }
7387 
7388 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
7389   if (!T->isDependentType()) {
7390     // FIXME: It isn't entirely clear whether incomplete atomic types
7391     // are allowed or not; for simplicity, ban them for the moment.
7392     if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
7393       return QualType();
7394 
7395     int DisallowedKind = -1;
7396     if (T->isArrayType())
7397       DisallowedKind = 1;
7398     else if (T->isFunctionType())
7399       DisallowedKind = 2;
7400     else if (T->isReferenceType())
7401       DisallowedKind = 3;
7402     else if (T->isAtomicType())
7403       DisallowedKind = 4;
7404     else if (T.hasQualifiers())
7405       DisallowedKind = 5;
7406     else if (!T.isTriviallyCopyableType(Context))
7407       // Some other non-trivially-copyable type (probably a C++ class)
7408       DisallowedKind = 6;
7409 
7410     if (DisallowedKind != -1) {
7411       Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
7412       return QualType();
7413     }
7414 
7415     // FIXME: Do we need any handling for ARC here?
7416   }
7417 
7418   // Build the pointer type.
7419   return Context.getAtomicType(T);
7420 }
7421