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