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