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