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