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