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