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