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