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