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