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