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