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