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