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