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