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