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