brintos

brintos / llvm-project-archived public Read only

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