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