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 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported. 2179 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported. 2180 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported. 2181 if (getLangOpts().OpenCL) { 2182 const QualType ArrType = Context.getBaseElementType(T); 2183 if (ArrType->isBlockPointerType() || ArrType->isPipeType() || 2184 ArrType->isSamplerT() || ArrType->isImageType()) { 2185 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType; 2186 return QualType(); 2187 } 2188 } 2189 2190 return T; 2191 } 2192 2193 /// \brief Build an ext-vector type. 2194 /// 2195 /// Run the required checks for the extended vector type. 2196 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, 2197 SourceLocation AttrLoc) { 2198 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined 2199 // in conjunction with complex types (pointers, arrays, functions, etc.). 2200 // 2201 // Additionally, OpenCL prohibits vectors of booleans (they're considered a 2202 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects 2203 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors 2204 // of bool aren't allowed. 2205 if ((!T->isDependentType() && !T->isIntegerType() && 2206 !T->isRealFloatingType()) || 2207 T->isBooleanType()) { 2208 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 2209 return QualType(); 2210 } 2211 2212 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { 2213 llvm::APSInt vecSize(32); 2214 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { 2215 Diag(AttrLoc, diag::err_attribute_argument_type) 2216 << "ext_vector_type" << AANT_ArgumentIntegerConstant 2217 << ArraySize->getSourceRange(); 2218 return QualType(); 2219 } 2220 2221 // Unlike gcc's vector_size attribute, the size is specified as the 2222 // number of elements, not the number of bytes. 2223 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 2224 2225 if (vectorSize == 0) { 2226 Diag(AttrLoc, diag::err_attribute_zero_size) 2227 << ArraySize->getSourceRange(); 2228 return QualType(); 2229 } 2230 2231 if (VectorType::isVectorSizeTooLarge(vectorSize)) { 2232 Diag(AttrLoc, diag::err_attribute_size_too_large) 2233 << ArraySize->getSourceRange(); 2234 return QualType(); 2235 } 2236 2237 return Context.getExtVectorType(T, vectorSize); 2238 } 2239 2240 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); 2241 } 2242 2243 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { 2244 if (T->isArrayType() || T->isFunctionType()) { 2245 Diag(Loc, diag::err_func_returning_array_function) 2246 << T->isFunctionType() << T; 2247 return true; 2248 } 2249 2250 // Functions cannot return half FP. 2251 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) { 2252 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << 2253 FixItHint::CreateInsertion(Loc, "*"); 2254 return true; 2255 } 2256 2257 // Methods cannot return interface types. All ObjC objects are 2258 // passed by reference. 2259 if (T->isObjCObjectType()) { 2260 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T; 2261 return 0; 2262 } 2263 2264 return false; 2265 } 2266 2267 QualType Sema::BuildFunctionType(QualType T, 2268 MutableArrayRef<QualType> ParamTypes, 2269 SourceLocation Loc, DeclarationName Entity, 2270 const FunctionProtoType::ExtProtoInfo &EPI) { 2271 bool Invalid = false; 2272 2273 Invalid |= CheckFunctionReturnType(T, Loc); 2274 2275 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { 2276 // FIXME: Loc is too inprecise here, should use proper locations for args. 2277 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); 2278 if (ParamType->isVoidType()) { 2279 Diag(Loc, diag::err_param_with_void_type); 2280 Invalid = true; 2281 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) { 2282 // Disallow half FP arguments. 2283 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << 2284 FixItHint::CreateInsertion(Loc, "*"); 2285 Invalid = true; 2286 } 2287 2288 ParamTypes[Idx] = ParamType; 2289 } 2290 2291 if (Invalid) 2292 return QualType(); 2293 2294 return Context.getFunctionType(T, ParamTypes, EPI); 2295 } 2296 2297 /// \brief Build a member pointer type \c T Class::*. 2298 /// 2299 /// \param T the type to which the member pointer refers. 2300 /// \param Class the class type into which the member pointer points. 2301 /// \param Loc the location where this type begins 2302 /// \param Entity the name of the entity that will have this member pointer type 2303 /// 2304 /// \returns a member pointer type, if successful, or a NULL type if there was 2305 /// an error. 2306 QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 2307 SourceLocation Loc, 2308 DeclarationName Entity) { 2309 // Verify that we're not building a pointer to pointer to function with 2310 // exception specification. 2311 if (CheckDistantExceptionSpec(T)) { 2312 Diag(Loc, diag::err_distant_exception_spec); 2313 return QualType(); 2314 } 2315 2316 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 2317 // with reference type, or "cv void." 2318 if (T->isReferenceType()) { 2319 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 2320 << getPrintableNameForEntity(Entity) << T; 2321 return QualType(); 2322 } 2323 2324 if (T->isVoidType()) { 2325 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 2326 << getPrintableNameForEntity(Entity); 2327 return QualType(); 2328 } 2329 2330 if (!Class->isDependentType() && !Class->isRecordType()) { 2331 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 2332 return QualType(); 2333 } 2334 2335 // Adjust the default free function calling convention to the default method 2336 // calling convention. 2337 bool IsCtorOrDtor = 2338 (Entity.getNameKind() == DeclarationName::CXXConstructorName) || 2339 (Entity.getNameKind() == DeclarationName::CXXDestructorName); 2340 if (T->isFunctionType()) 2341 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc); 2342 2343 return Context.getMemberPointerType(T, Class.getTypePtr()); 2344 } 2345 2346 /// \brief Build a block pointer type. 2347 /// 2348 /// \param T The type to which we'll be building a block pointer. 2349 /// 2350 /// \param Loc The source location, used for diagnostics. 2351 /// 2352 /// \param Entity The name of the entity that involves the block pointer 2353 /// type, if known. 2354 /// 2355 /// \returns A suitable block pointer type, if there are no 2356 /// errors. Otherwise, returns a NULL type. 2357 QualType Sema::BuildBlockPointerType(QualType T, 2358 SourceLocation Loc, 2359 DeclarationName Entity) { 2360 if (!T->isFunctionType()) { 2361 Diag(Loc, diag::err_nonfunction_block_type); 2362 return QualType(); 2363 } 2364 2365 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) 2366 return QualType(); 2367 2368 return Context.getBlockPointerType(T); 2369 } 2370 2371 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 2372 QualType QT = Ty.get(); 2373 if (QT.isNull()) { 2374 if (TInfo) *TInfo = nullptr; 2375 return QualType(); 2376 } 2377 2378 TypeSourceInfo *DI = nullptr; 2379 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 2380 QT = LIT->getType(); 2381 DI = LIT->getTypeSourceInfo(); 2382 } 2383 2384 if (TInfo) *TInfo = DI; 2385 return QT; 2386 } 2387 2388 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 2389 Qualifiers::ObjCLifetime ownership, 2390 unsigned chunkIndex); 2391 2392 /// Given that this is the declaration of a parameter under ARC, 2393 /// attempt to infer attributes and such for pointer-to-whatever 2394 /// types. 2395 static void inferARCWriteback(TypeProcessingState &state, 2396 QualType &declSpecType) { 2397 Sema &S = state.getSema(); 2398 Declarator &declarator = state.getDeclarator(); 2399 2400 // TODO: should we care about decl qualifiers? 2401 2402 // Check whether the declarator has the expected form. We walk 2403 // from the inside out in order to make the block logic work. 2404 unsigned outermostPointerIndex = 0; 2405 bool isBlockPointer = false; 2406 unsigned numPointers = 0; 2407 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 2408 unsigned chunkIndex = i; 2409 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); 2410 switch (chunk.Kind) { 2411 case DeclaratorChunk::Paren: 2412 // Ignore parens. 2413 break; 2414 2415 case DeclaratorChunk::Reference: 2416 case DeclaratorChunk::Pointer: 2417 // Count the number of pointers. Treat references 2418 // interchangeably as pointers; if they're mis-ordered, normal 2419 // type building will discover that. 2420 outermostPointerIndex = chunkIndex; 2421 numPointers++; 2422 break; 2423 2424 case DeclaratorChunk::BlockPointer: 2425 // If we have a pointer to block pointer, that's an acceptable 2426 // indirect reference; anything else is not an application of 2427 // the rules. 2428 if (numPointers != 1) return; 2429 numPointers++; 2430 outermostPointerIndex = chunkIndex; 2431 isBlockPointer = true; 2432 2433 // We don't care about pointer structure in return values here. 2434 goto done; 2435 2436 case DeclaratorChunk::Array: // suppress if written (id[])? 2437 case DeclaratorChunk::Function: 2438 case DeclaratorChunk::MemberPointer: 2439 case DeclaratorChunk::Pipe: 2440 return; 2441 } 2442 } 2443 done: 2444 2445 // If we have *one* pointer, then we want to throw the qualifier on 2446 // the declaration-specifiers, which means that it needs to be a 2447 // retainable object type. 2448 if (numPointers == 1) { 2449 // If it's not a retainable object type, the rule doesn't apply. 2450 if (!declSpecType->isObjCRetainableType()) return; 2451 2452 // If it already has lifetime, don't do anything. 2453 if (declSpecType.getObjCLifetime()) return; 2454 2455 // Otherwise, modify the type in-place. 2456 Qualifiers qs; 2457 2458 if (declSpecType->isObjCARCImplicitlyUnretainedType()) 2459 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); 2460 else 2461 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); 2462 declSpecType = S.Context.getQualifiedType(declSpecType, qs); 2463 2464 // If we have *two* pointers, then we want to throw the qualifier on 2465 // the outermost pointer. 2466 } else if (numPointers == 2) { 2467 // If we don't have a block pointer, we need to check whether the 2468 // declaration-specifiers gave us something that will turn into a 2469 // retainable object pointer after we slap the first pointer on it. 2470 if (!isBlockPointer && !declSpecType->isObjCObjectType()) 2471 return; 2472 2473 // Look for an explicit lifetime attribute there. 2474 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); 2475 if (chunk.Kind != DeclaratorChunk::Pointer && 2476 chunk.Kind != DeclaratorChunk::BlockPointer) 2477 return; 2478 for (const AttributeList *attr = chunk.getAttrs(); attr; 2479 attr = attr->getNext()) 2480 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 2481 return; 2482 2483 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, 2484 outermostPointerIndex); 2485 2486 // Any other number of pointers/references does not trigger the rule. 2487 } else return; 2488 2489 // TODO: mark whether we did this inference? 2490 } 2491 2492 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 2493 SourceLocation FallbackLoc, 2494 SourceLocation ConstQualLoc, 2495 SourceLocation VolatileQualLoc, 2496 SourceLocation RestrictQualLoc, 2497 SourceLocation AtomicQualLoc) { 2498 if (!Quals) 2499 return; 2500 2501 struct Qual { 2502 const char *Name; 2503 unsigned Mask; 2504 SourceLocation Loc; 2505 } const QualKinds[4] = { 2506 { "const", DeclSpec::TQ_const, ConstQualLoc }, 2507 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc }, 2508 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc }, 2509 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc } 2510 }; 2511 2512 SmallString<32> QualStr; 2513 unsigned NumQuals = 0; 2514 SourceLocation Loc; 2515 FixItHint FixIts[4]; 2516 2517 // Build a string naming the redundant qualifiers. 2518 for (unsigned I = 0; I != 4; ++I) { 2519 if (Quals & QualKinds[I].Mask) { 2520 if (!QualStr.empty()) QualStr += ' '; 2521 QualStr += QualKinds[I].Name; 2522 2523 // If we have a location for the qualifier, offer a fixit. 2524 SourceLocation QualLoc = QualKinds[I].Loc; 2525 if (QualLoc.isValid()) { 2526 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); 2527 if (Loc.isInvalid() || 2528 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) 2529 Loc = QualLoc; 2530 } 2531 2532 ++NumQuals; 2533 } 2534 } 2535 2536 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) 2537 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; 2538 } 2539 2540 // Diagnose pointless type qualifiers on the return type of a function. 2541 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, 2542 Declarator &D, 2543 unsigned FunctionChunkIndex) { 2544 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) { 2545 // FIXME: TypeSourceInfo doesn't preserve location information for 2546 // qualifiers. 2547 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2548 RetTy.getLocalCVRQualifiers(), 2549 D.getIdentifierLoc()); 2550 return; 2551 } 2552 2553 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, 2554 End = D.getNumTypeObjects(); 2555 OuterChunkIndex != End; ++OuterChunkIndex) { 2556 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); 2557 switch (OuterChunk.Kind) { 2558 case DeclaratorChunk::Paren: 2559 continue; 2560 2561 case DeclaratorChunk::Pointer: { 2562 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; 2563 S.diagnoseIgnoredQualifiers( 2564 diag::warn_qual_return_type, 2565 PTI.TypeQuals, 2566 SourceLocation(), 2567 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), 2568 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), 2569 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), 2570 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc)); 2571 return; 2572 } 2573 2574 case DeclaratorChunk::Function: 2575 case DeclaratorChunk::BlockPointer: 2576 case DeclaratorChunk::Reference: 2577 case DeclaratorChunk::Array: 2578 case DeclaratorChunk::MemberPointer: 2579 case DeclaratorChunk::Pipe: 2580 // FIXME: We can't currently provide an accurate source location and a 2581 // fix-it hint for these. 2582 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; 2583 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2584 RetTy.getCVRQualifiers() | AtomicQual, 2585 D.getIdentifierLoc()); 2586 return; 2587 } 2588 2589 llvm_unreachable("unknown declarator chunk kind"); 2590 } 2591 2592 // If the qualifiers come from a conversion function type, don't diagnose 2593 // them -- they're not necessarily redundant, since such a conversion 2594 // operator can be explicitly called as "x.operator const int()". 2595 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 2596 return; 2597 2598 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers 2599 // which are present there. 2600 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2601 D.getDeclSpec().getTypeQualifiers(), 2602 D.getIdentifierLoc(), 2603 D.getDeclSpec().getConstSpecLoc(), 2604 D.getDeclSpec().getVolatileSpecLoc(), 2605 D.getDeclSpec().getRestrictSpecLoc(), 2606 D.getDeclSpec().getAtomicSpecLoc()); 2607 } 2608 2609 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, 2610 TypeSourceInfo *&ReturnTypeInfo) { 2611 Sema &SemaRef = state.getSema(); 2612 Declarator &D = state.getDeclarator(); 2613 QualType T; 2614 ReturnTypeInfo = nullptr; 2615 2616 // The TagDecl owned by the DeclSpec. 2617 TagDecl *OwnedTagDecl = nullptr; 2618 2619 switch (D.getName().getKind()) { 2620 case UnqualifiedId::IK_ImplicitSelfParam: 2621 case UnqualifiedId::IK_OperatorFunctionId: 2622 case UnqualifiedId::IK_Identifier: 2623 case UnqualifiedId::IK_LiteralOperatorId: 2624 case UnqualifiedId::IK_TemplateId: 2625 T = ConvertDeclSpecToType(state); 2626 2627 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 2628 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2629 // Owned declaration is embedded in declarator. 2630 OwnedTagDecl->setEmbeddedInDeclarator(true); 2631 } 2632 break; 2633 2634 case UnqualifiedId::IK_ConstructorName: 2635 case UnqualifiedId::IK_ConstructorTemplateId: 2636 case UnqualifiedId::IK_DestructorName: 2637 // Constructors and destructors don't have return types. Use 2638 // "void" instead. 2639 T = SemaRef.Context.VoidTy; 2640 processTypeAttrs(state, T, TAL_DeclSpec, 2641 D.getDeclSpec().getAttributes().getList()); 2642 break; 2643 2644 case UnqualifiedId::IK_ConversionFunctionId: 2645 // The result type of a conversion function is the type that it 2646 // converts to. 2647 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, 2648 &ReturnTypeInfo); 2649 break; 2650 } 2651 2652 if (D.getAttributes()) 2653 distributeTypeAttrsFromDeclarator(state, T); 2654 2655 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 2656 if (D.getDeclSpec().containsPlaceholderType()) { 2657 int Error = -1; 2658 2659 switch (D.getContext()) { 2660 case Declarator::LambdaExprContext: 2661 llvm_unreachable("Can't specify a type specifier in lambda grammar"); 2662 case Declarator::ObjCParameterContext: 2663 case Declarator::ObjCResultContext: 2664 case Declarator::PrototypeContext: 2665 Error = 0; 2666 break; 2667 case Declarator::LambdaExprParameterContext: 2668 // In C++14, generic lambdas allow 'auto' in their parameters. 2669 if (!(SemaRef.getLangOpts().CPlusPlus14 2670 && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto)) 2671 Error = 16; 2672 break; 2673 case Declarator::MemberContext: { 2674 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || 2675 D.isFunctionDeclarator()) 2676 break; 2677 bool Cxx = SemaRef.getLangOpts().CPlusPlus; 2678 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { 2679 case TTK_Enum: llvm_unreachable("unhandled tag kind"); 2680 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break; 2681 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break; 2682 case TTK_Class: Error = 5; /* Class member */ break; 2683 case TTK_Interface: Error = 6; /* Interface member */ break; 2684 } 2685 break; 2686 } 2687 case Declarator::CXXCatchContext: 2688 case Declarator::ObjCCatchContext: 2689 Error = 7; // Exception declaration 2690 break; 2691 case Declarator::TemplateParamContext: 2692 Error = 8; // Template parameter 2693 break; 2694 case Declarator::BlockLiteralContext: 2695 Error = 9; // Block literal 2696 break; 2697 case Declarator::TemplateTypeArgContext: 2698 Error = 10; // Template type argument 2699 break; 2700 case Declarator::AliasDeclContext: 2701 case Declarator::AliasTemplateContext: 2702 Error = 12; // Type alias 2703 break; 2704 case Declarator::TrailingReturnContext: 2705 if (!SemaRef.getLangOpts().CPlusPlus14 || 2706 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type) 2707 Error = 13; // Function return type 2708 break; 2709 case Declarator::ConversionIdContext: 2710 if (!SemaRef.getLangOpts().CPlusPlus14 || 2711 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type) 2712 Error = 14; // conversion-type-id 2713 break; 2714 case Declarator::TypeNameContext: 2715 Error = 15; // Generic 2716 break; 2717 case Declarator::FileContext: 2718 case Declarator::BlockContext: 2719 case Declarator::ForContext: 2720 case Declarator::ConditionContext: 2721 break; 2722 case Declarator::CXXNewContext: 2723 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type) 2724 Error = 17; // 'new' type 2725 break; 2726 case Declarator::KNRTypeListContext: 2727 Error = 18; // K&R function parameter 2728 break; 2729 } 2730 2731 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 2732 Error = 11; 2733 2734 // In Objective-C it is an error to use 'auto' on a function declarator 2735 // (and everywhere for '__auto_type'). 2736 if (D.isFunctionDeclarator() && 2737 (!SemaRef.getLangOpts().CPlusPlus11 || 2738 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)) 2739 Error = 13; 2740 2741 bool HaveTrailing = false; 2742 2743 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator 2744 // contains a trailing return type. That is only legal at the outermost 2745 // level. Check all declarator chunks (outermost first) anyway, to give 2746 // better diagnostics. 2747 // We don't support '__auto_type' with trailing return types. 2748 if (SemaRef.getLangOpts().CPlusPlus11 && 2749 D.getDeclSpec().getTypeSpecType() != DeclSpec::TST_auto_type) { 2750 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2751 unsigned chunkIndex = e - i - 1; 2752 state.setCurrentChunkIndex(chunkIndex); 2753 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 2754 if (DeclType.Kind == DeclaratorChunk::Function) { 2755 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2756 if (FTI.hasTrailingReturnType()) { 2757 HaveTrailing = true; 2758 Error = -1; 2759 break; 2760 } 2761 } 2762 } 2763 } 2764 2765 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); 2766 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 2767 AutoRange = D.getName().getSourceRange(); 2768 2769 if (Error != -1) { 2770 unsigned Keyword; 2771 switch (D.getDeclSpec().getTypeSpecType()) { 2772 case DeclSpec::TST_auto: Keyword = 0; break; 2773 case DeclSpec::TST_decltype_auto: Keyword = 1; break; 2774 case DeclSpec::TST_auto_type: Keyword = 2; break; 2775 default: llvm_unreachable("unknown auto TypeSpecType"); 2776 } 2777 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) 2778 << Keyword << Error << AutoRange; 2779 T = SemaRef.Context.IntTy; 2780 D.setInvalidType(true); 2781 } else if (!HaveTrailing) { 2782 // If there was a trailing return type, we already got 2783 // warn_cxx98_compat_trailing_return_type in the parser. 2784 SemaRef.Diag(AutoRange.getBegin(), 2785 diag::warn_cxx98_compat_auto_type_specifier) 2786 << AutoRange; 2787 } 2788 } 2789 2790 if (SemaRef.getLangOpts().CPlusPlus && 2791 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 2792 // Check the contexts where C++ forbids the declaration of a new class 2793 // or enumeration in a type-specifier-seq. 2794 unsigned DiagID = 0; 2795 switch (D.getContext()) { 2796 case Declarator::TrailingReturnContext: 2797 // Class and enumeration definitions are syntactically not allowed in 2798 // trailing return types. 2799 llvm_unreachable("parser should not have allowed this"); 2800 break; 2801 case Declarator::FileContext: 2802 case Declarator::MemberContext: 2803 case Declarator::BlockContext: 2804 case Declarator::ForContext: 2805 case Declarator::BlockLiteralContext: 2806 case Declarator::LambdaExprContext: 2807 // C++11 [dcl.type]p3: 2808 // A type-specifier-seq shall not define a class or enumeration unless 2809 // it appears in the type-id of an alias-declaration (7.1.3) that is not 2810 // the declaration of a template-declaration. 2811 case Declarator::AliasDeclContext: 2812 break; 2813 case Declarator::AliasTemplateContext: 2814 DiagID = diag::err_type_defined_in_alias_template; 2815 break; 2816 case Declarator::TypeNameContext: 2817 case Declarator::ConversionIdContext: 2818 case Declarator::TemplateParamContext: 2819 case Declarator::CXXNewContext: 2820 case Declarator::CXXCatchContext: 2821 case Declarator::ObjCCatchContext: 2822 case Declarator::TemplateTypeArgContext: 2823 DiagID = diag::err_type_defined_in_type_specifier; 2824 break; 2825 case Declarator::PrototypeContext: 2826 case Declarator::LambdaExprParameterContext: 2827 case Declarator::ObjCParameterContext: 2828 case Declarator::ObjCResultContext: 2829 case Declarator::KNRTypeListContext: 2830 // C++ [dcl.fct]p6: 2831 // Types shall not be defined in return or parameter types. 2832 DiagID = diag::err_type_defined_in_param_type; 2833 break; 2834 case Declarator::ConditionContext: 2835 // C++ 6.4p2: 2836 // The type-specifier-seq shall not contain typedef and shall not declare 2837 // a new class or enumeration. 2838 DiagID = diag::err_type_defined_in_condition; 2839 break; 2840 } 2841 2842 if (DiagID != 0) { 2843 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) 2844 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2845 D.setInvalidType(true); 2846 } 2847 } 2848 2849 assert(!T.isNull() && "This function should not return a null type"); 2850 return T; 2851 } 2852 2853 /// Produce an appropriate diagnostic for an ambiguity between a function 2854 /// declarator and a C++ direct-initializer. 2855 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, 2856 DeclaratorChunk &DeclType, QualType RT) { 2857 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2858 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity"); 2859 2860 // If the return type is void there is no ambiguity. 2861 if (RT->isVoidType()) 2862 return; 2863 2864 // An initializer for a non-class type can have at most one argument. 2865 if (!RT->isRecordType() && FTI.NumParams > 1) 2866 return; 2867 2868 // An initializer for a reference must have exactly one argument. 2869 if (RT->isReferenceType() && FTI.NumParams != 1) 2870 return; 2871 2872 // Only warn if this declarator is declaring a function at block scope, and 2873 // doesn't have a storage class (such as 'extern') specified. 2874 if (!D.isFunctionDeclarator() || 2875 D.getFunctionDefinitionKind() != FDK_Declaration || 2876 !S.CurContext->isFunctionOrMethod() || 2877 D.getDeclSpec().getStorageClassSpec() 2878 != DeclSpec::SCS_unspecified) 2879 return; 2880 2881 // Inside a condition, a direct initializer is not permitted. We allow one to 2882 // be parsed in order to give better diagnostics in condition parsing. 2883 if (D.getContext() == Declarator::ConditionContext) 2884 return; 2885 2886 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); 2887 2888 S.Diag(DeclType.Loc, 2889 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration 2890 : diag::warn_empty_parens_are_function_decl) 2891 << ParenRange; 2892 2893 // If the declaration looks like: 2894 // T var1, 2895 // f(); 2896 // and name lookup finds a function named 'f', then the ',' was 2897 // probably intended to be a ';'. 2898 if (!D.isFirstDeclarator() && D.getIdentifier()) { 2899 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); 2900 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); 2901 if (Comma.getFileID() != Name.getFileID() || 2902 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { 2903 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 2904 Sema::LookupOrdinaryName); 2905 if (S.LookupName(Result, S.getCurScope())) 2906 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) 2907 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") 2908 << D.getIdentifier(); 2909 } 2910 } 2911 2912 if (FTI.NumParams > 0) { 2913 // For a declaration with parameters, eg. "T var(T());", suggest adding 2914 // parens around the first parameter to turn the declaration into a 2915 // variable declaration. 2916 SourceRange Range = FTI.Params[0].Param->getSourceRange(); 2917 SourceLocation B = Range.getBegin(); 2918 SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); 2919 // FIXME: Maybe we should suggest adding braces instead of parens 2920 // in C++11 for classes that don't have an initializer_list constructor. 2921 S.Diag(B, diag::note_additional_parens_for_variable_declaration) 2922 << FixItHint::CreateInsertion(B, "(") 2923 << FixItHint::CreateInsertion(E, ")"); 2924 } else { 2925 // For a declaration without parameters, eg. "T var();", suggest replacing 2926 // the parens with an initializer to turn the declaration into a variable 2927 // declaration. 2928 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 2929 2930 // Empty parens mean value-initialization, and no parens mean 2931 // default initialization. These are equivalent if the default 2932 // constructor is user-provided or if zero-initialization is a 2933 // no-op. 2934 if (RD && RD->hasDefinition() && 2935 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) 2936 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) 2937 << FixItHint::CreateRemoval(ParenRange); 2938 else { 2939 std::string Init = 2940 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); 2941 if (Init.empty() && S.LangOpts.CPlusPlus11) 2942 Init = "{}"; 2943 if (!Init.empty()) 2944 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) 2945 << FixItHint::CreateReplacement(ParenRange, Init); 2946 } 2947 } 2948 } 2949 2950 /// Helper for figuring out the default CC for a function declarator type. If 2951 /// this is the outermost chunk, then we can determine the CC from the 2952 /// declarator context. If not, then this could be either a member function 2953 /// type or normal function type. 2954 static CallingConv 2955 getCCForDeclaratorChunk(Sema &S, Declarator &D, 2956 const DeclaratorChunk::FunctionTypeInfo &FTI, 2957 unsigned ChunkIndex) { 2958 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function); 2959 2960 bool IsCXXInstanceMethod = false; 2961 2962 if (S.getLangOpts().CPlusPlus) { 2963 // Look inwards through parentheses to see if this chunk will form a 2964 // member pointer type or if we're the declarator. Any type attributes 2965 // between here and there will override the CC we choose here. 2966 unsigned I = ChunkIndex; 2967 bool FoundNonParen = false; 2968 while (I && !FoundNonParen) { 2969 --I; 2970 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) 2971 FoundNonParen = true; 2972 } 2973 2974 if (FoundNonParen) { 2975 // If we're not the declarator, we're a regular function type unless we're 2976 // in a member pointer. 2977 IsCXXInstanceMethod = 2978 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; 2979 } else if (D.getContext() == Declarator::LambdaExprContext) { 2980 // This can only be a call operator for a lambda, which is an instance 2981 // method. 2982 IsCXXInstanceMethod = true; 2983 } else { 2984 // We're the innermost decl chunk, so must be a function declarator. 2985 assert(D.isFunctionDeclarator()); 2986 2987 // If we're inside a record, we're declaring a method, but it could be 2988 // explicitly or implicitly static. 2989 IsCXXInstanceMethod = 2990 D.isFirstDeclarationOfMember() && 2991 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 2992 !D.isStaticMember(); 2993 } 2994 } 2995 2996 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic, 2997 IsCXXInstanceMethod); 2998 2999 // Attribute AT_OpenCLKernel affects the calling convention only on 3000 // the SPIR target, hence it cannot be treated as a calling 3001 // convention attribute. This is the simplest place to infer 3002 // "spir_kernel" for OpenCL kernels on SPIR. 3003 if (CC == CC_SpirFunction) { 3004 for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList(); 3005 Attr; Attr = Attr->getNext()) { 3006 if (Attr->getKind() == AttributeList::AT_OpenCLKernel) { 3007 CC = CC_SpirKernel; 3008 break; 3009 } 3010 } 3011 } 3012 3013 return CC; 3014 } 3015 3016 namespace { 3017 /// A simple notion of pointer kinds, which matches up with the various 3018 /// pointer declarators. 3019 enum class SimplePointerKind { 3020 Pointer, 3021 BlockPointer, 3022 MemberPointer, 3023 }; 3024 } // end anonymous namespace 3025 3026 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { 3027 switch (nullability) { 3028 case NullabilityKind::NonNull: 3029 if (!Ident__Nonnull) 3030 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); 3031 return Ident__Nonnull; 3032 3033 case NullabilityKind::Nullable: 3034 if (!Ident__Nullable) 3035 Ident__Nullable = PP.getIdentifierInfo("_Nullable"); 3036 return Ident__Nullable; 3037 3038 case NullabilityKind::Unspecified: 3039 if (!Ident__Null_unspecified) 3040 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); 3041 return Ident__Null_unspecified; 3042 } 3043 llvm_unreachable("Unknown nullability kind."); 3044 } 3045 3046 /// Retrieve the identifier "NSError". 3047 IdentifierInfo *Sema::getNSErrorIdent() { 3048 if (!Ident_NSError) 3049 Ident_NSError = PP.getIdentifierInfo("NSError"); 3050 3051 return Ident_NSError; 3052 } 3053 3054 /// Check whether there is a nullability attribute of any kind in the given 3055 /// attribute list. 3056 static bool hasNullabilityAttr(const AttributeList *attrs) { 3057 for (const AttributeList *attr = attrs; attr; 3058 attr = attr->getNext()) { 3059 if (attr->getKind() == AttributeList::AT_TypeNonNull || 3060 attr->getKind() == AttributeList::AT_TypeNullable || 3061 attr->getKind() == AttributeList::AT_TypeNullUnspecified) 3062 return true; 3063 } 3064 3065 return false; 3066 } 3067 3068 namespace { 3069 /// Describes the kind of a pointer a declarator describes. 3070 enum class PointerDeclaratorKind { 3071 // Not a pointer. 3072 NonPointer, 3073 // Single-level pointer. 3074 SingleLevelPointer, 3075 // Multi-level pointer (of any pointer kind). 3076 MultiLevelPointer, 3077 // CFFooRef* 3078 MaybePointerToCFRef, 3079 // CFErrorRef* 3080 CFErrorRefPointer, 3081 // NSError** 3082 NSErrorPointerPointer, 3083 }; 3084 } // end anonymous namespace 3085 3086 /// Classify the given declarator, whose type-specified is \c type, based on 3087 /// what kind of pointer it refers to. 3088 /// 3089 /// This is used to determine the default nullability. 3090 static PointerDeclaratorKind classifyPointerDeclarator(Sema &S, 3091 QualType type, 3092 Declarator &declarator) { 3093 unsigned numNormalPointers = 0; 3094 3095 // For any dependent type, we consider it a non-pointer. 3096 if (type->isDependentType()) 3097 return PointerDeclaratorKind::NonPointer; 3098 3099 // Look through the declarator chunks to identify pointers. 3100 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { 3101 DeclaratorChunk &chunk = declarator.getTypeObject(i); 3102 switch (chunk.Kind) { 3103 case DeclaratorChunk::Array: 3104 case DeclaratorChunk::Function: 3105 case DeclaratorChunk::Pipe: 3106 break; 3107 3108 case DeclaratorChunk::BlockPointer: 3109 case DeclaratorChunk::MemberPointer: 3110 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3111 : PointerDeclaratorKind::SingleLevelPointer; 3112 3113 case DeclaratorChunk::Paren: 3114 case DeclaratorChunk::Reference: 3115 continue; 3116 3117 case DeclaratorChunk::Pointer: 3118 ++numNormalPointers; 3119 if (numNormalPointers > 2) 3120 return PointerDeclaratorKind::MultiLevelPointer; 3121 continue; 3122 } 3123 } 3124 3125 // Then, dig into the type specifier itself. 3126 unsigned numTypeSpecifierPointers = 0; 3127 do { 3128 // Decompose normal pointers. 3129 if (auto ptrType = type->getAs<PointerType>()) { 3130 ++numNormalPointers; 3131 3132 if (numNormalPointers > 2) 3133 return PointerDeclaratorKind::MultiLevelPointer; 3134 3135 type = ptrType->getPointeeType(); 3136 ++numTypeSpecifierPointers; 3137 continue; 3138 } 3139 3140 // Decompose block pointers. 3141 if (type->getAs<BlockPointerType>()) { 3142 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3143 : PointerDeclaratorKind::SingleLevelPointer; 3144 } 3145 3146 // Decompose member pointers. 3147 if (type->getAs<MemberPointerType>()) { 3148 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3149 : PointerDeclaratorKind::SingleLevelPointer; 3150 } 3151 3152 // Look at Objective-C object pointers. 3153 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { 3154 ++numNormalPointers; 3155 ++numTypeSpecifierPointers; 3156 3157 // If this is NSError**, report that. 3158 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { 3159 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && 3160 numNormalPointers == 2 && numTypeSpecifierPointers < 2) { 3161 return PointerDeclaratorKind::NSErrorPointerPointer; 3162 } 3163 } 3164 3165 break; 3166 } 3167 3168 // Look at Objective-C class types. 3169 if (auto objcClass = type->getAs<ObjCInterfaceType>()) { 3170 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { 3171 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) 3172 return PointerDeclaratorKind::NSErrorPointerPointer;; 3173 } 3174 3175 break; 3176 } 3177 3178 // If at this point we haven't seen a pointer, we won't see one. 3179 if (numNormalPointers == 0) 3180 return PointerDeclaratorKind::NonPointer; 3181 3182 if (auto recordType = type->getAs<RecordType>()) { 3183 RecordDecl *recordDecl = recordType->getDecl(); 3184 3185 bool isCFError = false; 3186 if (S.CFError) { 3187 // If we already know about CFError, test it directly. 3188 isCFError = (S.CFError == recordDecl); 3189 } else { 3190 // Check whether this is CFError, which we identify based on its bridge 3191 // to NSError. 3192 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) { 3193 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) { 3194 if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) { 3195 S.CFError = recordDecl; 3196 isCFError = true; 3197 } 3198 } 3199 } 3200 } 3201 3202 // If this is CFErrorRef*, report it as such. 3203 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) { 3204 return PointerDeclaratorKind::CFErrorRefPointer; 3205 } 3206 break; 3207 } 3208 3209 break; 3210 } while (true); 3211 3212 switch (numNormalPointers) { 3213 case 0: 3214 return PointerDeclaratorKind::NonPointer; 3215 3216 case 1: 3217 return PointerDeclaratorKind::SingleLevelPointer; 3218 3219 case 2: 3220 return PointerDeclaratorKind::MaybePointerToCFRef; 3221 3222 default: 3223 return PointerDeclaratorKind::MultiLevelPointer; 3224 } 3225 } 3226 3227 static FileID getNullabilityCompletenessCheckFileID(Sema &S, 3228 SourceLocation loc) { 3229 // If we're anywhere in a function, method, or closure context, don't perform 3230 // completeness checks. 3231 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { 3232 if (ctx->isFunctionOrMethod()) 3233 return FileID(); 3234 3235 if (ctx->isFileContext()) 3236 break; 3237 } 3238 3239 // We only care about the expansion location. 3240 loc = S.SourceMgr.getExpansionLoc(loc); 3241 FileID file = S.SourceMgr.getFileID(loc); 3242 if (file.isInvalid()) 3243 return FileID(); 3244 3245 // Retrieve file information. 3246 bool invalid = false; 3247 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); 3248 if (invalid || !sloc.isFile()) 3249 return FileID(); 3250 3251 // We don't want to perform completeness checks on the main file or in 3252 // system headers. 3253 const SrcMgr::FileInfo &fileInfo = sloc.getFile(); 3254 if (fileInfo.getIncludeLoc().isInvalid()) 3255 return FileID(); 3256 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && 3257 S.Diags.getSuppressSystemWarnings()) { 3258 return FileID(); 3259 } 3260 3261 return file; 3262 } 3263 3264 /// Check for consistent use of nullability. 3265 static void checkNullabilityConsistency(TypeProcessingState &state, 3266 SimplePointerKind pointerKind, 3267 SourceLocation pointerLoc) { 3268 Sema &S = state.getSema(); 3269 3270 // Determine which file we're performing consistency checking for. 3271 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); 3272 if (file.isInvalid()) 3273 return; 3274 3275 // If we haven't seen any type nullability in this file, we won't warn now 3276 // about anything. 3277 FileNullability &fileNullability = S.NullabilityMap[file]; 3278 if (!fileNullability.SawTypeNullability) { 3279 // If this is the first pointer declarator in the file, record it. 3280 if (fileNullability.PointerLoc.isInvalid() && 3281 !S.Context.getDiagnostics().isIgnored(diag::warn_nullability_missing, 3282 pointerLoc)) { 3283 fileNullability.PointerLoc = pointerLoc; 3284 fileNullability.PointerKind = static_cast<unsigned>(pointerKind); 3285 } 3286 3287 return; 3288 } 3289 3290 // Complain about missing nullability. 3291 S.Diag(pointerLoc, diag::warn_nullability_missing) 3292 << static_cast<unsigned>(pointerKind); 3293 } 3294 3295 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 3296 QualType declSpecType, 3297 TypeSourceInfo *TInfo) { 3298 // The TypeSourceInfo that this function returns will not be a null type. 3299 // If there is an error, this function will fill in a dummy type as fallback. 3300 QualType T = declSpecType; 3301 Declarator &D = state.getDeclarator(); 3302 Sema &S = state.getSema(); 3303 ASTContext &Context = S.Context; 3304 const LangOptions &LangOpts = S.getLangOpts(); 3305 3306 // The name we're declaring, if any. 3307 DeclarationName Name; 3308 if (D.getIdentifier()) 3309 Name = D.getIdentifier(); 3310 3311 // Does this declaration declare a typedef-name? 3312 bool IsTypedefName = 3313 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 3314 D.getContext() == Declarator::AliasDeclContext || 3315 D.getContext() == Declarator::AliasTemplateContext; 3316 3317 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 3318 bool IsQualifiedFunction = T->isFunctionProtoType() && 3319 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 || 3320 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 3321 3322 // If T is 'decltype(auto)', the only declarators we can have are parens 3323 // and at most one function declarator if this is a function declaration. 3324 if (const AutoType *AT = T->getAs<AutoType>()) { 3325 if (AT->isDecltypeAuto()) { 3326 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3327 unsigned Index = E - I - 1; 3328 DeclaratorChunk &DeclChunk = D.getTypeObject(Index); 3329 unsigned DiagId = diag::err_decltype_auto_compound_type; 3330 unsigned DiagKind = 0; 3331 switch (DeclChunk.Kind) { 3332 case DeclaratorChunk::Paren: 3333 continue; 3334 case DeclaratorChunk::Function: { 3335 unsigned FnIndex; 3336 if (D.isFunctionDeclarationContext() && 3337 D.isFunctionDeclarator(FnIndex) && FnIndex == Index) 3338 continue; 3339 DiagId = diag::err_decltype_auto_function_declarator_not_declaration; 3340 break; 3341 } 3342 case DeclaratorChunk::Pointer: 3343 case DeclaratorChunk::BlockPointer: 3344 case DeclaratorChunk::MemberPointer: 3345 DiagKind = 0; 3346 break; 3347 case DeclaratorChunk::Reference: 3348 DiagKind = 1; 3349 break; 3350 case DeclaratorChunk::Array: 3351 DiagKind = 2; 3352 break; 3353 case DeclaratorChunk::Pipe: 3354 break; 3355 } 3356 3357 S.Diag(DeclChunk.Loc, DiagId) << DiagKind; 3358 D.setInvalidType(true); 3359 break; 3360 } 3361 } 3362 } 3363 3364 // Determine whether we should infer _Nonnull on pointer types. 3365 Optional<NullabilityKind> inferNullability; 3366 bool inferNullabilityCS = false; 3367 bool inferNullabilityInnerOnly = false; 3368 bool inferNullabilityInnerOnlyComplete = false; 3369 3370 // Are we in an assume-nonnull region? 3371 bool inAssumeNonNullRegion = false; 3372 if (S.PP.getPragmaAssumeNonNullLoc().isValid()) { 3373 inAssumeNonNullRegion = true; 3374 // Determine which file we saw the assume-nonnull region in. 3375 FileID file = getNullabilityCompletenessCheckFileID( 3376 S, S.PP.getPragmaAssumeNonNullLoc()); 3377 if (file.isValid()) { 3378 FileNullability &fileNullability = S.NullabilityMap[file]; 3379 3380 // If we haven't seen any type nullability before, now we have. 3381 if (!fileNullability.SawTypeNullability) { 3382 if (fileNullability.PointerLoc.isValid()) { 3383 S.Diag(fileNullability.PointerLoc, diag::warn_nullability_missing) 3384 << static_cast<unsigned>(fileNullability.PointerKind); 3385 } 3386 3387 fileNullability.SawTypeNullability = true; 3388 } 3389 } 3390 } 3391 3392 // Whether to complain about missing nullability specifiers or not. 3393 enum { 3394 /// Never complain. 3395 CAMN_No, 3396 /// Complain on the inner pointers (but not the outermost 3397 /// pointer). 3398 CAMN_InnerPointers, 3399 /// Complain about any pointers that don't have nullability 3400 /// specified or inferred. 3401 CAMN_Yes 3402 } complainAboutMissingNullability = CAMN_No; 3403 unsigned NumPointersRemaining = 0; 3404 3405 if (IsTypedefName) { 3406 // For typedefs, we do not infer any nullability (the default), 3407 // and we only complain about missing nullability specifiers on 3408 // inner pointers. 3409 complainAboutMissingNullability = CAMN_InnerPointers; 3410 3411 if (T->canHaveNullability() && !T->getNullability(S.Context)) { 3412 ++NumPointersRemaining; 3413 } 3414 3415 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { 3416 DeclaratorChunk &chunk = D.getTypeObject(i); 3417 switch (chunk.Kind) { 3418 case DeclaratorChunk::Array: 3419 case DeclaratorChunk::Function: 3420 case DeclaratorChunk::Pipe: 3421 break; 3422 3423 case DeclaratorChunk::BlockPointer: 3424 case DeclaratorChunk::MemberPointer: 3425 ++NumPointersRemaining; 3426 break; 3427 3428 case DeclaratorChunk::Paren: 3429 case DeclaratorChunk::Reference: 3430 continue; 3431 3432 case DeclaratorChunk::Pointer: 3433 ++NumPointersRemaining; 3434 continue; 3435 } 3436 } 3437 } else { 3438 bool isFunctionOrMethod = false; 3439 switch (auto context = state.getDeclarator().getContext()) { 3440 case Declarator::ObjCParameterContext: 3441 case Declarator::ObjCResultContext: 3442 case Declarator::PrototypeContext: 3443 case Declarator::TrailingReturnContext: 3444 isFunctionOrMethod = true; 3445 // fallthrough 3446 3447 case Declarator::MemberContext: 3448 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { 3449 complainAboutMissingNullability = CAMN_No; 3450 break; 3451 } 3452 3453 // Weak properties are inferred to be nullable. 3454 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) { 3455 inferNullability = NullabilityKind::Nullable; 3456 break; 3457 } 3458 3459 // fallthrough 3460 3461 case Declarator::FileContext: 3462 case Declarator::KNRTypeListContext: 3463 complainAboutMissingNullability = CAMN_Yes; 3464 3465 // Nullability inference depends on the type and declarator. 3466 switch (classifyPointerDeclarator(S, T, D)) { 3467 case PointerDeclaratorKind::NonPointer: 3468 case PointerDeclaratorKind::MultiLevelPointer: 3469 // Cannot infer nullability. 3470 break; 3471 3472 case PointerDeclaratorKind::SingleLevelPointer: 3473 // Infer _Nonnull if we are in an assumes-nonnull region. 3474 if (inAssumeNonNullRegion) { 3475 inferNullability = NullabilityKind::NonNull; 3476 inferNullabilityCS = (context == Declarator::ObjCParameterContext || 3477 context == Declarator::ObjCResultContext); 3478 } 3479 break; 3480 3481 case PointerDeclaratorKind::CFErrorRefPointer: 3482 case PointerDeclaratorKind::NSErrorPointerPointer: 3483 // Within a function or method signature, infer _Nullable at both 3484 // levels. 3485 if (isFunctionOrMethod && inAssumeNonNullRegion) 3486 inferNullability = NullabilityKind::Nullable; 3487 break; 3488 3489 case PointerDeclaratorKind::MaybePointerToCFRef: 3490 if (isFunctionOrMethod) { 3491 // On pointer-to-pointer parameters marked cf_returns_retained or 3492 // cf_returns_not_retained, if the outer pointer is explicit then 3493 // infer the inner pointer as _Nullable. 3494 auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool { 3495 while (NextAttr) { 3496 if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained || 3497 NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained) 3498 return true; 3499 NextAttr = NextAttr->getNext(); 3500 } 3501 return false; 3502 }; 3503 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { 3504 if (hasCFReturnsAttr(D.getAttributes()) || 3505 hasCFReturnsAttr(InnermostChunk->getAttrs()) || 3506 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) { 3507 inferNullability = NullabilityKind::Nullable; 3508 inferNullabilityInnerOnly = true; 3509 } 3510 } 3511 } 3512 break; 3513 } 3514 break; 3515 3516 case Declarator::ConversionIdContext: 3517 complainAboutMissingNullability = CAMN_Yes; 3518 break; 3519 3520 case Declarator::AliasDeclContext: 3521 case Declarator::AliasTemplateContext: 3522 case Declarator::BlockContext: 3523 case Declarator::BlockLiteralContext: 3524 case Declarator::ConditionContext: 3525 case Declarator::CXXCatchContext: 3526 case Declarator::CXXNewContext: 3527 case Declarator::ForContext: 3528 case Declarator::LambdaExprContext: 3529 case Declarator::LambdaExprParameterContext: 3530 case Declarator::ObjCCatchContext: 3531 case Declarator::TemplateParamContext: 3532 case Declarator::TemplateTypeArgContext: 3533 case Declarator::TypeNameContext: 3534 // Don't infer in these contexts. 3535 break; 3536 } 3537 } 3538 3539 // Local function that checks the nullability for a given pointer declarator. 3540 // Returns true if _Nonnull was inferred. 3541 auto inferPointerNullability = [&](SimplePointerKind pointerKind, 3542 SourceLocation pointerLoc, 3543 AttributeList *&attrs) -> AttributeList * { 3544 // We've seen a pointer. 3545 if (NumPointersRemaining > 0) 3546 --NumPointersRemaining; 3547 3548 // If a nullability attribute is present, there's nothing to do. 3549 if (hasNullabilityAttr(attrs)) 3550 return nullptr; 3551 3552 // If we're supposed to infer nullability, do so now. 3553 if (inferNullability && !inferNullabilityInnerOnlyComplete) { 3554 AttributeList::Syntax syntax 3555 = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword 3556 : AttributeList::AS_Keyword; 3557 AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool() 3558 .create( 3559 S.getNullabilityKeyword( 3560 *inferNullability), 3561 SourceRange(pointerLoc), 3562 nullptr, SourceLocation(), 3563 nullptr, 0, syntax); 3564 3565 spliceAttrIntoList(*nullabilityAttr, attrs); 3566 3567 if (inferNullabilityCS) { 3568 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() 3569 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); 3570 } 3571 3572 if (inferNullabilityInnerOnly) 3573 inferNullabilityInnerOnlyComplete = true; 3574 return nullabilityAttr; 3575 } 3576 3577 // If we're supposed to complain about missing nullability, do so 3578 // now if it's truly missing. 3579 switch (complainAboutMissingNullability) { 3580 case CAMN_No: 3581 break; 3582 3583 case CAMN_InnerPointers: 3584 if (NumPointersRemaining == 0) 3585 break; 3586 // Fallthrough. 3587 3588 case CAMN_Yes: 3589 checkNullabilityConsistency(state, pointerKind, pointerLoc); 3590 } 3591 return nullptr; 3592 }; 3593 3594 // If the type itself could have nullability but does not, infer pointer 3595 // nullability and perform consistency checking. 3596 if (T->canHaveNullability() && S.ActiveTemplateInstantiations.empty() && 3597 !T->getNullability(S.Context)) { 3598 SimplePointerKind pointerKind = SimplePointerKind::Pointer; 3599 if (T->isBlockPointerType()) 3600 pointerKind = SimplePointerKind::BlockPointer; 3601 else if (T->isMemberPointerType()) 3602 pointerKind = SimplePointerKind::MemberPointer; 3603 3604 if (auto *attr = inferPointerNullability( 3605 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), 3606 D.getMutableDeclSpec().getAttributes().getListRef())) { 3607 T = Context.getAttributedType( 3608 AttributedType::getNullabilityAttrKind(*inferNullability), T, T); 3609 attr->setUsedAsTypeAttr(); 3610 } 3611 } 3612 3613 // Walk the DeclTypeInfo, building the recursive type as we go. 3614 // DeclTypeInfos are ordered from the identifier out, which is 3615 // opposite of what we want :). 3616 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3617 unsigned chunkIndex = e - i - 1; 3618 state.setCurrentChunkIndex(chunkIndex); 3619 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 3620 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; 3621 switch (DeclType.Kind) { 3622 case DeclaratorChunk::Paren: 3623 T = S.BuildParenType(T); 3624 break; 3625 case DeclaratorChunk::BlockPointer: 3626 // If blocks are disabled, emit an error. 3627 if (!LangOpts.Blocks) 3628 S.Diag(DeclType.Loc, diag::err_blocks_disable); 3629 3630 // Handle pointer nullability. 3631 inferPointerNullability(SimplePointerKind::BlockPointer, 3632 DeclType.Loc, DeclType.getAttrListRef()); 3633 3634 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 3635 if (DeclType.Cls.TypeQuals) 3636 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 3637 break; 3638 case DeclaratorChunk::Pointer: 3639 // Verify that we're not building a pointer to pointer to function with 3640 // exception specification. 3641 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 3642 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 3643 D.setInvalidType(true); 3644 // Build the type anyway. 3645 } 3646 3647 // Handle pointer nullability 3648 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, 3649 DeclType.getAttrListRef()); 3650 3651 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) { 3652 T = Context.getObjCObjectPointerType(T); 3653 if (DeclType.Ptr.TypeQuals) 3654 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 3655 break; 3656 } 3657 T = S.BuildPointerType(T, DeclType.Loc, Name); 3658 if (DeclType.Ptr.TypeQuals) 3659 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 3660 break; 3661 case DeclaratorChunk::Reference: { 3662 // Verify that we're not building a reference to pointer to function with 3663 // exception specification. 3664 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 3665 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 3666 D.setInvalidType(true); 3667 // Build the type anyway. 3668 } 3669 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 3670 3671 if (DeclType.Ref.HasRestrict) 3672 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 3673 break; 3674 } 3675 case DeclaratorChunk::Array: { 3676 // Verify that we're not building an array of pointers to function with 3677 // exception specification. 3678 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 3679 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 3680 D.setInvalidType(true); 3681 // Build the type anyway. 3682 } 3683 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 3684 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 3685 ArrayType::ArraySizeModifier ASM; 3686 if (ATI.isStar) 3687 ASM = ArrayType::Star; 3688 else if (ATI.hasStatic) 3689 ASM = ArrayType::Static; 3690 else 3691 ASM = ArrayType::Normal; 3692 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 3693 // FIXME: This check isn't quite right: it allows star in prototypes 3694 // for function definitions, and disallows some edge cases detailed 3695 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 3696 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 3697 ASM = ArrayType::Normal; 3698 D.setInvalidType(true); 3699 } 3700 3701 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static 3702 // shall appear only in a declaration of a function parameter with an 3703 // array type, ... 3704 if (ASM == ArrayType::Static || ATI.TypeQuals) { 3705 if (!(D.isPrototypeContext() || 3706 D.getContext() == Declarator::KNRTypeListContext)) { 3707 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << 3708 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 3709 // Remove the 'static' and the type qualifiers. 3710 if (ASM == ArrayType::Static) 3711 ASM = ArrayType::Normal; 3712 ATI.TypeQuals = 0; 3713 D.setInvalidType(true); 3714 } 3715 3716 // C99 6.7.5.2p1: ... and then only in the outermost array type 3717 // derivation. 3718 unsigned x = chunkIndex; 3719 while (x != 0) { 3720 // Walk outwards along the declarator chunks. 3721 x--; 3722 const DeclaratorChunk &DC = D.getTypeObject(x); 3723 switch (DC.Kind) { 3724 case DeclaratorChunk::Paren: 3725 continue; 3726 case DeclaratorChunk::Array: 3727 case DeclaratorChunk::Pointer: 3728 case DeclaratorChunk::Reference: 3729 case DeclaratorChunk::MemberPointer: 3730 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << 3731 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 3732 if (ASM == ArrayType::Static) 3733 ASM = ArrayType::Normal; 3734 ATI.TypeQuals = 0; 3735 D.setInvalidType(true); 3736 break; 3737 case DeclaratorChunk::Function: 3738 case DeclaratorChunk::BlockPointer: 3739 case DeclaratorChunk::Pipe: 3740 // These are invalid anyway, so just ignore. 3741 break; 3742 } 3743 } 3744 } 3745 const AutoType *AT = T->getContainedAutoType(); 3746 // Allow arrays of auto if we are a generic lambda parameter. 3747 // i.e. [](auto (&array)[5]) { return array[0]; }; OK 3748 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) { 3749 // We've already diagnosed this for decltype(auto). 3750 if (!AT->isDecltypeAuto()) 3751 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) 3752 << getPrintableNameForEntity(Name) << T; 3753 T = QualType(); 3754 break; 3755 } 3756 3757 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 3758 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 3759 break; 3760 } 3761 case DeclaratorChunk::Function: { 3762 // If the function declarator has a prototype (i.e. it is not () and 3763 // does not have a K&R-style identifier list), then the arguments are part 3764 // of the type, otherwise the argument list is (). 3765 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 3766 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier(); 3767 3768 // Check for auto functions and trailing return type and adjust the 3769 // return type accordingly. 3770 if (!D.isInvalidType()) { 3771 // trailing-return-type is only required if we're declaring a function, 3772 // and not, for instance, a pointer to a function. 3773 if (D.getDeclSpec().containsPlaceholderType() && 3774 !FTI.hasTrailingReturnType() && chunkIndex == 0 && 3775 !S.getLangOpts().CPlusPlus14) { 3776 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 3777 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto 3778 ? diag::err_auto_missing_trailing_return 3779 : diag::err_deduced_return_type); 3780 T = Context.IntTy; 3781 D.setInvalidType(true); 3782 } else if (FTI.hasTrailingReturnType()) { 3783 // T must be exactly 'auto' at this point. See CWG issue 681. 3784 if (isa<ParenType>(T)) { 3785 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 3786 diag::err_trailing_return_in_parens) 3787 << T << D.getDeclSpec().getSourceRange(); 3788 D.setInvalidType(true); 3789 } else if (D.getContext() != Declarator::LambdaExprContext && 3790 (T.hasQualifiers() || !isa<AutoType>(T) || 3791 cast<AutoType>(T)->getKeyword() != AutoTypeKeyword::Auto)) { 3792 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 3793 diag::err_trailing_return_without_auto) 3794 << T << D.getDeclSpec().getSourceRange(); 3795 D.setInvalidType(true); 3796 } 3797 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); 3798 if (T.isNull()) { 3799 // An error occurred parsing the trailing return type. 3800 T = Context.IntTy; 3801 D.setInvalidType(true); 3802 } 3803 } 3804 } 3805 3806 // C99 6.7.5.3p1: The return type may not be a function or array type. 3807 // For conversion functions, we'll diagnose this particular error later. 3808 if ((T->isArrayType() || T->isFunctionType()) && 3809 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 3810 unsigned diagID = diag::err_func_returning_array_function; 3811 // Last processing chunk in block context means this function chunk 3812 // represents the block. 3813 if (chunkIndex == 0 && 3814 D.getContext() == Declarator::BlockLiteralContext) 3815 diagID = diag::err_block_returning_array_function; 3816 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 3817 T = Context.IntTy; 3818 D.setInvalidType(true); 3819 } 3820 3821 // Do not allow returning half FP value. 3822 // FIXME: This really should be in BuildFunctionType. 3823 if (T->isHalfType()) { 3824 if (S.getLangOpts().OpenCL) { 3825 if (!S.getOpenCLOptions().cl_khr_fp16) { 3826 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T; 3827 D.setInvalidType(true); 3828 } 3829 } else if (!S.getLangOpts().HalfArgsAndReturns) { 3830 S.Diag(D.getIdentifierLoc(), 3831 diag::err_parameters_retval_cannot_have_fp16_type) << 1; 3832 D.setInvalidType(true); 3833 } 3834 } 3835 3836 // Methods cannot return interface types. All ObjC objects are 3837 // passed by reference. 3838 if (T->isObjCObjectType()) { 3839 SourceLocation DiagLoc, FixitLoc; 3840 if (TInfo) { 3841 DiagLoc = TInfo->getTypeLoc().getLocStart(); 3842 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd()); 3843 } else { 3844 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 3845 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd()); 3846 } 3847 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) 3848 << 0 << T 3849 << FixItHint::CreateInsertion(FixitLoc, "*"); 3850 3851 T = Context.getObjCObjectPointerType(T); 3852 if (TInfo) { 3853 TypeLocBuilder TLB; 3854 TLB.pushFullCopy(TInfo->getTypeLoc()); 3855 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); 3856 TLoc.setStarLoc(FixitLoc); 3857 TInfo = TLB.getTypeSourceInfo(Context, T); 3858 } 3859 3860 D.setInvalidType(true); 3861 } 3862 3863 // cv-qualifiers on return types are pointless except when the type is a 3864 // class type in C++. 3865 if ((T.getCVRQualifiers() || T->isAtomicType()) && 3866 !(S.getLangOpts().CPlusPlus && 3867 (T->isDependentType() || T->isRecordType()))) { 3868 if (T->isVoidType() && !S.getLangOpts().CPlusPlus && 3869 D.getFunctionDefinitionKind() == FDK_Definition) { 3870 // [6.9.1/3] qualified void return is invalid on a C 3871 // function definition. Apparently ok on declarations and 3872 // in C++ though (!) 3873 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; 3874 } else 3875 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); 3876 } 3877 3878 // Objective-C ARC ownership qualifiers are ignored on the function 3879 // return type (by type canonicalization). Complain if this attribute 3880 // was written here. 3881 if (T.getQualifiers().hasObjCLifetime()) { 3882 SourceLocation AttrLoc; 3883 if (chunkIndex + 1 < D.getNumTypeObjects()) { 3884 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 3885 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs(); 3886 Attr; Attr = Attr->getNext()) { 3887 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 3888 AttrLoc = Attr->getLoc(); 3889 break; 3890 } 3891 } 3892 } 3893 if (AttrLoc.isInvalid()) { 3894 for (const AttributeList *Attr 3895 = D.getDeclSpec().getAttributes().getList(); 3896 Attr; Attr = Attr->getNext()) { 3897 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 3898 AttrLoc = Attr->getLoc(); 3899 break; 3900 } 3901 } 3902 } 3903 3904 if (AttrLoc.isValid()) { 3905 // The ownership attributes are almost always written via 3906 // the predefined 3907 // __strong/__weak/__autoreleasing/__unsafe_unretained. 3908 if (AttrLoc.isMacroID()) 3909 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first; 3910 3911 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 3912 << T.getQualifiers().getObjCLifetime(); 3913 } 3914 } 3915 3916 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { 3917 // C++ [dcl.fct]p6: 3918 // Types shall not be defined in return or parameter types. 3919 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 3920 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 3921 << Context.getTypeDeclType(Tag); 3922 } 3923 3924 // Exception specs are not allowed in typedefs. Complain, but add it 3925 // anyway. 3926 if (IsTypedefName && FTI.getExceptionSpecType()) 3927 S.Diag(FTI.getExceptionSpecLocBeg(), 3928 diag::err_exception_spec_in_typedef) 3929 << (D.getContext() == Declarator::AliasDeclContext || 3930 D.getContext() == Declarator::AliasTemplateContext); 3931 3932 // If we see "T var();" or "T var(T());" at block scope, it is probably 3933 // an attempt to initialize a variable, not a function declaration. 3934 if (FTI.isAmbiguous) 3935 warnAboutAmbiguousFunction(S, D, DeclType, T); 3936 3937 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex)); 3938 3939 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) { 3940 // Simple void foo(), where the incoming T is the result type. 3941 T = Context.getFunctionNoProtoType(T, EI); 3942 } else { 3943 // We allow a zero-parameter variadic function in C if the 3944 // function is marked with the "overloadable" attribute. Scan 3945 // for this attribute now. 3946 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) { 3947 bool Overloadable = false; 3948 for (const AttributeList *Attrs = D.getAttributes(); 3949 Attrs; Attrs = Attrs->getNext()) { 3950 if (Attrs->getKind() == AttributeList::AT_Overloadable) { 3951 Overloadable = true; 3952 break; 3953 } 3954 } 3955 3956 if (!Overloadable) 3957 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); 3958 } 3959 3960 if (FTI.NumParams && FTI.Params[0].Param == nullptr) { 3961 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 3962 // definition. 3963 S.Diag(FTI.Params[0].IdentLoc, 3964 diag::err_ident_list_in_fn_declaration); 3965 D.setInvalidType(true); 3966 // Recover by creating a K&R-style function type. 3967 T = Context.getFunctionNoProtoType(T, EI); 3968 break; 3969 } 3970 3971 FunctionProtoType::ExtProtoInfo EPI; 3972 EPI.ExtInfo = EI; 3973 EPI.Variadic = FTI.isVariadic; 3974 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 3975 EPI.TypeQuals = FTI.TypeQuals; 3976 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 3977 : FTI.RefQualifierIsLValueRef? RQ_LValue 3978 : RQ_RValue; 3979 3980 // Otherwise, we have a function with a parameter list that is 3981 // potentially variadic. 3982 SmallVector<QualType, 16> ParamTys; 3983 ParamTys.reserve(FTI.NumParams); 3984 3985 SmallVector<bool, 16> ConsumedParameters; 3986 ConsumedParameters.reserve(FTI.NumParams); 3987 bool HasAnyConsumedParameters = false; 3988 3989 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 3990 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 3991 QualType ParamTy = Param->getType(); 3992 assert(!ParamTy.isNull() && "Couldn't parse type?"); 3993 3994 // Look for 'void'. void is allowed only as a single parameter to a 3995 // function with no other parameters (C99 6.7.5.3p10). We record 3996 // int(void) as a FunctionProtoType with an empty parameter list. 3997 if (ParamTy->isVoidType()) { 3998 // If this is something like 'float(int, void)', reject it. 'void' 3999 // is an incomplete type (C99 6.2.5p19) and function decls cannot 4000 // have parameters of incomplete type. 4001 if (FTI.NumParams != 1 || FTI.isVariadic) { 4002 S.Diag(DeclType.Loc, diag::err_void_only_param); 4003 ParamTy = Context.IntTy; 4004 Param->setType(ParamTy); 4005 } else if (FTI.Params[i].Ident) { 4006 // Reject, but continue to parse 'int(void abc)'. 4007 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); 4008 ParamTy = Context.IntTy; 4009 Param->setType(ParamTy); 4010 } else { 4011 // Reject, but continue to parse 'float(const void)'. 4012 if (ParamTy.hasQualifiers()) 4013 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 4014 4015 // Do not add 'void' to the list. 4016 break; 4017 } 4018 } else if (ParamTy->isHalfType()) { 4019 // Disallow half FP parameters. 4020 // FIXME: This really should be in BuildFunctionType. 4021 if (S.getLangOpts().OpenCL) { 4022 if (!S.getOpenCLOptions().cl_khr_fp16) { 4023 S.Diag(Param->getLocation(), 4024 diag::err_opencl_half_param) << ParamTy; 4025 D.setInvalidType(); 4026 Param->setInvalidDecl(); 4027 } 4028 } else if (!S.getLangOpts().HalfArgsAndReturns) { 4029 S.Diag(Param->getLocation(), 4030 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 4031 D.setInvalidType(); 4032 } 4033 } else if (!FTI.hasPrototype) { 4034 if (ParamTy->isPromotableIntegerType()) { 4035 ParamTy = Context.getPromotedIntegerType(ParamTy); 4036 Param->setKNRPromoted(true); 4037 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { 4038 if (BTy->getKind() == BuiltinType::Float) { 4039 ParamTy = Context.DoubleTy; 4040 Param->setKNRPromoted(true); 4041 } 4042 } 4043 } 4044 4045 if (LangOpts.ObjCAutoRefCount) { 4046 bool Consumed = Param->hasAttr<NSConsumedAttr>(); 4047 ConsumedParameters.push_back(Consumed); 4048 HasAnyConsumedParameters |= Consumed; 4049 } 4050 4051 ParamTys.push_back(ParamTy); 4052 } 4053 4054 if (HasAnyConsumedParameters) 4055 EPI.ConsumedParameters = ConsumedParameters.data(); 4056 4057 SmallVector<QualType, 4> Exceptions; 4058 SmallVector<ParsedType, 2> DynamicExceptions; 4059 SmallVector<SourceRange, 2> DynamicExceptionRanges; 4060 Expr *NoexceptExpr = nullptr; 4061 4062 if (FTI.getExceptionSpecType() == EST_Dynamic) { 4063 // FIXME: It's rather inefficient to have to split into two vectors 4064 // here. 4065 unsigned N = FTI.NumExceptions; 4066 DynamicExceptions.reserve(N); 4067 DynamicExceptionRanges.reserve(N); 4068 for (unsigned I = 0; I != N; ++I) { 4069 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 4070 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 4071 } 4072 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 4073 NoexceptExpr = FTI.NoexceptExpr; 4074 } 4075 4076 S.checkExceptionSpecification(D.isFunctionDeclarationContext(), 4077 FTI.getExceptionSpecType(), 4078 DynamicExceptions, 4079 DynamicExceptionRanges, 4080 NoexceptExpr, 4081 Exceptions, 4082 EPI.ExceptionSpec); 4083 4084 T = Context.getFunctionType(T, ParamTys, EPI); 4085 } 4086 break; 4087 } 4088 case DeclaratorChunk::MemberPointer: { 4089 // The scope spec must refer to a class, or be dependent. 4090 CXXScopeSpec &SS = DeclType.Mem.Scope(); 4091 QualType ClsType; 4092 4093 // Handle pointer nullability. 4094 inferPointerNullability(SimplePointerKind::MemberPointer, 4095 DeclType.Loc, DeclType.getAttrListRef()); 4096 4097 if (SS.isInvalid()) { 4098 // Avoid emitting extra errors if we already errored on the scope. 4099 D.setInvalidType(true); 4100 } else if (S.isDependentScopeSpecifier(SS) || 4101 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 4102 NestedNameSpecifier *NNS = SS.getScopeRep(); 4103 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 4104 switch (NNS->getKind()) { 4105 case NestedNameSpecifier::Identifier: 4106 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 4107 NNS->getAsIdentifier()); 4108 break; 4109 4110 case NestedNameSpecifier::Namespace: 4111 case NestedNameSpecifier::NamespaceAlias: 4112 case NestedNameSpecifier::Global: 4113 case NestedNameSpecifier::Super: 4114 llvm_unreachable("Nested-name-specifier must name a type"); 4115 4116 case NestedNameSpecifier::TypeSpec: 4117 case NestedNameSpecifier::TypeSpecWithTemplate: 4118 ClsType = QualType(NNS->getAsType(), 0); 4119 // Note: if the NNS has a prefix and ClsType is a nondependent 4120 // TemplateSpecializationType, then the NNS prefix is NOT included 4121 // in ClsType; hence we wrap ClsType into an ElaboratedType. 4122 // NOTE: in particular, no wrap occurs if ClsType already is an 4123 // Elaborated, DependentName, or DependentTemplateSpecialization. 4124 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 4125 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 4126 break; 4127 } 4128 } else { 4129 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 4130 diag::err_illegal_decl_mempointer_in_nonclass) 4131 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 4132 << DeclType.Mem.Scope().getRange(); 4133 D.setInvalidType(true); 4134 } 4135 4136 if (!ClsType.isNull()) 4137 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, 4138 D.getIdentifier()); 4139 if (T.isNull()) { 4140 T = Context.IntTy; 4141 D.setInvalidType(true); 4142 } else if (DeclType.Mem.TypeQuals) { 4143 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 4144 } 4145 break; 4146 } 4147 4148 case DeclaratorChunk::Pipe: { 4149 T = S.BuildPipeType(T, DeclType.Loc ); 4150 break; 4151 } 4152 } 4153 4154 if (T.isNull()) { 4155 D.setInvalidType(true); 4156 T = Context.IntTy; 4157 } 4158 4159 // See if there are any attributes on this declarator chunk. 4160 processTypeAttrs(state, T, TAL_DeclChunk, 4161 const_cast<AttributeList *>(DeclType.getAttrs())); 4162 } 4163 4164 assert(!T.isNull() && "T must not be null after this point"); 4165 4166 if (LangOpts.CPlusPlus && T->isFunctionType()) { 4167 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 4168 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 4169 4170 // C++ 8.3.5p4: 4171 // A cv-qualifier-seq shall only be part of the function type 4172 // for a nonstatic member function, the function type to which a pointer 4173 // to member refers, or the top-level function type of a function typedef 4174 // declaration. 4175 // 4176 // Core issue 547 also allows cv-qualifiers on function types that are 4177 // top-level template type arguments. 4178 bool FreeFunction; 4179 if (!D.getCXXScopeSpec().isSet()) { 4180 FreeFunction = ((D.getContext() != Declarator::MemberContext && 4181 D.getContext() != Declarator::LambdaExprContext) || 4182 D.getDeclSpec().isFriendSpecified()); 4183 } else { 4184 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 4185 FreeFunction = (DC && !DC->isRecord()); 4186 } 4187 4188 // C++11 [dcl.fct]p6 (w/DR1417): 4189 // An attempt to specify a function type with a cv-qualifier-seq or a 4190 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 4191 // - the function type for a non-static member function, 4192 // - the function type to which a pointer to member refers, 4193 // - the top-level function type of a function typedef declaration or 4194 // alias-declaration, 4195 // - the type-id in the default argument of a type-parameter, or 4196 // - the type-id of a template-argument for a type-parameter 4197 // 4198 // FIXME: Checking this here is insufficient. We accept-invalid on: 4199 // 4200 // template<typename T> struct S { void f(T); }; 4201 // S<int() const> s; 4202 // 4203 // ... for instance. 4204 if (IsQualifiedFunction && 4205 !(!FreeFunction && 4206 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 4207 !IsTypedefName && 4208 D.getContext() != Declarator::TemplateTypeArgContext) { 4209 SourceLocation Loc = D.getLocStart(); 4210 SourceRange RemovalRange; 4211 unsigned I; 4212 if (D.isFunctionDeclarator(I)) { 4213 SmallVector<SourceLocation, 4> RemovalLocs; 4214 const DeclaratorChunk &Chunk = D.getTypeObject(I); 4215 assert(Chunk.Kind == DeclaratorChunk::Function); 4216 if (Chunk.Fun.hasRefQualifier()) 4217 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 4218 if (Chunk.Fun.TypeQuals & Qualifiers::Const) 4219 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); 4220 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) 4221 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); 4222 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) 4223 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); 4224 if (!RemovalLocs.empty()) { 4225 std::sort(RemovalLocs.begin(), RemovalLocs.end(), 4226 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 4227 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 4228 Loc = RemovalLocs.front(); 4229 } 4230 } 4231 4232 S.Diag(Loc, diag::err_invalid_qualified_function_type) 4233 << FreeFunction << D.isFunctionDeclarator() << T 4234 << getFunctionQualifiersAsString(FnTy) 4235 << FixItHint::CreateRemoval(RemovalRange); 4236 4237 // Strip the cv-qualifiers and ref-qualifiers from the type. 4238 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 4239 EPI.TypeQuals = 0; 4240 EPI.RefQualifier = RQ_None; 4241 4242 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), 4243 EPI); 4244 // Rebuild any parens around the identifier in the function type. 4245 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4246 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 4247 break; 4248 T = S.BuildParenType(T); 4249 } 4250 } 4251 } 4252 4253 // Apply any undistributed attributes from the declarator. 4254 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); 4255 4256 // Diagnose any ignored type attributes. 4257 state.diagnoseIgnoredTypeAttrs(T); 4258 4259 // C++0x [dcl.constexpr]p9: 4260 // A constexpr specifier used in an object declaration declares the object 4261 // as const. 4262 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 4263 T.addConst(); 4264 } 4265 4266 // If there was an ellipsis in the declarator, the declaration declares a 4267 // parameter pack whose type may be a pack expansion type. 4268 if (D.hasEllipsis()) { 4269 // C++0x [dcl.fct]p13: 4270 // A declarator-id or abstract-declarator containing an ellipsis shall 4271 // only be used in a parameter-declaration. Such a parameter-declaration 4272 // is a parameter pack (14.5.3). [...] 4273 switch (D.getContext()) { 4274 case Declarator::PrototypeContext: 4275 case Declarator::LambdaExprParameterContext: 4276 // C++0x [dcl.fct]p13: 4277 // [...] When it is part of a parameter-declaration-clause, the 4278 // parameter pack is a function parameter pack (14.5.3). The type T 4279 // of the declarator-id of the function parameter pack shall contain 4280 // a template parameter pack; each template parameter pack in T is 4281 // expanded by the function parameter pack. 4282 // 4283 // We represent function parameter packs as function parameters whose 4284 // type is a pack expansion. 4285 if (!T->containsUnexpandedParameterPack()) { 4286 S.Diag(D.getEllipsisLoc(), 4287 diag::err_function_parameter_pack_without_parameter_packs) 4288 << T << D.getSourceRange(); 4289 D.setEllipsisLoc(SourceLocation()); 4290 } else { 4291 T = Context.getPackExpansionType(T, None); 4292 } 4293 break; 4294 case Declarator::TemplateParamContext: 4295 // C++0x [temp.param]p15: 4296 // If a template-parameter is a [...] is a parameter-declaration that 4297 // declares a parameter pack (8.3.5), then the template-parameter is a 4298 // template parameter pack (14.5.3). 4299 // 4300 // Note: core issue 778 clarifies that, if there are any unexpanded 4301 // parameter packs in the type of the non-type template parameter, then 4302 // it expands those parameter packs. 4303 if (T->containsUnexpandedParameterPack()) 4304 T = Context.getPackExpansionType(T, None); 4305 else 4306 S.Diag(D.getEllipsisLoc(), 4307 LangOpts.CPlusPlus11 4308 ? diag::warn_cxx98_compat_variadic_templates 4309 : diag::ext_variadic_templates); 4310 break; 4311 4312 case Declarator::FileContext: 4313 case Declarator::KNRTypeListContext: 4314 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here? 4315 case Declarator::ObjCResultContext: // FIXME: special diagnostic here? 4316 case Declarator::TypeNameContext: 4317 case Declarator::CXXNewContext: 4318 case Declarator::AliasDeclContext: 4319 case Declarator::AliasTemplateContext: 4320 case Declarator::MemberContext: 4321 case Declarator::BlockContext: 4322 case Declarator::ForContext: 4323 case Declarator::ConditionContext: 4324 case Declarator::CXXCatchContext: 4325 case Declarator::ObjCCatchContext: 4326 case Declarator::BlockLiteralContext: 4327 case Declarator::LambdaExprContext: 4328 case Declarator::ConversionIdContext: 4329 case Declarator::TrailingReturnContext: 4330 case Declarator::TemplateTypeArgContext: 4331 // FIXME: We may want to allow parameter packs in block-literal contexts 4332 // in the future. 4333 S.Diag(D.getEllipsisLoc(), 4334 diag::err_ellipsis_in_declarator_not_parameter); 4335 D.setEllipsisLoc(SourceLocation()); 4336 break; 4337 } 4338 } 4339 4340 assert(!T.isNull() && "T must not be null at the end of this function"); 4341 if (D.isInvalidType()) 4342 return Context.getTrivialTypeSourceInfo(T); 4343 4344 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 4345 } 4346 4347 /// GetTypeForDeclarator - Convert the type for the specified 4348 /// declarator to Type instances. 4349 /// 4350 /// The result of this call will never be null, but the associated 4351 /// type may be a null type if there's an unrecoverable error. 4352 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 4353 // Determine the type of the declarator. Not all forms of declarator 4354 // have a type. 4355 4356 TypeProcessingState state(*this, D); 4357 4358 TypeSourceInfo *ReturnTypeInfo = nullptr; 4359 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 4360 4361 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 4362 inferARCWriteback(state, T); 4363 4364 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 4365 } 4366 4367 static void transferARCOwnershipToDeclSpec(Sema &S, 4368 QualType &declSpecTy, 4369 Qualifiers::ObjCLifetime ownership) { 4370 if (declSpecTy->isObjCRetainableType() && 4371 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 4372 Qualifiers qs; 4373 qs.addObjCLifetime(ownership); 4374 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 4375 } 4376 } 4377 4378 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 4379 Qualifiers::ObjCLifetime ownership, 4380 unsigned chunkIndex) { 4381 Sema &S = state.getSema(); 4382 Declarator &D = state.getDeclarator(); 4383 4384 // Look for an explicit lifetime attribute. 4385 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 4386 for (const AttributeList *attr = chunk.getAttrs(); attr; 4387 attr = attr->getNext()) 4388 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 4389 return; 4390 4391 const char *attrStr = nullptr; 4392 switch (ownership) { 4393 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 4394 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 4395 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 4396 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 4397 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 4398 } 4399 4400 IdentifierLoc *Arg = new (S.Context) IdentifierLoc; 4401 Arg->Ident = &S.Context.Idents.get(attrStr); 4402 Arg->Loc = SourceLocation(); 4403 4404 ArgsUnion Args(Arg); 4405 4406 // If there wasn't one, add one (with an invalid source location 4407 // so that we don't make an AttributedType for it). 4408 AttributeList *attr = D.getAttributePool() 4409 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 4410 /*scope*/ nullptr, SourceLocation(), 4411 /*args*/ &Args, 1, AttributeList::AS_GNU); 4412 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 4413 4414 // TODO: mark whether we did this inference? 4415 } 4416 4417 /// \brief Used for transferring ownership in casts resulting in l-values. 4418 static void transferARCOwnership(TypeProcessingState &state, 4419 QualType &declSpecTy, 4420 Qualifiers::ObjCLifetime ownership) { 4421 Sema &S = state.getSema(); 4422 Declarator &D = state.getDeclarator(); 4423 4424 int inner = -1; 4425 bool hasIndirection = false; 4426 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4427 DeclaratorChunk &chunk = D.getTypeObject(i); 4428 switch (chunk.Kind) { 4429 case DeclaratorChunk::Paren: 4430 // Ignore parens. 4431 break; 4432 4433 case DeclaratorChunk::Array: 4434 case DeclaratorChunk::Reference: 4435 case DeclaratorChunk::Pointer: 4436 if (inner != -1) 4437 hasIndirection = true; 4438 inner = i; 4439 break; 4440 4441 case DeclaratorChunk::BlockPointer: 4442 if (inner != -1) 4443 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 4444 return; 4445 4446 case DeclaratorChunk::Function: 4447 case DeclaratorChunk::MemberPointer: 4448 case DeclaratorChunk::Pipe: 4449 return; 4450 } 4451 } 4452 4453 if (inner == -1) 4454 return; 4455 4456 DeclaratorChunk &chunk = D.getTypeObject(inner); 4457 if (chunk.Kind == DeclaratorChunk::Pointer) { 4458 if (declSpecTy->isObjCRetainableType()) 4459 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 4460 if (declSpecTy->isObjCObjectType() && hasIndirection) 4461 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 4462 } else { 4463 assert(chunk.Kind == DeclaratorChunk::Array || 4464 chunk.Kind == DeclaratorChunk::Reference); 4465 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 4466 } 4467 } 4468 4469 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 4470 TypeProcessingState state(*this, D); 4471 4472 TypeSourceInfo *ReturnTypeInfo = nullptr; 4473 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 4474 4475 if (getLangOpts().ObjC1) { 4476 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 4477 if (ownership != Qualifiers::OCL_None) 4478 transferARCOwnership(state, declSpecTy, ownership); 4479 } 4480 4481 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 4482 } 4483 4484 /// Map an AttributedType::Kind to an AttributeList::Kind. 4485 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 4486 switch (kind) { 4487 case AttributedType::attr_address_space: 4488 return AttributeList::AT_AddressSpace; 4489 case AttributedType::attr_regparm: 4490 return AttributeList::AT_Regparm; 4491 case AttributedType::attr_vector_size: 4492 return AttributeList::AT_VectorSize; 4493 case AttributedType::attr_neon_vector_type: 4494 return AttributeList::AT_NeonVectorType; 4495 case AttributedType::attr_neon_polyvector_type: 4496 return AttributeList::AT_NeonPolyVectorType; 4497 case AttributedType::attr_objc_gc: 4498 return AttributeList::AT_ObjCGC; 4499 case AttributedType::attr_objc_ownership: 4500 case AttributedType::attr_objc_inert_unsafe_unretained: 4501 return AttributeList::AT_ObjCOwnership; 4502 case AttributedType::attr_noreturn: 4503 return AttributeList::AT_NoReturn; 4504 case AttributedType::attr_cdecl: 4505 return AttributeList::AT_CDecl; 4506 case AttributedType::attr_fastcall: 4507 return AttributeList::AT_FastCall; 4508 case AttributedType::attr_stdcall: 4509 return AttributeList::AT_StdCall; 4510 case AttributedType::attr_thiscall: 4511 return AttributeList::AT_ThisCall; 4512 case AttributedType::attr_pascal: 4513 return AttributeList::AT_Pascal; 4514 case AttributedType::attr_vectorcall: 4515 return AttributeList::AT_VectorCall; 4516 case AttributedType::attr_pcs: 4517 case AttributedType::attr_pcs_vfp: 4518 return AttributeList::AT_Pcs; 4519 case AttributedType::attr_inteloclbicc: 4520 return AttributeList::AT_IntelOclBicc; 4521 case AttributedType::attr_ms_abi: 4522 return AttributeList::AT_MSABI; 4523 case AttributedType::attr_sysv_abi: 4524 return AttributeList::AT_SysVABI; 4525 case AttributedType::attr_ptr32: 4526 return AttributeList::AT_Ptr32; 4527 case AttributedType::attr_ptr64: 4528 return AttributeList::AT_Ptr64; 4529 case AttributedType::attr_sptr: 4530 return AttributeList::AT_SPtr; 4531 case AttributedType::attr_uptr: 4532 return AttributeList::AT_UPtr; 4533 case AttributedType::attr_nonnull: 4534 return AttributeList::AT_TypeNonNull; 4535 case AttributedType::attr_nullable: 4536 return AttributeList::AT_TypeNullable; 4537 case AttributedType::attr_null_unspecified: 4538 return AttributeList::AT_TypeNullUnspecified; 4539 case AttributedType::attr_objc_kindof: 4540 return AttributeList::AT_ObjCKindOf; 4541 } 4542 llvm_unreachable("unexpected attribute kind!"); 4543 } 4544 4545 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 4546 const AttributeList *attrs, 4547 const AttributeList *DeclAttrs = nullptr) { 4548 // DeclAttrs and attrs cannot be both empty. 4549 assert((attrs || DeclAttrs) && 4550 "no type attributes in the expected location!"); 4551 4552 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind()); 4553 // Try to search for an attribute of matching kind in attrs list. 4554 while (attrs && attrs->getKind() != parsedKind) 4555 attrs = attrs->getNext(); 4556 if (!attrs) { 4557 // No matching type attribute in attrs list found. 4558 // Try searching through C++11 attributes in the declarator attribute list. 4559 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() || 4560 DeclAttrs->getKind() != parsedKind)) 4561 DeclAttrs = DeclAttrs->getNext(); 4562 attrs = DeclAttrs; 4563 } 4564 4565 assert(attrs && "no matching type attribute in expected location!"); 4566 4567 TL.setAttrNameLoc(attrs->getLoc()); 4568 if (TL.hasAttrExprOperand()) { 4569 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind"); 4570 TL.setAttrExprOperand(attrs->getArgAsExpr(0)); 4571 } else if (TL.hasAttrEnumOperand()) { 4572 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) && 4573 "unexpected attribute operand kind"); 4574 if (attrs->isArgIdent(0)) 4575 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc); 4576 else 4577 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc()); 4578 } 4579 4580 // FIXME: preserve this information to here. 4581 if (TL.hasAttrOperand()) 4582 TL.setAttrOperandParensRange(SourceRange()); 4583 } 4584 4585 namespace { 4586 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 4587 ASTContext &Context; 4588 const DeclSpec &DS; 4589 4590 public: 4591 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 4592 : Context(Context), DS(DS) {} 4593 4594 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 4595 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 4596 Visit(TL.getModifiedLoc()); 4597 } 4598 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 4599 Visit(TL.getUnqualifiedLoc()); 4600 } 4601 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 4602 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 4603 } 4604 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 4605 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 4606 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 4607 // addition field. What we have is good enough for dispay of location 4608 // of 'fixit' on interface name. 4609 TL.setNameEndLoc(DS.getLocEnd()); 4610 } 4611 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 4612 TypeSourceInfo *RepTInfo = nullptr; 4613 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 4614 TL.copy(RepTInfo->getTypeLoc()); 4615 } 4616 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 4617 TypeSourceInfo *RepTInfo = nullptr; 4618 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 4619 TL.copy(RepTInfo->getTypeLoc()); 4620 } 4621 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 4622 TypeSourceInfo *TInfo = nullptr; 4623 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4624 4625 // If we got no declarator info from previous Sema routines, 4626 // just fill with the typespec loc. 4627 if (!TInfo) { 4628 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 4629 return; 4630 } 4631 4632 TypeLoc OldTL = TInfo->getTypeLoc(); 4633 if (TInfo->getType()->getAs<ElaboratedType>()) { 4634 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 4635 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 4636 .castAs<TemplateSpecializationTypeLoc>(); 4637 TL.copy(NamedTL); 4638 } else { 4639 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 4640 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 4641 } 4642 4643 } 4644 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 4645 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 4646 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 4647 TL.setParensRange(DS.getTypeofParensRange()); 4648 } 4649 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 4650 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 4651 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 4652 TL.setParensRange(DS.getTypeofParensRange()); 4653 assert(DS.getRepAsType()); 4654 TypeSourceInfo *TInfo = nullptr; 4655 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4656 TL.setUnderlyingTInfo(TInfo); 4657 } 4658 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 4659 // FIXME: This holds only because we only have one unary transform. 4660 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 4661 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 4662 TL.setParensRange(DS.getTypeofParensRange()); 4663 assert(DS.getRepAsType()); 4664 TypeSourceInfo *TInfo = nullptr; 4665 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4666 TL.setUnderlyingTInfo(TInfo); 4667 } 4668 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 4669 // By default, use the source location of the type specifier. 4670 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 4671 if (TL.needsExtraLocalData()) { 4672 // Set info for the written builtin specifiers. 4673 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 4674 // Try to have a meaningful source location. 4675 if (TL.getWrittenSignSpec() != TSS_unspecified) 4676 // Sign spec loc overrides the others (e.g., 'unsigned long'). 4677 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 4678 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 4679 // Width spec loc overrides type spec loc (e.g., 'short int'). 4680 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 4681 } 4682 } 4683 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 4684 ElaboratedTypeKeyword Keyword 4685 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 4686 if (DS.getTypeSpecType() == TST_typename) { 4687 TypeSourceInfo *TInfo = nullptr; 4688 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4689 if (TInfo) { 4690 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 4691 return; 4692 } 4693 } 4694 TL.setElaboratedKeywordLoc(Keyword != ETK_None 4695 ? DS.getTypeSpecTypeLoc() 4696 : SourceLocation()); 4697 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 4698 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4699 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 4700 } 4701 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 4702 assert(DS.getTypeSpecType() == TST_typename); 4703 TypeSourceInfo *TInfo = nullptr; 4704 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4705 assert(TInfo); 4706 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 4707 } 4708 void VisitDependentTemplateSpecializationTypeLoc( 4709 DependentTemplateSpecializationTypeLoc TL) { 4710 assert(DS.getTypeSpecType() == TST_typename); 4711 TypeSourceInfo *TInfo = nullptr; 4712 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4713 assert(TInfo); 4714 TL.copy( 4715 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 4716 } 4717 void VisitTagTypeLoc(TagTypeLoc TL) { 4718 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 4719 } 4720 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 4721 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 4722 // or an _Atomic qualifier. 4723 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 4724 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 4725 TL.setParensRange(DS.getTypeofParensRange()); 4726 4727 TypeSourceInfo *TInfo = nullptr; 4728 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4729 assert(TInfo); 4730 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 4731 } else { 4732 TL.setKWLoc(DS.getAtomicSpecLoc()); 4733 // No parens, to indicate this was spelled as an _Atomic qualifier. 4734 TL.setParensRange(SourceRange()); 4735 Visit(TL.getValueLoc()); 4736 } 4737 } 4738 4739 void VisitPipeTypeLoc(PipeTypeLoc TL) { 4740 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 4741 4742 TypeSourceInfo *TInfo = nullptr; 4743 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4744 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 4745 } 4746 4747 void VisitTypeLoc(TypeLoc TL) { 4748 // FIXME: add other typespec types and change this to an assert. 4749 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 4750 } 4751 }; 4752 4753 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 4754 ASTContext &Context; 4755 const DeclaratorChunk &Chunk; 4756 4757 public: 4758 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 4759 : Context(Context), Chunk(Chunk) {} 4760 4761 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 4762 llvm_unreachable("qualified type locs not expected here!"); 4763 } 4764 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 4765 llvm_unreachable("decayed type locs not expected here!"); 4766 } 4767 4768 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 4769 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 4770 } 4771 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 4772 // nothing 4773 } 4774 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 4775 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 4776 TL.setCaretLoc(Chunk.Loc); 4777 } 4778 void VisitPointerTypeLoc(PointerTypeLoc TL) { 4779 assert(Chunk.Kind == DeclaratorChunk::Pointer); 4780 TL.setStarLoc(Chunk.Loc); 4781 } 4782 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 4783 assert(Chunk.Kind == DeclaratorChunk::Pointer); 4784 TL.setStarLoc(Chunk.Loc); 4785 } 4786 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 4787 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 4788 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 4789 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 4790 4791 const Type* ClsTy = TL.getClass(); 4792 QualType ClsQT = QualType(ClsTy, 0); 4793 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 4794 // Now copy source location info into the type loc component. 4795 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 4796 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 4797 case NestedNameSpecifier::Identifier: 4798 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 4799 { 4800 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 4801 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 4802 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 4803 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 4804 } 4805 break; 4806 4807 case NestedNameSpecifier::TypeSpec: 4808 case NestedNameSpecifier::TypeSpecWithTemplate: 4809 if (isa<ElaboratedType>(ClsTy)) { 4810 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 4811 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 4812 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 4813 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 4814 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 4815 } else { 4816 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 4817 } 4818 break; 4819 4820 case NestedNameSpecifier::Namespace: 4821 case NestedNameSpecifier::NamespaceAlias: 4822 case NestedNameSpecifier::Global: 4823 case NestedNameSpecifier::Super: 4824 llvm_unreachable("Nested-name-specifier must name a type"); 4825 } 4826 4827 // Finally fill in MemberPointerLocInfo fields. 4828 TL.setStarLoc(Chunk.Loc); 4829 TL.setClassTInfo(ClsTInfo); 4830 } 4831 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 4832 assert(Chunk.Kind == DeclaratorChunk::Reference); 4833 // 'Amp' is misleading: this might have been originally 4834 /// spelled with AmpAmp. 4835 TL.setAmpLoc(Chunk.Loc); 4836 } 4837 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 4838 assert(Chunk.Kind == DeclaratorChunk::Reference); 4839 assert(!Chunk.Ref.LValueRef); 4840 TL.setAmpAmpLoc(Chunk.Loc); 4841 } 4842 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 4843 assert(Chunk.Kind == DeclaratorChunk::Array); 4844 TL.setLBracketLoc(Chunk.Loc); 4845 TL.setRBracketLoc(Chunk.EndLoc); 4846 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 4847 } 4848 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 4849 assert(Chunk.Kind == DeclaratorChunk::Function); 4850 TL.setLocalRangeBegin(Chunk.Loc); 4851 TL.setLocalRangeEnd(Chunk.EndLoc); 4852 4853 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 4854 TL.setLParenLoc(FTI.getLParenLoc()); 4855 TL.setRParenLoc(FTI.getRParenLoc()); 4856 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { 4857 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 4858 TL.setParam(tpi++, Param); 4859 } 4860 // FIXME: exception specs 4861 } 4862 void VisitParenTypeLoc(ParenTypeLoc TL) { 4863 assert(Chunk.Kind == DeclaratorChunk::Paren); 4864 TL.setLParenLoc(Chunk.Loc); 4865 TL.setRParenLoc(Chunk.EndLoc); 4866 } 4867 void VisitPipeTypeLoc(PipeTypeLoc TL) { 4868 assert(Chunk.Kind == DeclaratorChunk::Pipe); 4869 TL.setKWLoc(Chunk.Loc); 4870 } 4871 4872 void VisitTypeLoc(TypeLoc TL) { 4873 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 4874 } 4875 }; 4876 } // end anonymous namespace 4877 4878 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 4879 SourceLocation Loc; 4880 switch (Chunk.Kind) { 4881 case DeclaratorChunk::Function: 4882 case DeclaratorChunk::Array: 4883 case DeclaratorChunk::Paren: 4884 case DeclaratorChunk::Pipe: 4885 llvm_unreachable("cannot be _Atomic qualified"); 4886 4887 case DeclaratorChunk::Pointer: 4888 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); 4889 break; 4890 4891 case DeclaratorChunk::BlockPointer: 4892 case DeclaratorChunk::Reference: 4893 case DeclaratorChunk::MemberPointer: 4894 // FIXME: Provide a source location for the _Atomic keyword. 4895 break; 4896 } 4897 4898 ATL.setKWLoc(Loc); 4899 ATL.setParensRange(SourceRange()); 4900 } 4901 4902 /// \brief Create and instantiate a TypeSourceInfo with type source information. 4903 /// 4904 /// \param T QualType referring to the type as written in source code. 4905 /// 4906 /// \param ReturnTypeInfo For declarators whose return type does not show 4907 /// up in the normal place in the declaration specifiers (such as a C++ 4908 /// conversion function), this pointer will refer to a type source information 4909 /// for that return type. 4910 TypeSourceInfo * 4911 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 4912 TypeSourceInfo *ReturnTypeInfo) { 4913 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 4914 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 4915 const AttributeList *DeclAttrs = D.getAttributes(); 4916 4917 // Handle parameter packs whose type is a pack expansion. 4918 if (isa<PackExpansionType>(T)) { 4919 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 4920 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 4921 } 4922 4923 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4924 // An AtomicTypeLoc might be produced by an atomic qualifier in this 4925 // declarator chunk. 4926 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 4927 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 4928 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 4929 } 4930 4931 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 4932 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs); 4933 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 4934 } 4935 4936 // FIXME: Ordering here? 4937 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) 4938 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 4939 4940 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 4941 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 4942 } 4943 4944 // If we have different source information for the return type, use 4945 // that. This really only applies to C++ conversion functions. 4946 if (ReturnTypeInfo) { 4947 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 4948 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 4949 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 4950 } else { 4951 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 4952 } 4953 4954 return TInfo; 4955 } 4956 4957 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 4958 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 4959 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 4960 // and Sema during declaration parsing. Try deallocating/caching them when 4961 // it's appropriate, instead of allocating them and keeping them around. 4962 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 4963 TypeAlignment); 4964 new (LocT) LocInfoType(T, TInfo); 4965 assert(LocT->getTypeClass() != T->getTypeClass() && 4966 "LocInfoType's TypeClass conflicts with an existing Type class"); 4967 return ParsedType::make(QualType(LocT, 0)); 4968 } 4969 4970 void LocInfoType::getAsStringInternal(std::string &Str, 4971 const PrintingPolicy &Policy) const { 4972 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 4973 " was used directly instead of getting the QualType through" 4974 " GetTypeFromParser"); 4975 } 4976 4977 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 4978 // C99 6.7.6: Type names have no identifier. This is already validated by 4979 // the parser. 4980 assert(D.getIdentifier() == nullptr && 4981 "Type name should have no identifier!"); 4982 4983 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4984 QualType T = TInfo->getType(); 4985 if (D.isInvalidType()) 4986 return true; 4987 4988 // Make sure there are no unused decl attributes on the declarator. 4989 // We don't want to do this for ObjC parameters because we're going 4990 // to apply them to the actual parameter declaration. 4991 // Likewise, we don't want to do this for alias declarations, because 4992 // we are actually going to build a declaration from this eventually. 4993 if (D.getContext() != Declarator::ObjCParameterContext && 4994 D.getContext() != Declarator::AliasDeclContext && 4995 D.getContext() != Declarator::AliasTemplateContext) 4996 checkUnusedDeclAttributes(D); 4997 4998 if (getLangOpts().CPlusPlus) { 4999 // Check that there are no default arguments (C++ only). 5000 CheckExtraCXXDefaultArguments(D); 5001 } 5002 5003 return CreateParsedType(T, TInfo); 5004 } 5005 5006 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 5007 QualType T = Context.getObjCInstanceType(); 5008 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 5009 return CreateParsedType(T, TInfo); 5010 } 5011 5012 //===----------------------------------------------------------------------===// 5013 // Type Attribute Processing 5014 //===----------------------------------------------------------------------===// 5015 5016 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 5017 /// specified type. The attribute contains 1 argument, the id of the address 5018 /// space for the type. 5019 static void HandleAddressSpaceTypeAttribute(QualType &Type, 5020 const AttributeList &Attr, Sema &S){ 5021 5022 // If this type is already address space qualified, reject it. 5023 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 5024 // qualifiers for two or more different address spaces." 5025 if (Type.getAddressSpace()) { 5026 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 5027 Attr.setInvalid(); 5028 return; 5029 } 5030 5031 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 5032 // qualified by an address-space qualifier." 5033 if (Type->isFunctionType()) { 5034 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 5035 Attr.setInvalid(); 5036 return; 5037 } 5038 5039 unsigned ASIdx; 5040 if (Attr.getKind() == AttributeList::AT_AddressSpace) { 5041 // Check the attribute arguments. 5042 if (Attr.getNumArgs() != 1) { 5043 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 5044 << Attr.getName() << 1; 5045 Attr.setInvalid(); 5046 return; 5047 } 5048 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 5049 llvm::APSInt addrSpace(32); 5050 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 5051 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 5052 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 5053 << Attr.getName() << AANT_ArgumentIntegerConstant 5054 << ASArgExpr->getSourceRange(); 5055 Attr.setInvalid(); 5056 return; 5057 } 5058 5059 // Bounds checking. 5060 if (addrSpace.isSigned()) { 5061 if (addrSpace.isNegative()) { 5062 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 5063 << ASArgExpr->getSourceRange(); 5064 Attr.setInvalid(); 5065 return; 5066 } 5067 addrSpace.setIsSigned(false); 5068 } 5069 llvm::APSInt max(addrSpace.getBitWidth()); 5070 max = Qualifiers::MaxAddressSpace; 5071 if (addrSpace > max) { 5072 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 5073 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange(); 5074 Attr.setInvalid(); 5075 return; 5076 } 5077 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 5078 } else { 5079 // The keyword-based type attributes imply which address space to use. 5080 switch (Attr.getKind()) { 5081 case AttributeList::AT_OpenCLGlobalAddressSpace: 5082 ASIdx = LangAS::opencl_global; break; 5083 case AttributeList::AT_OpenCLLocalAddressSpace: 5084 ASIdx = LangAS::opencl_local; break; 5085 case AttributeList::AT_OpenCLConstantAddressSpace: 5086 ASIdx = LangAS::opencl_constant; break; 5087 case AttributeList::AT_OpenCLGenericAddressSpace: 5088 ASIdx = LangAS::opencl_generic; break; 5089 default: 5090 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace); 5091 ASIdx = 0; break; 5092 } 5093 } 5094 5095 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 5096 } 5097 5098 /// Does this type have a "direct" ownership qualifier? That is, 5099 /// is it written like "__strong id", as opposed to something like 5100 /// "typeof(foo)", where that happens to be strong? 5101 static bool hasDirectOwnershipQualifier(QualType type) { 5102 // Fast path: no qualifier at all. 5103 assert(type.getQualifiers().hasObjCLifetime()); 5104 5105 while (true) { 5106 // __strong id 5107 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 5108 if (attr->getAttrKind() == AttributedType::attr_objc_ownership) 5109 return true; 5110 5111 type = attr->getModifiedType(); 5112 5113 // X *__strong (...) 5114 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 5115 type = paren->getInnerType(); 5116 5117 // That's it for things we want to complain about. In particular, 5118 // we do not want to look through typedefs, typeof(expr), 5119 // typeof(type), or any other way that the type is somehow 5120 // abstracted. 5121 } else { 5122 5123 return false; 5124 } 5125 } 5126 } 5127 5128 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 5129 /// attribute on the specified type. 5130 /// 5131 /// Returns 'true' if the attribute was handled. 5132 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 5133 AttributeList &attr, 5134 QualType &type) { 5135 bool NonObjCPointer = false; 5136 5137 if (!type->isDependentType() && !type->isUndeducedType()) { 5138 if (const PointerType *ptr = type->getAs<PointerType>()) { 5139 QualType pointee = ptr->getPointeeType(); 5140 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 5141 return false; 5142 // It is important not to lose the source info that there was an attribute 5143 // applied to non-objc pointer. We will create an attributed type but 5144 // its type will be the same as the original type. 5145 NonObjCPointer = true; 5146 } else if (!type->isObjCRetainableType()) { 5147 return false; 5148 } 5149 5150 // Don't accept an ownership attribute in the declspec if it would 5151 // just be the return type of a block pointer. 5152 if (state.isProcessingDeclSpec()) { 5153 Declarator &D = state.getDeclarator(); 5154 if (maybeMovePastReturnType(D, D.getNumTypeObjects(), 5155 /*onlyBlockPointers=*/true)) 5156 return false; 5157 } 5158 } 5159 5160 Sema &S = state.getSema(); 5161 SourceLocation AttrLoc = attr.getLoc(); 5162 if (AttrLoc.isMacroID()) 5163 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; 5164 5165 if (!attr.isArgIdent(0)) { 5166 S.Diag(AttrLoc, diag::err_attribute_argument_type) 5167 << attr.getName() << AANT_ArgumentString; 5168 attr.setInvalid(); 5169 return true; 5170 } 5171 5172 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 5173 Qualifiers::ObjCLifetime lifetime; 5174 if (II->isStr("none")) 5175 lifetime = Qualifiers::OCL_ExplicitNone; 5176 else if (II->isStr("strong")) 5177 lifetime = Qualifiers::OCL_Strong; 5178 else if (II->isStr("weak")) 5179 lifetime = Qualifiers::OCL_Weak; 5180 else if (II->isStr("autoreleasing")) 5181 lifetime = Qualifiers::OCL_Autoreleasing; 5182 else { 5183 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 5184 << attr.getName() << II; 5185 attr.setInvalid(); 5186 return true; 5187 } 5188 5189 // Just ignore lifetime attributes other than __weak and __unsafe_unretained 5190 // outside of ARC mode. 5191 if (!S.getLangOpts().ObjCAutoRefCount && 5192 lifetime != Qualifiers::OCL_Weak && 5193 lifetime != Qualifiers::OCL_ExplicitNone) { 5194 return true; 5195 } 5196 5197 SplitQualType underlyingType = type.split(); 5198 5199 // Check for redundant/conflicting ownership qualifiers. 5200 if (Qualifiers::ObjCLifetime previousLifetime 5201 = type.getQualifiers().getObjCLifetime()) { 5202 // If it's written directly, that's an error. 5203 if (hasDirectOwnershipQualifier(type)) { 5204 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 5205 << type; 5206 return true; 5207 } 5208 5209 // Otherwise, if the qualifiers actually conflict, pull sugar off 5210 // until we reach a type that is directly qualified. 5211 if (previousLifetime != lifetime) { 5212 // This should always terminate: the canonical type is 5213 // qualified, so some bit of sugar must be hiding it. 5214 while (!underlyingType.Quals.hasObjCLifetime()) { 5215 underlyingType = underlyingType.getSingleStepDesugaredType(); 5216 } 5217 underlyingType.Quals.removeObjCLifetime(); 5218 } 5219 } 5220 5221 underlyingType.Quals.addObjCLifetime(lifetime); 5222 5223 if (NonObjCPointer) { 5224 StringRef name = attr.getName()->getName(); 5225 switch (lifetime) { 5226 case Qualifiers::OCL_None: 5227 case Qualifiers::OCL_ExplicitNone: 5228 break; 5229 case Qualifiers::OCL_Strong: name = "__strong"; break; 5230 case Qualifiers::OCL_Weak: name = "__weak"; break; 5231 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 5232 } 5233 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 5234 << TDS_ObjCObjOrBlock << type; 5235 } 5236 5237 // Don't actually add the __unsafe_unretained qualifier in non-ARC files, 5238 // because having both 'T' and '__unsafe_unretained T' exist in the type 5239 // system causes unfortunate widespread consistency problems. (For example, 5240 // they're not considered compatible types, and we mangle them identicially 5241 // as template arguments.) These problems are all individually fixable, 5242 // but it's easier to just not add the qualifier and instead sniff it out 5243 // in specific places using isObjCInertUnsafeUnretainedType(). 5244 // 5245 // Doing this does means we miss some trivial consistency checks that 5246 // would've triggered in ARC, but that's better than trying to solve all 5247 // the coexistence problems with __unsafe_unretained. 5248 if (!S.getLangOpts().ObjCAutoRefCount && 5249 lifetime == Qualifiers::OCL_ExplicitNone) { 5250 type = S.Context.getAttributedType( 5251 AttributedType::attr_objc_inert_unsafe_unretained, 5252 type, type); 5253 return true; 5254 } 5255 5256 QualType origType = type; 5257 if (!NonObjCPointer) 5258 type = S.Context.getQualifiedType(underlyingType); 5259 5260 // If we have a valid source location for the attribute, use an 5261 // AttributedType instead. 5262 if (AttrLoc.isValid()) 5263 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 5264 origType, type); 5265 5266 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, 5267 unsigned diagnostic, QualType type) { 5268 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 5269 S.DelayedDiagnostics.add( 5270 sema::DelayedDiagnostic::makeForbiddenType( 5271 S.getSourceManager().getExpansionLoc(loc), 5272 diagnostic, type, /*ignored*/ 0)); 5273 } else { 5274 S.Diag(loc, diagnostic); 5275 } 5276 }; 5277 5278 // Sometimes, __weak isn't allowed. 5279 if (lifetime == Qualifiers::OCL_Weak && 5280 !S.getLangOpts().ObjCWeak && !NonObjCPointer) { 5281 5282 // Use a specialized diagnostic if the runtime just doesn't support them. 5283 unsigned diagnostic = 5284 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled 5285 : diag::err_arc_weak_no_runtime); 5286 5287 // In any case, delay the diagnostic until we know what we're parsing. 5288 diagnoseOrDelay(S, AttrLoc, diagnostic, type); 5289 5290 attr.setInvalid(); 5291 return true; 5292 } 5293 5294 // Forbid __weak for class objects marked as 5295 // objc_arc_weak_reference_unavailable 5296 if (lifetime == Qualifiers::OCL_Weak) { 5297 if (const ObjCObjectPointerType *ObjT = 5298 type->getAs<ObjCObjectPointerType>()) { 5299 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 5300 if (Class->isArcWeakrefUnavailable()) { 5301 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 5302 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 5303 diag::note_class_declared); 5304 } 5305 } 5306 } 5307 } 5308 5309 return true; 5310 } 5311 5312 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 5313 /// attribute on the specified type. Returns true to indicate that 5314 /// the attribute was handled, false to indicate that the type does 5315 /// not permit the attribute. 5316 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 5317 AttributeList &attr, 5318 QualType &type) { 5319 Sema &S = state.getSema(); 5320 5321 // Delay if this isn't some kind of pointer. 5322 if (!type->isPointerType() && 5323 !type->isObjCObjectPointerType() && 5324 !type->isBlockPointerType()) 5325 return false; 5326 5327 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 5328 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 5329 attr.setInvalid(); 5330 return true; 5331 } 5332 5333 // Check the attribute arguments. 5334 if (!attr.isArgIdent(0)) { 5335 S.Diag(attr.getLoc(), diag::err_attribute_argument_type) 5336 << attr.getName() << AANT_ArgumentString; 5337 attr.setInvalid(); 5338 return true; 5339 } 5340 Qualifiers::GC GCAttr; 5341 if (attr.getNumArgs() > 1) { 5342 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) 5343 << attr.getName() << 1; 5344 attr.setInvalid(); 5345 return true; 5346 } 5347 5348 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 5349 if (II->isStr("weak")) 5350 GCAttr = Qualifiers::Weak; 5351 else if (II->isStr("strong")) 5352 GCAttr = Qualifiers::Strong; 5353 else { 5354 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 5355 << attr.getName() << II; 5356 attr.setInvalid(); 5357 return true; 5358 } 5359 5360 QualType origType = type; 5361 type = S.Context.getObjCGCQualType(origType, GCAttr); 5362 5363 // Make an attributed type to preserve the source information. 5364 if (attr.getLoc().isValid()) 5365 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 5366 origType, type); 5367 5368 return true; 5369 } 5370 5371 namespace { 5372 /// A helper class to unwrap a type down to a function for the 5373 /// purposes of applying attributes there. 5374 /// 5375 /// Use: 5376 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 5377 /// if (unwrapped.isFunctionType()) { 5378 /// const FunctionType *fn = unwrapped.get(); 5379 /// // change fn somehow 5380 /// T = unwrapped.wrap(fn); 5381 /// } 5382 struct FunctionTypeUnwrapper { 5383 enum WrapKind { 5384 Desugar, 5385 Attributed, 5386 Parens, 5387 Pointer, 5388 BlockPointer, 5389 Reference, 5390 MemberPointer 5391 }; 5392 5393 QualType Original; 5394 const FunctionType *Fn; 5395 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 5396 5397 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 5398 while (true) { 5399 const Type *Ty = T.getTypePtr(); 5400 if (isa<FunctionType>(Ty)) { 5401 Fn = cast<FunctionType>(Ty); 5402 return; 5403 } else if (isa<ParenType>(Ty)) { 5404 T = cast<ParenType>(Ty)->getInnerType(); 5405 Stack.push_back(Parens); 5406 } else if (isa<PointerType>(Ty)) { 5407 T = cast<PointerType>(Ty)->getPointeeType(); 5408 Stack.push_back(Pointer); 5409 } else if (isa<BlockPointerType>(Ty)) { 5410 T = cast<BlockPointerType>(Ty)->getPointeeType(); 5411 Stack.push_back(BlockPointer); 5412 } else if (isa<MemberPointerType>(Ty)) { 5413 T = cast<MemberPointerType>(Ty)->getPointeeType(); 5414 Stack.push_back(MemberPointer); 5415 } else if (isa<ReferenceType>(Ty)) { 5416 T = cast<ReferenceType>(Ty)->getPointeeType(); 5417 Stack.push_back(Reference); 5418 } else if (isa<AttributedType>(Ty)) { 5419 T = cast<AttributedType>(Ty)->getEquivalentType(); 5420 Stack.push_back(Attributed); 5421 } else { 5422 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 5423 if (Ty == DTy) { 5424 Fn = nullptr; 5425 return; 5426 } 5427 5428 T = QualType(DTy, 0); 5429 Stack.push_back(Desugar); 5430 } 5431 } 5432 } 5433 5434 bool isFunctionType() const { return (Fn != nullptr); } 5435 const FunctionType *get() const { return Fn; } 5436 5437 QualType wrap(Sema &S, const FunctionType *New) { 5438 // If T wasn't modified from the unwrapped type, do nothing. 5439 if (New == get()) return Original; 5440 5441 Fn = New; 5442 return wrap(S.Context, Original, 0); 5443 } 5444 5445 private: 5446 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 5447 if (I == Stack.size()) 5448 return C.getQualifiedType(Fn, Old.getQualifiers()); 5449 5450 // Build up the inner type, applying the qualifiers from the old 5451 // type to the new type. 5452 SplitQualType SplitOld = Old.split(); 5453 5454 // As a special case, tail-recurse if there are no qualifiers. 5455 if (SplitOld.Quals.empty()) 5456 return wrap(C, SplitOld.Ty, I); 5457 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 5458 } 5459 5460 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 5461 if (I == Stack.size()) return QualType(Fn, 0); 5462 5463 switch (static_cast<WrapKind>(Stack[I++])) { 5464 case Desugar: 5465 // This is the point at which we potentially lose source 5466 // information. 5467 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 5468 5469 case Attributed: 5470 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); 5471 5472 case Parens: { 5473 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 5474 return C.getParenType(New); 5475 } 5476 5477 case Pointer: { 5478 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 5479 return C.getPointerType(New); 5480 } 5481 5482 case BlockPointer: { 5483 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 5484 return C.getBlockPointerType(New); 5485 } 5486 5487 case MemberPointer: { 5488 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 5489 QualType New = wrap(C, OldMPT->getPointeeType(), I); 5490 return C.getMemberPointerType(New, OldMPT->getClass()); 5491 } 5492 5493 case Reference: { 5494 const ReferenceType *OldRef = cast<ReferenceType>(Old); 5495 QualType New = wrap(C, OldRef->getPointeeType(), I); 5496 if (isa<LValueReferenceType>(OldRef)) 5497 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 5498 else 5499 return C.getRValueReferenceType(New); 5500 } 5501 } 5502 5503 llvm_unreachable("unknown wrapping kind"); 5504 } 5505 }; 5506 } // end anonymous namespace 5507 5508 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 5509 AttributeList &Attr, 5510 QualType &Type) { 5511 Sema &S = State.getSema(); 5512 5513 AttributeList::Kind Kind = Attr.getKind(); 5514 QualType Desugared = Type; 5515 const AttributedType *AT = dyn_cast<AttributedType>(Type); 5516 while (AT) { 5517 AttributedType::Kind CurAttrKind = AT->getAttrKind(); 5518 5519 // You cannot specify duplicate type attributes, so if the attribute has 5520 // already been applied, flag it. 5521 if (getAttrListKind(CurAttrKind) == Kind) { 5522 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact) 5523 << Attr.getName(); 5524 return true; 5525 } 5526 5527 // You cannot have both __sptr and __uptr on the same type, nor can you 5528 // have __ptr32 and __ptr64. 5529 if ((CurAttrKind == AttributedType::attr_ptr32 && 5530 Kind == AttributeList::AT_Ptr64) || 5531 (CurAttrKind == AttributedType::attr_ptr64 && 5532 Kind == AttributeList::AT_Ptr32)) { 5533 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 5534 << "'__ptr32'" << "'__ptr64'"; 5535 return true; 5536 } else if ((CurAttrKind == AttributedType::attr_sptr && 5537 Kind == AttributeList::AT_UPtr) || 5538 (CurAttrKind == AttributedType::attr_uptr && 5539 Kind == AttributeList::AT_SPtr)) { 5540 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 5541 << "'__sptr'" << "'__uptr'"; 5542 return true; 5543 } 5544 5545 Desugared = AT->getEquivalentType(); 5546 AT = dyn_cast<AttributedType>(Desugared); 5547 } 5548 5549 // Pointer type qualifiers can only operate on pointer types, but not 5550 // pointer-to-member types. 5551 if (!isa<PointerType>(Desugared)) { 5552 if (Type->isMemberPointerType()) 5553 S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers) 5554 << Attr.getName(); 5555 else 5556 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only) 5557 << Attr.getName() << 0; 5558 return true; 5559 } 5560 5561 AttributedType::Kind TAK; 5562 switch (Kind) { 5563 default: llvm_unreachable("Unknown attribute kind"); 5564 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break; 5565 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break; 5566 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break; 5567 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break; 5568 } 5569 5570 Type = S.Context.getAttributedType(TAK, Type, Type); 5571 return false; 5572 } 5573 5574 bool Sema::checkNullabilityTypeSpecifier(QualType &type, 5575 NullabilityKind nullability, 5576 SourceLocation nullabilityLoc, 5577 bool isContextSensitive) { 5578 // We saw a nullability type specifier. If this is the first one for 5579 // this file, note that. 5580 FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc); 5581 if (!file.isInvalid()) { 5582 FileNullability &fileNullability = NullabilityMap[file]; 5583 if (!fileNullability.SawTypeNullability) { 5584 // If we have already seen a pointer declarator without a nullability 5585 // annotation, complain about it. 5586 if (fileNullability.PointerLoc.isValid()) { 5587 Diag(fileNullability.PointerLoc, diag::warn_nullability_missing) 5588 << static_cast<unsigned>(fileNullability.PointerKind); 5589 } 5590 5591 fileNullability.SawTypeNullability = true; 5592 } 5593 } 5594 5595 // Check for existing nullability attributes on the type. 5596 QualType desugared = type; 5597 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { 5598 // Check whether there is already a null 5599 if (auto existingNullability = attributed->getImmediateNullability()) { 5600 // Duplicated nullability. 5601 if (nullability == *existingNullability) { 5602 Diag(nullabilityLoc, diag::warn_nullability_duplicate) 5603 << DiagNullabilityKind(nullability, isContextSensitive) 5604 << FixItHint::CreateRemoval(nullabilityLoc); 5605 5606 break; 5607 } 5608 5609 // Conflicting nullability. 5610 Diag(nullabilityLoc, diag::err_nullability_conflicting) 5611 << DiagNullabilityKind(nullability, isContextSensitive) 5612 << DiagNullabilityKind(*existingNullability, false); 5613 return true; 5614 } 5615 5616 desugared = attributed->getModifiedType(); 5617 } 5618 5619 // If there is already a different nullability specifier, complain. 5620 // This (unlike the code above) looks through typedefs that might 5621 // have nullability specifiers on them, which means we cannot 5622 // provide a useful Fix-It. 5623 if (auto existingNullability = desugared->getNullability(Context)) { 5624 if (nullability != *existingNullability) { 5625 Diag(nullabilityLoc, diag::err_nullability_conflicting) 5626 << DiagNullabilityKind(nullability, isContextSensitive) 5627 << DiagNullabilityKind(*existingNullability, false); 5628 5629 // Try to find the typedef with the existing nullability specifier. 5630 if (auto typedefType = desugared->getAs<TypedefType>()) { 5631 TypedefNameDecl *typedefDecl = typedefType->getDecl(); 5632 QualType underlyingType = typedefDecl->getUnderlyingType(); 5633 if (auto typedefNullability 5634 = AttributedType::stripOuterNullability(underlyingType)) { 5635 if (*typedefNullability == *existingNullability) { 5636 Diag(typedefDecl->getLocation(), diag::note_nullability_here) 5637 << DiagNullabilityKind(*existingNullability, false); 5638 } 5639 } 5640 } 5641 5642 return true; 5643 } 5644 } 5645 5646 // If this definitely isn't a pointer type, reject the specifier. 5647 if (!desugared->canHaveNullability()) { 5648 Diag(nullabilityLoc, diag::err_nullability_nonpointer) 5649 << DiagNullabilityKind(nullability, isContextSensitive) << type; 5650 return true; 5651 } 5652 5653 // For the context-sensitive keywords/Objective-C property 5654 // attributes, require that the type be a single-level pointer. 5655 if (isContextSensitive) { 5656 // Make sure that the pointee isn't itself a pointer type. 5657 QualType pointeeType = desugared->getPointeeType(); 5658 if (pointeeType->isAnyPointerType() || 5659 pointeeType->isObjCObjectPointerType() || 5660 pointeeType->isMemberPointerType()) { 5661 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) 5662 << DiagNullabilityKind(nullability, true) 5663 << type; 5664 Diag(nullabilityLoc, diag::note_nullability_type_specifier) 5665 << DiagNullabilityKind(nullability, false) 5666 << type 5667 << FixItHint::CreateReplacement(nullabilityLoc, 5668 getNullabilitySpelling(nullability)); 5669 return true; 5670 } 5671 } 5672 5673 // Form the attributed type. 5674 type = Context.getAttributedType( 5675 AttributedType::getNullabilityAttrKind(nullability), type, type); 5676 return false; 5677 } 5678 5679 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) { 5680 // Find out if it's an Objective-C object or object pointer type; 5681 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); 5682 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() 5683 : type->getAs<ObjCObjectType>(); 5684 5685 // If not, we can't apply __kindof. 5686 if (!objType) { 5687 // FIXME: Handle dependent types that aren't yet object types. 5688 Diag(loc, diag::err_objc_kindof_nonobject) 5689 << type; 5690 return true; 5691 } 5692 5693 // Rebuild the "equivalent" type, which pushes __kindof down into 5694 // the object type. 5695 QualType equivType = Context.getObjCObjectType(objType->getBaseType(), 5696 objType->getTypeArgsAsWritten(), 5697 objType->getProtocols(), 5698 /*isKindOf=*/true); 5699 5700 // If we started with an object pointer type, rebuild it. 5701 if (ptrType) { 5702 equivType = Context.getObjCObjectPointerType(equivType); 5703 if (auto nullability = type->getNullability(Context)) { 5704 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability); 5705 equivType = Context.getAttributedType(attrKind, equivType, equivType); 5706 } 5707 } 5708 5709 // Build the attributed type to record where __kindof occurred. 5710 type = Context.getAttributedType(AttributedType::attr_objc_kindof, 5711 type, 5712 equivType); 5713 5714 return false; 5715 } 5716 5717 /// Map a nullability attribute kind to a nullability kind. 5718 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) { 5719 switch (kind) { 5720 case AttributeList::AT_TypeNonNull: 5721 return NullabilityKind::NonNull; 5722 5723 case AttributeList::AT_TypeNullable: 5724 return NullabilityKind::Nullable; 5725 5726 case AttributeList::AT_TypeNullUnspecified: 5727 return NullabilityKind::Unspecified; 5728 5729 default: 5730 llvm_unreachable("not a nullability attribute kind"); 5731 } 5732 } 5733 5734 /// Distribute a nullability type attribute that cannot be applied to 5735 /// the type specifier to a pointer, block pointer, or member pointer 5736 /// declarator, complaining if necessary. 5737 /// 5738 /// \returns true if the nullability annotation was distributed, false 5739 /// otherwise. 5740 static bool distributeNullabilityTypeAttr(TypeProcessingState &state, 5741 QualType type, 5742 AttributeList &attr) { 5743 Declarator &declarator = state.getDeclarator(); 5744 5745 /// Attempt to move the attribute to the specified chunk. 5746 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { 5747 // If there is already a nullability attribute there, don't add 5748 // one. 5749 if (hasNullabilityAttr(chunk.getAttrListRef())) 5750 return false; 5751 5752 // Complain about the nullability qualifier being in the wrong 5753 // place. 5754 enum { 5755 PK_Pointer, 5756 PK_BlockPointer, 5757 PK_MemberPointer, 5758 PK_FunctionPointer, 5759 PK_MemberFunctionPointer, 5760 } pointerKind 5761 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer 5762 : PK_Pointer) 5763 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer 5764 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; 5765 5766 auto diag = state.getSema().Diag(attr.getLoc(), 5767 diag::warn_nullability_declspec) 5768 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), 5769 attr.isContextSensitiveKeywordAttribute()) 5770 << type 5771 << static_cast<unsigned>(pointerKind); 5772 5773 // FIXME: MemberPointer chunks don't carry the location of the *. 5774 if (chunk.Kind != DeclaratorChunk::MemberPointer) { 5775 diag << FixItHint::CreateRemoval(attr.getLoc()) 5776 << FixItHint::CreateInsertion( 5777 state.getSema().getPreprocessor() 5778 .getLocForEndOfToken(chunk.Loc), 5779 " " + attr.getName()->getName().str() + " "); 5780 } 5781 5782 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 5783 chunk.getAttrListRef()); 5784 return true; 5785 }; 5786 5787 // Move it to the outermost pointer, member pointer, or block 5788 // pointer declarator. 5789 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 5790 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 5791 switch (chunk.Kind) { 5792 case DeclaratorChunk::Pointer: 5793 case DeclaratorChunk::BlockPointer: 5794 case DeclaratorChunk::MemberPointer: 5795 return moveToChunk(chunk, false); 5796 5797 case DeclaratorChunk::Paren: 5798 case DeclaratorChunk::Array: 5799 continue; 5800 5801 case DeclaratorChunk::Function: 5802 // Try to move past the return type to a function/block/member 5803 // function pointer. 5804 if (DeclaratorChunk *dest = maybeMovePastReturnType( 5805 declarator, i, 5806 /*onlyBlockPointers=*/false)) { 5807 return moveToChunk(*dest, true); 5808 } 5809 5810 return false; 5811 5812 // Don't walk through these. 5813 case DeclaratorChunk::Reference: 5814 case DeclaratorChunk::Pipe: 5815 return false; 5816 } 5817 } 5818 5819 return false; 5820 } 5821 5822 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) { 5823 assert(!Attr.isInvalid()); 5824 switch (Attr.getKind()) { 5825 default: 5826 llvm_unreachable("not a calling convention attribute"); 5827 case AttributeList::AT_CDecl: 5828 return AttributedType::attr_cdecl; 5829 case AttributeList::AT_FastCall: 5830 return AttributedType::attr_fastcall; 5831 case AttributeList::AT_StdCall: 5832 return AttributedType::attr_stdcall; 5833 case AttributeList::AT_ThisCall: 5834 return AttributedType::attr_thiscall; 5835 case AttributeList::AT_Pascal: 5836 return AttributedType::attr_pascal; 5837 case AttributeList::AT_VectorCall: 5838 return AttributedType::attr_vectorcall; 5839 case AttributeList::AT_Pcs: { 5840 // The attribute may have had a fixit applied where we treated an 5841 // identifier as a string literal. The contents of the string are valid, 5842 // but the form may not be. 5843 StringRef Str; 5844 if (Attr.isArgExpr(0)) 5845 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); 5846 else 5847 Str = Attr.getArgAsIdent(0)->Ident->getName(); 5848 return llvm::StringSwitch<AttributedType::Kind>(Str) 5849 .Case("aapcs", AttributedType::attr_pcs) 5850 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp); 5851 } 5852 case AttributeList::AT_IntelOclBicc: 5853 return AttributedType::attr_inteloclbicc; 5854 case AttributeList::AT_MSABI: 5855 return AttributedType::attr_ms_abi; 5856 case AttributeList::AT_SysVABI: 5857 return AttributedType::attr_sysv_abi; 5858 } 5859 llvm_unreachable("unexpected attribute kind!"); 5860 } 5861 5862 /// Process an individual function attribute. Returns true to 5863 /// indicate that the attribute was handled, false if it wasn't. 5864 static bool handleFunctionTypeAttr(TypeProcessingState &state, 5865 AttributeList &attr, 5866 QualType &type) { 5867 Sema &S = state.getSema(); 5868 5869 FunctionTypeUnwrapper unwrapped(S, type); 5870 5871 if (attr.getKind() == AttributeList::AT_NoReturn) { 5872 if (S.CheckNoReturnAttr(attr)) 5873 return true; 5874 5875 // Delay if this is not a function type. 5876 if (!unwrapped.isFunctionType()) 5877 return false; 5878 5879 // Otherwise we can process right away. 5880 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 5881 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 5882 return true; 5883 } 5884 5885 // ns_returns_retained is not always a type attribute, but if we got 5886 // here, we're treating it as one right now. 5887 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) { 5888 assert(S.getLangOpts().ObjCAutoRefCount && 5889 "ns_returns_retained treated as type attribute in non-ARC"); 5890 if (attr.getNumArgs()) return true; 5891 5892 // Delay if this is not a function type. 5893 if (!unwrapped.isFunctionType()) 5894 return false; 5895 5896 FunctionType::ExtInfo EI 5897 = unwrapped.get()->getExtInfo().withProducesResult(true); 5898 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 5899 return true; 5900 } 5901 5902 if (attr.getKind() == AttributeList::AT_Regparm) { 5903 unsigned value; 5904 if (S.CheckRegparmAttr(attr, value)) 5905 return true; 5906 5907 // Delay if this is not a function type. 5908 if (!unwrapped.isFunctionType()) 5909 return false; 5910 5911 // Diagnose regparm with fastcall. 5912 const FunctionType *fn = unwrapped.get(); 5913 CallingConv CC = fn->getCallConv(); 5914 if (CC == CC_X86FastCall) { 5915 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 5916 << FunctionType::getNameForCallConv(CC) 5917 << "regparm"; 5918 attr.setInvalid(); 5919 return true; 5920 } 5921 5922 FunctionType::ExtInfo EI = 5923 unwrapped.get()->getExtInfo().withRegParm(value); 5924 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 5925 return true; 5926 } 5927 5928 // Delay if the type didn't work out to a function. 5929 if (!unwrapped.isFunctionType()) return false; 5930 5931 // Otherwise, a calling convention. 5932 CallingConv CC; 5933 if (S.CheckCallingConvAttr(attr, CC)) 5934 return true; 5935 5936 const FunctionType *fn = unwrapped.get(); 5937 CallingConv CCOld = fn->getCallConv(); 5938 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr); 5939 5940 if (CCOld != CC) { 5941 // Error out on when there's already an attribute on the type 5942 // and the CCs don't match. 5943 const AttributedType *AT = S.getCallingConvAttributedType(type); 5944 if (AT && AT->getAttrKind() != CCAttrKind) { 5945 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 5946 << FunctionType::getNameForCallConv(CC) 5947 << FunctionType::getNameForCallConv(CCOld); 5948 attr.setInvalid(); 5949 return true; 5950 } 5951 } 5952 5953 // Diagnose use of callee-cleanup calling convention on variadic functions. 5954 if (!supportsVariadicCall(CC)) { 5955 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); 5956 if (FnP && FnP->isVariadic()) { 5957 unsigned DiagID = diag::err_cconv_varargs; 5958 // stdcall and fastcall are ignored with a warning for GCC and MS 5959 // compatibility. 5960 if (CC == CC_X86StdCall || CC == CC_X86FastCall) 5961 DiagID = diag::warn_cconv_varargs; 5962 5963 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC); 5964 attr.setInvalid(); 5965 return true; 5966 } 5967 } 5968 5969 // Also diagnose fastcall with regparm. 5970 if (CC == CC_X86FastCall && fn->getHasRegParm()) { 5971 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 5972 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); 5973 attr.setInvalid(); 5974 return true; 5975 } 5976 5977 // Modify the CC from the wrapped function type, wrap it all back, and then 5978 // wrap the whole thing in an AttributedType as written. The modified type 5979 // might have a different CC if we ignored the attribute. 5980 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 5981 QualType Equivalent = 5982 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 5983 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent); 5984 return true; 5985 } 5986 5987 bool Sema::hasExplicitCallingConv(QualType &T) { 5988 QualType R = T.IgnoreParens(); 5989 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) { 5990 if (AT->isCallingConv()) 5991 return true; 5992 R = AT->getModifiedType().IgnoreParens(); 5993 } 5994 return false; 5995 } 5996 5997 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 5998 SourceLocation Loc) { 5999 FunctionTypeUnwrapper Unwrapped(*this, T); 6000 const FunctionType *FT = Unwrapped.get(); 6001 bool IsVariadic = (isa<FunctionProtoType>(FT) && 6002 cast<FunctionProtoType>(FT)->isVariadic()); 6003 CallingConv CurCC = FT->getCallConv(); 6004 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); 6005 6006 if (CurCC == ToCC) 6007 return; 6008 6009 // MS compiler ignores explicit calling convention attributes on structors. We 6010 // should do the same. 6011 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { 6012 // Issue a warning on ignored calling convention -- except of __stdcall. 6013 // Again, this is what MS compiler does. 6014 if (CurCC != CC_X86StdCall) 6015 Diag(Loc, diag::warn_cconv_structors) 6016 << FunctionType::getNameForCallConv(CurCC); 6017 // Default adjustment. 6018 } else { 6019 // Only adjust types with the default convention. For example, on Windows 6020 // we should adjust a __cdecl type to __thiscall for instance methods, and a 6021 // __thiscall type to __cdecl for static methods. 6022 CallingConv DefaultCC = 6023 Context.getDefaultCallingConvention(IsVariadic, IsStatic); 6024 6025 if (CurCC != DefaultCC || DefaultCC == ToCC) 6026 return; 6027 6028 if (hasExplicitCallingConv(T)) 6029 return; 6030 } 6031 6032 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); 6033 QualType Wrapped = Unwrapped.wrap(*this, FT); 6034 T = Context.getAdjustedType(T, Wrapped); 6035 } 6036 6037 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 6038 /// and float scalars, although arrays, pointers, and function return values are 6039 /// allowed in conjunction with this construct. Aggregates with this attribute 6040 /// are invalid, even if they are of the same size as a corresponding scalar. 6041 /// The raw attribute should contain precisely 1 argument, the vector size for 6042 /// the variable, measured in bytes. If curType and rawAttr are well formed, 6043 /// this routine will return a new vector type. 6044 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 6045 Sema &S) { 6046 // Check the attribute arguments. 6047 if (Attr.getNumArgs() != 1) { 6048 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6049 << Attr.getName() << 1; 6050 Attr.setInvalid(); 6051 return; 6052 } 6053 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6054 llvm::APSInt vecSize(32); 6055 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 6056 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 6057 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6058 << Attr.getName() << AANT_ArgumentIntegerConstant 6059 << sizeExpr->getSourceRange(); 6060 Attr.setInvalid(); 6061 return; 6062 } 6063 // The base type must be integer (not Boolean or enumeration) or float, and 6064 // can't already be a vector. 6065 if (!CurType->isBuiltinType() || CurType->isBooleanType() || 6066 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) { 6067 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 6068 Attr.setInvalid(); 6069 return; 6070 } 6071 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 6072 // vecSize is specified in bytes - convert to bits. 6073 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 6074 6075 // the vector size needs to be an integral multiple of the type size. 6076 if (vectorSize % typeSize) { 6077 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 6078 << sizeExpr->getSourceRange(); 6079 Attr.setInvalid(); 6080 return; 6081 } 6082 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) { 6083 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large) 6084 << sizeExpr->getSourceRange(); 6085 Attr.setInvalid(); 6086 return; 6087 } 6088 if (vectorSize == 0) { 6089 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 6090 << sizeExpr->getSourceRange(); 6091 Attr.setInvalid(); 6092 return; 6093 } 6094 6095 // Success! Instantiate the vector type, the number of elements is > 0, and 6096 // not required to be a power of 2, unlike GCC. 6097 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 6098 VectorType::GenericVector); 6099 } 6100 6101 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 6102 /// a type. 6103 static void HandleExtVectorTypeAttr(QualType &CurType, 6104 const AttributeList &Attr, 6105 Sema &S) { 6106 // check the attribute arguments. 6107 if (Attr.getNumArgs() != 1) { 6108 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6109 << Attr.getName() << 1; 6110 return; 6111 } 6112 6113 Expr *sizeExpr; 6114 6115 // Special case where the argument is a template id. 6116 if (Attr.isArgIdent(0)) { 6117 CXXScopeSpec SS; 6118 SourceLocation TemplateKWLoc; 6119 UnqualifiedId id; 6120 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); 6121 6122 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 6123 id, false, false); 6124 if (Size.isInvalid()) 6125 return; 6126 6127 sizeExpr = Size.get(); 6128 } else { 6129 sizeExpr = Attr.getArgAsExpr(0); 6130 } 6131 6132 // Create the vector type. 6133 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 6134 if (!T.isNull()) 6135 CurType = T; 6136 } 6137 6138 static bool isPermittedNeonBaseType(QualType &Ty, 6139 VectorType::VectorKind VecKind, Sema &S) { 6140 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 6141 if (!BTy) 6142 return false; 6143 6144 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 6145 6146 // Signed poly is mathematically wrong, but has been baked into some ABIs by 6147 // now. 6148 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || 6149 Triple.getArch() == llvm::Triple::aarch64_be; 6150 if (VecKind == VectorType::NeonPolyVector) { 6151 if (IsPolyUnsigned) { 6152 // AArch64 polynomial vectors are unsigned and support poly64. 6153 return BTy->getKind() == BuiltinType::UChar || 6154 BTy->getKind() == BuiltinType::UShort || 6155 BTy->getKind() == BuiltinType::ULong || 6156 BTy->getKind() == BuiltinType::ULongLong; 6157 } else { 6158 // AArch32 polynomial vector are signed. 6159 return BTy->getKind() == BuiltinType::SChar || 6160 BTy->getKind() == BuiltinType::Short; 6161 } 6162 } 6163 6164 // Non-polynomial vector types: the usual suspects are allowed, as well as 6165 // float64_t on AArch64. 6166 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 || 6167 Triple.getArch() == llvm::Triple::aarch64_be; 6168 6169 if (Is64Bit && BTy->getKind() == BuiltinType::Double) 6170 return true; 6171 6172 return BTy->getKind() == BuiltinType::SChar || 6173 BTy->getKind() == BuiltinType::UChar || 6174 BTy->getKind() == BuiltinType::Short || 6175 BTy->getKind() == BuiltinType::UShort || 6176 BTy->getKind() == BuiltinType::Int || 6177 BTy->getKind() == BuiltinType::UInt || 6178 BTy->getKind() == BuiltinType::Long || 6179 BTy->getKind() == BuiltinType::ULong || 6180 BTy->getKind() == BuiltinType::LongLong || 6181 BTy->getKind() == BuiltinType::ULongLong || 6182 BTy->getKind() == BuiltinType::Float || 6183 BTy->getKind() == BuiltinType::Half; 6184 } 6185 6186 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 6187 /// "neon_polyvector_type" attributes are used to create vector types that 6188 /// are mangled according to ARM's ABI. Otherwise, these types are identical 6189 /// to those created with the "vector_size" attribute. Unlike "vector_size" 6190 /// the argument to these Neon attributes is the number of vector elements, 6191 /// not the vector size in bytes. The vector width and element type must 6192 /// match one of the standard Neon vector types. 6193 static void HandleNeonVectorTypeAttr(QualType& CurType, 6194 const AttributeList &Attr, Sema &S, 6195 VectorType::VectorKind VecKind) { 6196 // Target must have NEON 6197 if (!S.Context.getTargetInfo().hasFeature("neon")) { 6198 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName(); 6199 Attr.setInvalid(); 6200 return; 6201 } 6202 // Check the attribute arguments. 6203 if (Attr.getNumArgs() != 1) { 6204 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6205 << Attr.getName() << 1; 6206 Attr.setInvalid(); 6207 return; 6208 } 6209 // The number of elements must be an ICE. 6210 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6211 llvm::APSInt numEltsInt(32); 6212 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 6213 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 6214 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6215 << Attr.getName() << AANT_ArgumentIntegerConstant 6216 << numEltsExpr->getSourceRange(); 6217 Attr.setInvalid(); 6218 return; 6219 } 6220 // Only certain element types are supported for Neon vectors. 6221 if (!isPermittedNeonBaseType(CurType, VecKind, S)) { 6222 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 6223 Attr.setInvalid(); 6224 return; 6225 } 6226 6227 // The total size of the vector must be 64 or 128 bits. 6228 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 6229 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 6230 unsigned vecSize = typeSize * numElts; 6231 if (vecSize != 64 && vecSize != 128) { 6232 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 6233 Attr.setInvalid(); 6234 return; 6235 } 6236 6237 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 6238 } 6239 6240 /// Handle OpenCL Access Qualifier Attribute. 6241 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr, 6242 Sema &S) { 6243 // OpenCL v2.0 s6.6 - Access qualifier can used only for image and pipe type. 6244 if (!(CurType->isImageType() || CurType->isPipeType())) { 6245 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); 6246 Attr.setInvalid(); 6247 return; 6248 } 6249 } 6250 6251 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 6252 TypeAttrLocation TAL, AttributeList *attrs) { 6253 // Scan through and apply attributes to this type where it makes sense. Some 6254 // attributes (such as __address_space__, __vector_size__, etc) apply to the 6255 // type, but others can be present in the type specifiers even though they 6256 // apply to the decl. Here we apply type attributes and ignore the rest. 6257 6258 bool hasOpenCLAddressSpace = false; 6259 while (attrs) { 6260 AttributeList &attr = *attrs; 6261 attrs = attr.getNext(); // reset to the next here due to early loop continue 6262 // stmts 6263 6264 // Skip attributes that were marked to be invalid. 6265 if (attr.isInvalid()) 6266 continue; 6267 6268 if (attr.isCXX11Attribute()) { 6269 // [[gnu::...]] attributes are treated as declaration attributes, so may 6270 // not appertain to a DeclaratorChunk, even if we handle them as type 6271 // attributes. 6272 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) { 6273 if (TAL == TAL_DeclChunk) { 6274 state.getSema().Diag(attr.getLoc(), 6275 diag::warn_cxx11_gnu_attribute_on_type) 6276 << attr.getName(); 6277 continue; 6278 } 6279 } else if (TAL != TAL_DeclChunk) { 6280 // Otherwise, only consider type processing for a C++11 attribute if 6281 // it's actually been applied to a type. 6282 continue; 6283 } 6284 } 6285 6286 // If this is an attribute we can handle, do so now, 6287 // otherwise, add it to the FnAttrs list for rechaining. 6288 switch (attr.getKind()) { 6289 default: 6290 // A C++11 attribute on a declarator chunk must appertain to a type. 6291 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { 6292 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 6293 << attr.getName(); 6294 attr.setUsedAsTypeAttr(); 6295 } 6296 break; 6297 6298 case AttributeList::UnknownAttribute: 6299 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 6300 state.getSema().Diag(attr.getLoc(), 6301 diag::warn_unknown_attribute_ignored) 6302 << attr.getName(); 6303 break; 6304 6305 case AttributeList::IgnoredAttribute: 6306 break; 6307 6308 case AttributeList::AT_MayAlias: 6309 // FIXME: This attribute needs to actually be handled, but if we ignore 6310 // it it breaks large amounts of Linux software. 6311 attr.setUsedAsTypeAttr(); 6312 break; 6313 case AttributeList::AT_OpenCLPrivateAddressSpace: 6314 case AttributeList::AT_OpenCLGlobalAddressSpace: 6315 case AttributeList::AT_OpenCLLocalAddressSpace: 6316 case AttributeList::AT_OpenCLConstantAddressSpace: 6317 case AttributeList::AT_OpenCLGenericAddressSpace: 6318 case AttributeList::AT_AddressSpace: 6319 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 6320 attr.setUsedAsTypeAttr(); 6321 hasOpenCLAddressSpace = true; 6322 break; 6323 OBJC_POINTER_TYPE_ATTRS_CASELIST: 6324 if (!handleObjCPointerTypeAttr(state, attr, type)) 6325 distributeObjCPointerTypeAttr(state, attr, type); 6326 attr.setUsedAsTypeAttr(); 6327 break; 6328 case AttributeList::AT_VectorSize: 6329 HandleVectorSizeAttr(type, attr, state.getSema()); 6330 attr.setUsedAsTypeAttr(); 6331 break; 6332 case AttributeList::AT_ExtVectorType: 6333 HandleExtVectorTypeAttr(type, attr, state.getSema()); 6334 attr.setUsedAsTypeAttr(); 6335 break; 6336 case AttributeList::AT_NeonVectorType: 6337 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 6338 VectorType::NeonVector); 6339 attr.setUsedAsTypeAttr(); 6340 break; 6341 case AttributeList::AT_NeonPolyVectorType: 6342 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 6343 VectorType::NeonPolyVector); 6344 attr.setUsedAsTypeAttr(); 6345 break; 6346 case AttributeList::AT_OpenCLAccess: 6347 HandleOpenCLAccessAttr(type, attr, state.getSema()); 6348 attr.setUsedAsTypeAttr(); 6349 break; 6350 6351 MS_TYPE_ATTRS_CASELIST: 6352 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 6353 attr.setUsedAsTypeAttr(); 6354 break; 6355 6356 6357 NULLABILITY_TYPE_ATTRS_CASELIST: 6358 // Either add nullability here or try to distribute it. We 6359 // don't want to distribute the nullability specifier past any 6360 // dependent type, because that complicates the user model. 6361 if (type->canHaveNullability() || type->isDependentType() || 6362 !distributeNullabilityTypeAttr(state, type, attr)) { 6363 if (state.getSema().checkNullabilityTypeSpecifier( 6364 type, 6365 mapNullabilityAttrKind(attr.getKind()), 6366 attr.getLoc(), 6367 attr.isContextSensitiveKeywordAttribute())) { 6368 attr.setInvalid(); 6369 } 6370 6371 attr.setUsedAsTypeAttr(); 6372 } 6373 break; 6374 6375 case AttributeList::AT_ObjCKindOf: 6376 // '__kindof' must be part of the decl-specifiers. 6377 switch (TAL) { 6378 case TAL_DeclSpec: 6379 break; 6380 6381 case TAL_DeclChunk: 6382 case TAL_DeclName: 6383 state.getSema().Diag(attr.getLoc(), 6384 diag::err_objc_kindof_wrong_position) 6385 << FixItHint::CreateRemoval(attr.getLoc()) 6386 << FixItHint::CreateInsertion( 6387 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof "); 6388 break; 6389 } 6390 6391 // Apply it regardless. 6392 if (state.getSema().checkObjCKindOfType(type, attr.getLoc())) 6393 attr.setInvalid(); 6394 attr.setUsedAsTypeAttr(); 6395 break; 6396 6397 case AttributeList::AT_NSReturnsRetained: 6398 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 6399 break; 6400 // fallthrough into the function attrs 6401 6402 FUNCTION_TYPE_ATTRS_CASELIST: 6403 attr.setUsedAsTypeAttr(); 6404 6405 // Never process function type attributes as part of the 6406 // declaration-specifiers. 6407 if (TAL == TAL_DeclSpec) 6408 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 6409 6410 // Otherwise, handle the possible delays. 6411 else if (!handleFunctionTypeAttr(state, attr, type)) 6412 distributeFunctionTypeAttr(state, attr, type); 6413 break; 6414 } 6415 } 6416 6417 // If address space is not set, OpenCL 2.0 defines non private default 6418 // address spaces for some cases: 6419 // OpenCL 2.0, section 6.5: 6420 // The address space for a variable at program scope or a static variable 6421 // inside a function can either be __global or __constant, but defaults to 6422 // __global if not specified. 6423 // (...) 6424 // Pointers that are declared without pointing to a named address space point 6425 // to the generic address space. 6426 if (state.getSema().getLangOpts().OpenCLVersion >= 200 && 6427 !hasOpenCLAddressSpace && type.getAddressSpace() == 0 && 6428 (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) { 6429 Declarator &D = state.getDeclarator(); 6430 if (state.getCurrentChunkIndex() > 0 && 6431 D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind == 6432 DeclaratorChunk::Pointer) { 6433 type = state.getSema().Context.getAddrSpaceQualType( 6434 type, LangAS::opencl_generic); 6435 } else if (state.getCurrentChunkIndex() == 0 && 6436 D.getContext() == Declarator::FileContext && 6437 !D.isFunctionDeclarator() && !D.isFunctionDefinition() && 6438 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6439 !type->isSamplerT()) 6440 type = state.getSema().Context.getAddrSpaceQualType( 6441 type, LangAS::opencl_global); 6442 else if (state.getCurrentChunkIndex() == 0 && 6443 D.getContext() == Declarator::BlockContext && 6444 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) 6445 type = state.getSema().Context.getAddrSpaceQualType( 6446 type, LangAS::opencl_global); 6447 } 6448 } 6449 6450 void Sema::completeExprArrayBound(Expr *E) { 6451 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 6452 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 6453 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { 6454 SourceLocation PointOfInstantiation = E->getExprLoc(); 6455 6456 if (MemberSpecializationInfo *MSInfo = 6457 Var->getMemberSpecializationInfo()) { 6458 // If we don't already have a point of instantiation, this is it. 6459 if (MSInfo->getPointOfInstantiation().isInvalid()) { 6460 MSInfo->setPointOfInstantiation(PointOfInstantiation); 6461 6462 // This is a modification of an existing AST node. Notify 6463 // listeners. 6464 if (ASTMutationListener *L = getASTMutationListener()) 6465 L->StaticDataMemberInstantiated(Var); 6466 } 6467 } else { 6468 VarTemplateSpecializationDecl *VarSpec = 6469 cast<VarTemplateSpecializationDecl>(Var); 6470 if (VarSpec->getPointOfInstantiation().isInvalid()) 6471 VarSpec->setPointOfInstantiation(PointOfInstantiation); 6472 } 6473 6474 InstantiateVariableDefinition(PointOfInstantiation, Var); 6475 6476 // Update the type to the newly instantiated definition's type both 6477 // here and within the expression. 6478 if (VarDecl *Def = Var->getDefinition()) { 6479 DRE->setDecl(Def); 6480 QualType T = Def->getType(); 6481 DRE->setType(T); 6482 // FIXME: Update the type on all intervening expressions. 6483 E->setType(T); 6484 } 6485 6486 // We still go on to try to complete the type independently, as it 6487 // may also require instantiations or diagnostics if it remains 6488 // incomplete. 6489 } 6490 } 6491 } 6492 } 6493 6494 /// \brief Ensure that the type of the given expression is complete. 6495 /// 6496 /// This routine checks whether the expression \p E has a complete type. If the 6497 /// expression refers to an instantiable construct, that instantiation is 6498 /// performed as needed to complete its type. Furthermore 6499 /// Sema::RequireCompleteType is called for the expression's type (or in the 6500 /// case of a reference type, the referred-to type). 6501 /// 6502 /// \param E The expression whose type is required to be complete. 6503 /// \param Diagnoser The object that will emit a diagnostic if the type is 6504 /// incomplete. 6505 /// 6506 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 6507 /// otherwise. 6508 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) { 6509 QualType T = E->getType(); 6510 6511 // Incomplete array types may be completed by the initializer attached to 6512 // their definitions. For static data members of class templates and for 6513 // variable templates, we need to instantiate the definition to get this 6514 // initializer and complete the type. 6515 if (T->isIncompleteArrayType()) { 6516 completeExprArrayBound(E); 6517 T = E->getType(); 6518 } 6519 6520 // FIXME: Are there other cases which require instantiating something other 6521 // than the type to complete the type of an expression? 6522 6523 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 6524 } 6525 6526 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 6527 BoundTypeDiagnoser<> Diagnoser(DiagID); 6528 return RequireCompleteExprType(E, Diagnoser); 6529 } 6530 6531 /// @brief Ensure that the type T is a complete type. 6532 /// 6533 /// This routine checks whether the type @p T is complete in any 6534 /// context where a complete type is required. If @p T is a complete 6535 /// type, returns false. If @p T is a class template specialization, 6536 /// this routine then attempts to perform class template 6537 /// instantiation. If instantiation fails, or if @p T is incomplete 6538 /// and cannot be completed, issues the diagnostic @p diag (giving it 6539 /// the type @p T) and returns true. 6540 /// 6541 /// @param Loc The location in the source that the incomplete type 6542 /// diagnostic should refer to. 6543 /// 6544 /// @param T The type that this routine is examining for completeness. 6545 /// 6546 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 6547 /// @c false otherwise. 6548 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 6549 TypeDiagnoser &Diagnoser) { 6550 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser)) 6551 return true; 6552 if (const TagType *Tag = T->getAs<TagType>()) { 6553 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 6554 Tag->getDecl()->setCompleteDefinitionRequired(); 6555 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 6556 } 6557 } 6558 return false; 6559 } 6560 6561 /// \brief Determine whether there is any declaration of \p D that was ever a 6562 /// definition (perhaps before module merging) and is currently visible. 6563 /// \param D The definition of the entity. 6564 /// \param Suggested Filled in with the declaration that should be made visible 6565 /// in order to provide a definition of this entity. 6566 /// \param OnlyNeedComplete If \c true, we only need the type to be complete, 6567 /// not defined. This only matters for enums with a fixed underlying 6568 /// type, since in all other cases, a type is complete if and only if it 6569 /// is defined. 6570 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 6571 bool OnlyNeedComplete) { 6572 // Easy case: if we don't have modules, all declarations are visible. 6573 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) 6574 return true; 6575 6576 // If this definition was instantiated from a template, map back to the 6577 // pattern from which it was instantiated. 6578 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { 6579 // We're in the middle of defining it; this definition should be treated 6580 // as visible. 6581 return true; 6582 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 6583 if (auto *Pattern = RD->getTemplateInstantiationPattern()) 6584 RD = Pattern; 6585 D = RD->getDefinition(); 6586 } else if (auto *ED = dyn_cast<EnumDecl>(D)) { 6587 while (auto *NewED = ED->getInstantiatedFromMemberEnum()) 6588 ED = NewED; 6589 if (OnlyNeedComplete && ED->isFixed()) { 6590 // If the enum has a fixed underlying type, and we're only looking for a 6591 // complete type (not a definition), any visible declaration of it will 6592 // do. 6593 *Suggested = nullptr; 6594 for (auto *Redecl : ED->redecls()) { 6595 if (isVisible(Redecl)) 6596 return true; 6597 if (Redecl->isThisDeclarationADefinition() || 6598 (Redecl->isCanonicalDecl() && !*Suggested)) 6599 *Suggested = Redecl; 6600 } 6601 return false; 6602 } 6603 D = ED->getDefinition(); 6604 } 6605 assert(D && "missing definition for pattern of instantiated definition"); 6606 6607 *Suggested = D; 6608 if (isVisible(D)) 6609 return true; 6610 6611 // The external source may have additional definitions of this type that are 6612 // visible, so complete the redeclaration chain now and ask again. 6613 if (auto *Source = Context.getExternalSource()) { 6614 Source->CompleteRedeclChain(D); 6615 return isVisible(D); 6616 } 6617 6618 return false; 6619 } 6620 6621 /// Locks in the inheritance model for the given class and all of its bases. 6622 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { 6623 RD = RD->getMostRecentDecl(); 6624 if (!RD->hasAttr<MSInheritanceAttr>()) { 6625 MSInheritanceAttr::Spelling IM; 6626 6627 switch (S.MSPointerToMemberRepresentationMethod) { 6628 case LangOptions::PPTMK_BestCase: 6629 IM = RD->calculateInheritanceModel(); 6630 break; 6631 case LangOptions::PPTMK_FullGeneralitySingleInheritance: 6632 IM = MSInheritanceAttr::Keyword_single_inheritance; 6633 break; 6634 case LangOptions::PPTMK_FullGeneralityMultipleInheritance: 6635 IM = MSInheritanceAttr::Keyword_multiple_inheritance; 6636 break; 6637 case LangOptions::PPTMK_FullGeneralityVirtualInheritance: 6638 IM = MSInheritanceAttr::Keyword_unspecified_inheritance; 6639 break; 6640 } 6641 6642 RD->addAttr(MSInheritanceAttr::CreateImplicit( 6643 S.getASTContext(), IM, 6644 /*BestCase=*/S.MSPointerToMemberRepresentationMethod == 6645 LangOptions::PPTMK_BestCase, 6646 S.ImplicitMSInheritanceAttrLoc.isValid() 6647 ? S.ImplicitMSInheritanceAttrLoc 6648 : RD->getSourceRange())); 6649 S.Consumer.AssignInheritanceModel(RD); 6650 } 6651 } 6652 6653 /// \brief The implementation of RequireCompleteType 6654 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 6655 TypeDiagnoser *Diagnoser) { 6656 // FIXME: Add this assertion to make sure we always get instantiation points. 6657 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 6658 // FIXME: Add this assertion to help us flush out problems with 6659 // checking for dependent types and type-dependent expressions. 6660 // 6661 // assert(!T->isDependentType() && 6662 // "Can't ask whether a dependent type is complete"); 6663 6664 // We lock in the inheritance model once somebody has asked us to ensure 6665 // that a pointer-to-member type is complete. 6666 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 6667 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { 6668 if (!MPTy->getClass()->isDependentType()) { 6669 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); 6670 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); 6671 } 6672 } 6673 } 6674 6675 // If we have a complete type, we're done. 6676 NamedDecl *Def = nullptr; 6677 if (!T->isIncompleteType(&Def)) { 6678 // If we know about the definition but it is not visible, complain. 6679 NamedDecl *SuggestedDef = nullptr; 6680 if (Def && 6681 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { 6682 // If the user is going to see an error here, recover by making the 6683 // definition visible. 6684 bool TreatAsComplete = Diagnoser && !isSFINAEContext(); 6685 if (Diagnoser) 6686 diagnoseMissingImport(Loc, SuggestedDef, /*NeedDefinition*/true, 6687 /*Recover*/TreatAsComplete); 6688 return !TreatAsComplete; 6689 } 6690 6691 return false; 6692 } 6693 6694 const TagType *Tag = T->getAs<TagType>(); 6695 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>(); 6696 6697 // If there's an unimported definition of this type in a module (for 6698 // instance, because we forward declared it, then imported the definition), 6699 // import that definition now. 6700 // 6701 // FIXME: What about other cases where an import extends a redeclaration 6702 // chain for a declaration that can be accessed through a mechanism other 6703 // than name lookup (eg, referenced in a template, or a variable whose type 6704 // could be completed by the module)? 6705 // 6706 // FIXME: Should we map through to the base array element type before 6707 // checking for a tag type? 6708 if (Tag || IFace) { 6709 NamedDecl *D = 6710 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl(); 6711 6712 // Avoid diagnosing invalid decls as incomplete. 6713 if (D->isInvalidDecl()) 6714 return true; 6715 6716 // Give the external AST source a chance to complete the type. 6717 if (auto *Source = Context.getExternalSource()) { 6718 if (Tag) 6719 Source->CompleteType(Tag->getDecl()); 6720 else 6721 Source->CompleteType(IFace->getDecl()); 6722 6723 // If the external source completed the type, go through the motions 6724 // again to ensure we're allowed to use the completed type. 6725 if (!T->isIncompleteType()) 6726 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 6727 } 6728 } 6729 6730 // If we have a class template specialization or a class member of a 6731 // class template specialization, or an array with known size of such, 6732 // try to instantiate it. 6733 QualType MaybeTemplate = T; 6734 while (const ConstantArrayType *Array 6735 = Context.getAsConstantArrayType(MaybeTemplate)) 6736 MaybeTemplate = Array->getElementType(); 6737 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 6738 bool Instantiated = false; 6739 bool Diagnosed = false; 6740 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 6741 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 6742 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 6743 Diagnosed = InstantiateClassTemplateSpecialization( 6744 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, 6745 /*Complain=*/Diagnoser); 6746 Instantiated = true; 6747 } 6748 } else if (CXXRecordDecl *Rec 6749 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 6750 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); 6751 if (!Rec->isBeingDefined() && Pattern) { 6752 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); 6753 assert(MSI && "Missing member specialization information?"); 6754 // This record was instantiated from a class within a template. 6755 if (MSI->getTemplateSpecializationKind() != 6756 TSK_ExplicitSpecialization) { 6757 Diagnosed = InstantiateClass(Loc, Rec, Pattern, 6758 getTemplateInstantiationArgs(Rec), 6759 TSK_ImplicitInstantiation, 6760 /*Complain=*/Diagnoser); 6761 Instantiated = true; 6762 } 6763 } 6764 } 6765 6766 if (Instantiated) { 6767 // Instantiate* might have already complained that the template is not 6768 // defined, if we asked it to. 6769 if (Diagnoser && Diagnosed) 6770 return true; 6771 // If we instantiated a definition, check that it's usable, even if 6772 // instantiation produced an error, so that repeated calls to this 6773 // function give consistent answers. 6774 if (!T->isIncompleteType()) 6775 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 6776 } 6777 } 6778 6779 if (!Diagnoser) 6780 return true; 6781 6782 // We have an incomplete type. Produce a diagnostic. 6783 if (Ident___float128 && 6784 T == Context.getTypeDeclType(Context.getFloat128StubType())) { 6785 Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128); 6786 return true; 6787 } 6788 6789 Diagnoser->diagnose(*this, Loc, T); 6790 6791 // If the type was a forward declaration of a class/struct/union 6792 // type, produce a note. 6793 if (Tag && !Tag->getDecl()->isInvalidDecl()) 6794 Diag(Tag->getDecl()->getLocation(), 6795 Tag->isBeingDefined() ? diag::note_type_being_defined 6796 : diag::note_forward_declaration) 6797 << QualType(Tag, 0); 6798 6799 // If the Objective-C class was a forward declaration, produce a note. 6800 if (IFace && !IFace->getDecl()->isInvalidDecl()) 6801 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); 6802 6803 // If we have external information that we can use to suggest a fix, 6804 // produce a note. 6805 if (ExternalSource) 6806 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); 6807 6808 return true; 6809 } 6810 6811 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 6812 unsigned DiagID) { 6813 BoundTypeDiagnoser<> Diagnoser(DiagID); 6814 return RequireCompleteType(Loc, T, Diagnoser); 6815 } 6816 6817 /// \brief Get diagnostic %select index for tag kind for 6818 /// literal type diagnostic message. 6819 /// WARNING: Indexes apply to particular diagnostics only! 6820 /// 6821 /// \returns diagnostic %select index. 6822 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 6823 switch (Tag) { 6824 case TTK_Struct: return 0; 6825 case TTK_Interface: return 1; 6826 case TTK_Class: return 2; 6827 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 6828 } 6829 } 6830 6831 /// @brief Ensure that the type T is a literal type. 6832 /// 6833 /// This routine checks whether the type @p T is a literal type. If @p T is an 6834 /// incomplete type, an attempt is made to complete it. If @p T is a literal 6835 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 6836 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 6837 /// it the type @p T), along with notes explaining why the type is not a 6838 /// literal type, and returns true. 6839 /// 6840 /// @param Loc The location in the source that the non-literal type 6841 /// diagnostic should refer to. 6842 /// 6843 /// @param T The type that this routine is examining for literalness. 6844 /// 6845 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 6846 /// 6847 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 6848 /// @c false otherwise. 6849 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 6850 TypeDiagnoser &Diagnoser) { 6851 assert(!T->isDependentType() && "type should not be dependent"); 6852 6853 QualType ElemType = Context.getBaseElementType(T); 6854 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && 6855 T->isLiteralType(Context)) 6856 return false; 6857 6858 Diagnoser.diagnose(*this, Loc, T); 6859 6860 if (T->isVariableArrayType()) 6861 return true; 6862 6863 const RecordType *RT = ElemType->getAs<RecordType>(); 6864 if (!RT) 6865 return true; 6866 6867 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 6868 6869 // A partially-defined class type can't be a literal type, because a literal 6870 // class type must have a trivial destructor (which can't be checked until 6871 // the class definition is complete). 6872 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) 6873 return true; 6874 6875 // If the class has virtual base classes, then it's not an aggregate, and 6876 // cannot have any constexpr constructors or a trivial default constructor, 6877 // so is non-literal. This is better to diagnose than the resulting absence 6878 // of constexpr constructors. 6879 if (RD->getNumVBases()) { 6880 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 6881 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 6882 for (const auto &I : RD->vbases()) 6883 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here) 6884 << I.getSourceRange(); 6885 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 6886 !RD->hasTrivialDefaultConstructor()) { 6887 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 6888 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 6889 for (const auto &I : RD->bases()) { 6890 if (!I.getType()->isLiteralType(Context)) { 6891 Diag(I.getLocStart(), 6892 diag::note_non_literal_base_class) 6893 << RD << I.getType() << I.getSourceRange(); 6894 return true; 6895 } 6896 } 6897 for (const auto *I : RD->fields()) { 6898 if (!I->getType()->isLiteralType(Context) || 6899 I->getType().isVolatileQualified()) { 6900 Diag(I->getLocation(), diag::note_non_literal_field) 6901 << RD << I << I->getType() 6902 << I->getType().isVolatileQualified(); 6903 return true; 6904 } 6905 } 6906 } else if (!RD->hasTrivialDestructor()) { 6907 // All fields and bases are of literal types, so have trivial destructors. 6908 // If this class's destructor is non-trivial it must be user-declared. 6909 CXXDestructorDecl *Dtor = RD->getDestructor(); 6910 assert(Dtor && "class has literal fields and bases but no dtor?"); 6911 if (!Dtor) 6912 return true; 6913 6914 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 6915 diag::note_non_literal_user_provided_dtor : 6916 diag::note_non_literal_nontrivial_dtor) << RD; 6917 if (!Dtor->isUserProvided()) 6918 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true); 6919 } 6920 6921 return true; 6922 } 6923 6924 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 6925 BoundTypeDiagnoser<> Diagnoser(DiagID); 6926 return RequireLiteralType(Loc, T, Diagnoser); 6927 } 6928 6929 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 6930 /// and qualified by the nested-name-specifier contained in SS. 6931 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 6932 const CXXScopeSpec &SS, QualType T) { 6933 if (T.isNull()) 6934 return T; 6935 NestedNameSpecifier *NNS; 6936 if (SS.isValid()) 6937 NNS = SS.getScopeRep(); 6938 else { 6939 if (Keyword == ETK_None) 6940 return T; 6941 NNS = nullptr; 6942 } 6943 return Context.getElaboratedType(Keyword, NNS, T); 6944 } 6945 6946 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 6947 ExprResult ER = CheckPlaceholderExpr(E); 6948 if (ER.isInvalid()) return QualType(); 6949 E = ER.get(); 6950 6951 if (!getLangOpts().CPlusPlus && E->refersToBitField()) 6952 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; 6953 6954 if (!E->isTypeDependent()) { 6955 QualType T = E->getType(); 6956 if (const TagType *TT = T->getAs<TagType>()) 6957 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 6958 } 6959 return Context.getTypeOfExprType(E); 6960 } 6961 6962 /// getDecltypeForExpr - Given an expr, will return the decltype for 6963 /// that expression, according to the rules in C++11 6964 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 6965 static QualType getDecltypeForExpr(Sema &S, Expr *E) { 6966 if (E->isTypeDependent()) 6967 return S.Context.DependentTy; 6968 6969 // C++11 [dcl.type.simple]p4: 6970 // The type denoted by decltype(e) is defined as follows: 6971 // 6972 // - if e is an unparenthesized id-expression or an unparenthesized class 6973 // member access (5.2.5), decltype(e) is the type of the entity named 6974 // by e. If there is no such entity, or if e names a set of overloaded 6975 // functions, the program is ill-formed; 6976 // 6977 // We apply the same rules for Objective-C ivar and property references. 6978 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 6979 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 6980 return VD->getType(); 6981 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 6982 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 6983 return FD->getType(); 6984 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { 6985 return IR->getDecl()->getType(); 6986 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { 6987 if (PR->isExplicitProperty()) 6988 return PR->getExplicitProperty()->getType(); 6989 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { 6990 return PE->getType(); 6991 } 6992 6993 // C++11 [expr.lambda.prim]p18: 6994 // Every occurrence of decltype((x)) where x is a possibly 6995 // parenthesized id-expression that names an entity of automatic 6996 // storage duration is treated as if x were transformed into an 6997 // access to a corresponding data member of the closure type that 6998 // would have been declared if x were an odr-use of the denoted 6999 // entity. 7000 using namespace sema; 7001 if (S.getCurLambda()) { 7002 if (isa<ParenExpr>(E)) { 7003 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 7004 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 7005 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 7006 if (!T.isNull()) 7007 return S.Context.getLValueReferenceType(T); 7008 } 7009 } 7010 } 7011 } 7012 7013 7014 // C++11 [dcl.type.simple]p4: 7015 // [...] 7016 QualType T = E->getType(); 7017 switch (E->getValueKind()) { 7018 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 7019 // type of e; 7020 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 7021 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 7022 // type of e; 7023 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 7024 // - otherwise, decltype(e) is the type of e. 7025 case VK_RValue: break; 7026 } 7027 7028 return T; 7029 } 7030 7031 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc, 7032 bool AsUnevaluated) { 7033 ExprResult ER = CheckPlaceholderExpr(E); 7034 if (ER.isInvalid()) return QualType(); 7035 E = ER.get(); 7036 7037 if (AsUnevaluated && ActiveTemplateInstantiations.empty() && 7038 E->HasSideEffects(Context, false)) { 7039 // The expression operand for decltype is in an unevaluated expression 7040 // context, so side effects could result in unintended consequences. 7041 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 7042 } 7043 7044 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 7045 } 7046 7047 QualType Sema::BuildUnaryTransformType(QualType BaseType, 7048 UnaryTransformType::UTTKind UKind, 7049 SourceLocation Loc) { 7050 switch (UKind) { 7051 case UnaryTransformType::EnumUnderlyingType: 7052 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 7053 Diag(Loc, diag::err_only_enums_have_underlying_types); 7054 return QualType(); 7055 } else { 7056 QualType Underlying = BaseType; 7057 if (!BaseType->isDependentType()) { 7058 // The enum could be incomplete if we're parsing its definition or 7059 // recovering from an error. 7060 NamedDecl *FwdDecl = nullptr; 7061 if (BaseType->isIncompleteType(&FwdDecl)) { 7062 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; 7063 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; 7064 return QualType(); 7065 } 7066 7067 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 7068 assert(ED && "EnumType has no EnumDecl"); 7069 7070 DiagnoseUseOfDecl(ED, Loc); 7071 7072 Underlying = ED->getIntegerType(); 7073 assert(!Underlying.isNull()); 7074 } 7075 return Context.getUnaryTransformType(BaseType, Underlying, 7076 UnaryTransformType::EnumUnderlyingType); 7077 } 7078 } 7079 llvm_unreachable("unknown unary transform type"); 7080 } 7081 7082 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 7083 if (!T->isDependentType()) { 7084 // FIXME: It isn't entirely clear whether incomplete atomic types 7085 // are allowed or not; for simplicity, ban them for the moment. 7086 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 7087 return QualType(); 7088 7089 int DisallowedKind = -1; 7090 if (T->isArrayType()) 7091 DisallowedKind = 1; 7092 else if (T->isFunctionType()) 7093 DisallowedKind = 2; 7094 else if (T->isReferenceType()) 7095 DisallowedKind = 3; 7096 else if (T->isAtomicType()) 7097 DisallowedKind = 4; 7098 else if (T.hasQualifiers()) 7099 DisallowedKind = 5; 7100 else if (!T.isTriviallyCopyableType(Context)) 7101 // Some other non-trivially-copyable type (probably a C++ class) 7102 DisallowedKind = 6; 7103 7104 if (DisallowedKind != -1) { 7105 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 7106 return QualType(); 7107 } 7108 7109 // FIXME: Do we need any handling for ARC here? 7110 } 7111 7112 // Build the pointer type. 7113 return Context.getAtomicType(T); 7114 } 7115