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