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