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