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