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