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