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