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