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