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