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