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