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