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