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