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