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