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