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