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