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