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