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