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