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