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