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 = 4493 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin(); 4494 4495 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 4496 << T.getQualifiers().getObjCLifetime(); 4497 } 4498 } 4499 4500 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { 4501 // C++ [dcl.fct]p6: 4502 // Types shall not be defined in return or parameter types. 4503 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 4504 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 4505 << Context.getTypeDeclType(Tag); 4506 } 4507 4508 // Exception specs are not allowed in typedefs. Complain, but add it 4509 // anyway. 4510 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17) 4511 S.Diag(FTI.getExceptionSpecLocBeg(), 4512 diag::err_exception_spec_in_typedef) 4513 << (D.getContext() == DeclaratorContext::AliasDeclContext || 4514 D.getContext() == DeclaratorContext::AliasTemplateContext); 4515 4516 // If we see "T var();" or "T var(T());" at block scope, it is probably 4517 // an attempt to initialize a variable, not a function declaration. 4518 if (FTI.isAmbiguous) 4519 warnAboutAmbiguousFunction(S, D, DeclType, T); 4520 4521 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex)); 4522 4523 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus 4524 && !LangOpts.OpenCL) { 4525 // Simple void foo(), where the incoming T is the result type. 4526 T = Context.getFunctionNoProtoType(T, EI); 4527 } else { 4528 // We allow a zero-parameter variadic function in C if the 4529 // function is marked with the "overloadable" attribute. Scan 4530 // for this attribute now. 4531 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) { 4532 bool Overloadable = false; 4533 for (const AttributeList *Attrs = D.getAttributes(); 4534 Attrs; Attrs = Attrs->getNext()) { 4535 if (Attrs->getKind() == AttributeList::AT_Overloadable) { 4536 Overloadable = true; 4537 break; 4538 } 4539 } 4540 4541 if (!Overloadable) 4542 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); 4543 } 4544 4545 if (FTI.NumParams && FTI.Params[0].Param == nullptr) { 4546 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 4547 // definition. 4548 S.Diag(FTI.Params[0].IdentLoc, 4549 diag::err_ident_list_in_fn_declaration); 4550 D.setInvalidType(true); 4551 // Recover by creating a K&R-style function type. 4552 T = Context.getFunctionNoProtoType(T, EI); 4553 break; 4554 } 4555 4556 FunctionProtoType::ExtProtoInfo EPI; 4557 EPI.ExtInfo = EI; 4558 EPI.Variadic = FTI.isVariadic; 4559 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 4560 EPI.TypeQuals = FTI.TypeQuals; 4561 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 4562 : FTI.RefQualifierIsLValueRef? RQ_LValue 4563 : RQ_RValue; 4564 4565 // Otherwise, we have a function with a parameter list that is 4566 // potentially variadic. 4567 SmallVector<QualType, 16> ParamTys; 4568 ParamTys.reserve(FTI.NumParams); 4569 4570 SmallVector<FunctionProtoType::ExtParameterInfo, 16> 4571 ExtParameterInfos(FTI.NumParams); 4572 bool HasAnyInterestingExtParameterInfos = false; 4573 4574 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 4575 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 4576 QualType ParamTy = Param->getType(); 4577 assert(!ParamTy.isNull() && "Couldn't parse type?"); 4578 4579 // Look for 'void'. void is allowed only as a single parameter to a 4580 // function with no other parameters (C99 6.7.5.3p10). We record 4581 // int(void) as a FunctionProtoType with an empty parameter list. 4582 if (ParamTy->isVoidType()) { 4583 // If this is something like 'float(int, void)', reject it. 'void' 4584 // is an incomplete type (C99 6.2.5p19) and function decls cannot 4585 // have parameters of incomplete type. 4586 if (FTI.NumParams != 1 || FTI.isVariadic) { 4587 S.Diag(DeclType.Loc, diag::err_void_only_param); 4588 ParamTy = Context.IntTy; 4589 Param->setType(ParamTy); 4590 } else if (FTI.Params[i].Ident) { 4591 // Reject, but continue to parse 'int(void abc)'. 4592 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); 4593 ParamTy = Context.IntTy; 4594 Param->setType(ParamTy); 4595 } else { 4596 // Reject, but continue to parse 'float(const void)'. 4597 if (ParamTy.hasQualifiers()) 4598 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 4599 4600 // Do not add 'void' to the list. 4601 break; 4602 } 4603 } else if (ParamTy->isHalfType()) { 4604 // Disallow half FP parameters. 4605 // FIXME: This really should be in BuildFunctionType. 4606 if (S.getLangOpts().OpenCL) { 4607 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 4608 S.Diag(Param->getLocation(), 4609 diag::err_opencl_half_param) << ParamTy; 4610 D.setInvalidType(); 4611 Param->setInvalidDecl(); 4612 } 4613 } else if (!S.getLangOpts().HalfArgsAndReturns) { 4614 S.Diag(Param->getLocation(), 4615 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 4616 D.setInvalidType(); 4617 } 4618 } else if (!FTI.hasPrototype) { 4619 if (ParamTy->isPromotableIntegerType()) { 4620 ParamTy = Context.getPromotedIntegerType(ParamTy); 4621 Param->setKNRPromoted(true); 4622 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { 4623 if (BTy->getKind() == BuiltinType::Float) { 4624 ParamTy = Context.DoubleTy; 4625 Param->setKNRPromoted(true); 4626 } 4627 } 4628 } 4629 4630 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { 4631 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); 4632 HasAnyInterestingExtParameterInfos = true; 4633 } 4634 4635 if (auto attr = Param->getAttr<ParameterABIAttr>()) { 4636 ExtParameterInfos[i] = 4637 ExtParameterInfos[i].withABI(attr->getABI()); 4638 HasAnyInterestingExtParameterInfos = true; 4639 } 4640 4641 if (Param->hasAttr<PassObjectSizeAttr>()) { 4642 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); 4643 HasAnyInterestingExtParameterInfos = true; 4644 } 4645 4646 if (Param->hasAttr<NoEscapeAttr>()) { 4647 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true); 4648 HasAnyInterestingExtParameterInfos = true; 4649 } 4650 4651 ParamTys.push_back(ParamTy); 4652 } 4653 4654 if (HasAnyInterestingExtParameterInfos) { 4655 EPI.ExtParameterInfos = ExtParameterInfos.data(); 4656 checkExtParameterInfos(S, ParamTys, EPI, 4657 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); 4658 } 4659 4660 SmallVector<QualType, 4> Exceptions; 4661 SmallVector<ParsedType, 2> DynamicExceptions; 4662 SmallVector<SourceRange, 2> DynamicExceptionRanges; 4663 Expr *NoexceptExpr = nullptr; 4664 4665 if (FTI.getExceptionSpecType() == EST_Dynamic) { 4666 // FIXME: It's rather inefficient to have to split into two vectors 4667 // here. 4668 unsigned N = FTI.getNumExceptions(); 4669 DynamicExceptions.reserve(N); 4670 DynamicExceptionRanges.reserve(N); 4671 for (unsigned I = 0; I != N; ++I) { 4672 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 4673 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 4674 } 4675 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 4676 NoexceptExpr = FTI.NoexceptExpr; 4677 } 4678 4679 S.checkExceptionSpecification(D.isFunctionDeclarationContext(), 4680 FTI.getExceptionSpecType(), 4681 DynamicExceptions, 4682 DynamicExceptionRanges, 4683 NoexceptExpr, 4684 Exceptions, 4685 EPI.ExceptionSpec); 4686 4687 T = Context.getFunctionType(T, ParamTys, EPI); 4688 } 4689 break; 4690 } 4691 case DeclaratorChunk::MemberPointer: { 4692 // The scope spec must refer to a class, or be dependent. 4693 CXXScopeSpec &SS = DeclType.Mem.Scope(); 4694 QualType ClsType; 4695 4696 // Handle pointer nullability. 4697 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc, 4698 DeclType.EndLoc, DeclType.getAttrListRef()); 4699 4700 if (SS.isInvalid()) { 4701 // Avoid emitting extra errors if we already errored on the scope. 4702 D.setInvalidType(true); 4703 } else if (S.isDependentScopeSpecifier(SS) || 4704 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 4705 NestedNameSpecifier *NNS = SS.getScopeRep(); 4706 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 4707 switch (NNS->getKind()) { 4708 case NestedNameSpecifier::Identifier: 4709 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 4710 NNS->getAsIdentifier()); 4711 break; 4712 4713 case NestedNameSpecifier::Namespace: 4714 case NestedNameSpecifier::NamespaceAlias: 4715 case NestedNameSpecifier::Global: 4716 case NestedNameSpecifier::Super: 4717 llvm_unreachable("Nested-name-specifier must name a type"); 4718 4719 case NestedNameSpecifier::TypeSpec: 4720 case NestedNameSpecifier::TypeSpecWithTemplate: 4721 ClsType = QualType(NNS->getAsType(), 0); 4722 // Note: if the NNS has a prefix and ClsType is a nondependent 4723 // TemplateSpecializationType, then the NNS prefix is NOT included 4724 // in ClsType; hence we wrap ClsType into an ElaboratedType. 4725 // NOTE: in particular, no wrap occurs if ClsType already is an 4726 // Elaborated, DependentName, or DependentTemplateSpecialization. 4727 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 4728 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 4729 break; 4730 } 4731 } else { 4732 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 4733 diag::err_illegal_decl_mempointer_in_nonclass) 4734 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 4735 << DeclType.Mem.Scope().getRange(); 4736 D.setInvalidType(true); 4737 } 4738 4739 if (!ClsType.isNull()) 4740 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, 4741 D.getIdentifier()); 4742 if (T.isNull()) { 4743 T = Context.IntTy; 4744 D.setInvalidType(true); 4745 } else if (DeclType.Mem.TypeQuals) { 4746 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 4747 } 4748 break; 4749 } 4750 4751 case DeclaratorChunk::Pipe: { 4752 T = S.BuildReadPipeType(T, DeclType.Loc); 4753 processTypeAttrs(state, T, TAL_DeclSpec, 4754 D.getDeclSpec().getAttributes().getList()); 4755 break; 4756 } 4757 } 4758 4759 if (T.isNull()) { 4760 D.setInvalidType(true); 4761 T = Context.IntTy; 4762 } 4763 4764 // See if there are any attributes on this declarator chunk. 4765 processTypeAttrs(state, T, TAL_DeclChunk, 4766 const_cast<AttributeList *>(DeclType.getAttrs())); 4767 } 4768 4769 // GNU warning -Wstrict-prototypes 4770 // Warn if a function declaration is without a prototype. 4771 // This warning is issued for all kinds of unprototyped function 4772 // declarations (i.e. function type typedef, function pointer etc.) 4773 // C99 6.7.5.3p14: 4774 // The empty list in a function declarator that is not part of a definition 4775 // of that function specifies that no information about the number or types 4776 // of the parameters is supplied. 4777 if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) { 4778 bool IsBlock = false; 4779 for (const DeclaratorChunk &DeclType : D.type_objects()) { 4780 switch (DeclType.Kind) { 4781 case DeclaratorChunk::BlockPointer: 4782 IsBlock = true; 4783 break; 4784 case DeclaratorChunk::Function: { 4785 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 4786 if (FTI.NumParams == 0 && !FTI.isVariadic) 4787 S.Diag(DeclType.Loc, diag::warn_strict_prototypes) 4788 << IsBlock 4789 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); 4790 IsBlock = false; 4791 break; 4792 } 4793 default: 4794 break; 4795 } 4796 } 4797 } 4798 4799 assert(!T.isNull() && "T must not be null after this point"); 4800 4801 if (LangOpts.CPlusPlus && T->isFunctionType()) { 4802 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 4803 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 4804 4805 // C++ 8.3.5p4: 4806 // A cv-qualifier-seq shall only be part of the function type 4807 // for a nonstatic member function, the function type to which a pointer 4808 // to member refers, or the top-level function type of a function typedef 4809 // declaration. 4810 // 4811 // Core issue 547 also allows cv-qualifiers on function types that are 4812 // top-level template type arguments. 4813 enum { NonMember, Member, DeductionGuide } Kind = NonMember; 4814 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) 4815 Kind = DeductionGuide; 4816 else if (!D.getCXXScopeSpec().isSet()) { 4817 if ((D.getContext() == DeclaratorContext::MemberContext || 4818 D.getContext() == DeclaratorContext::LambdaExprContext) && 4819 !D.getDeclSpec().isFriendSpecified()) 4820 Kind = Member; 4821 } else { 4822 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 4823 if (!DC || DC->isRecord()) 4824 Kind = Member; 4825 } 4826 4827 // C++11 [dcl.fct]p6 (w/DR1417): 4828 // An attempt to specify a function type with a cv-qualifier-seq or a 4829 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 4830 // - the function type for a non-static member function, 4831 // - the function type to which a pointer to member refers, 4832 // - the top-level function type of a function typedef declaration or 4833 // alias-declaration, 4834 // - the type-id in the default argument of a type-parameter, or 4835 // - the type-id of a template-argument for a type-parameter 4836 // 4837 // FIXME: Checking this here is insufficient. We accept-invalid on: 4838 // 4839 // template<typename T> struct S { void f(T); }; 4840 // S<int() const> s; 4841 // 4842 // ... for instance. 4843 if (IsQualifiedFunction && 4844 !(Kind == Member && 4845 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 4846 !IsTypedefName && 4847 D.getContext() != DeclaratorContext::TemplateArgContext && 4848 D.getContext() != DeclaratorContext::TemplateTypeArgContext) { 4849 SourceLocation Loc = D.getLocStart(); 4850 SourceRange RemovalRange; 4851 unsigned I; 4852 if (D.isFunctionDeclarator(I)) { 4853 SmallVector<SourceLocation, 4> RemovalLocs; 4854 const DeclaratorChunk &Chunk = D.getTypeObject(I); 4855 assert(Chunk.Kind == DeclaratorChunk::Function); 4856 if (Chunk.Fun.hasRefQualifier()) 4857 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 4858 if (Chunk.Fun.TypeQuals & Qualifiers::Const) 4859 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); 4860 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) 4861 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); 4862 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) 4863 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); 4864 if (!RemovalLocs.empty()) { 4865 llvm::sort(RemovalLocs.begin(), RemovalLocs.end(), 4866 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 4867 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 4868 Loc = RemovalLocs.front(); 4869 } 4870 } 4871 4872 S.Diag(Loc, diag::err_invalid_qualified_function_type) 4873 << Kind << D.isFunctionDeclarator() << T 4874 << getFunctionQualifiersAsString(FnTy) 4875 << FixItHint::CreateRemoval(RemovalRange); 4876 4877 // Strip the cv-qualifiers and ref-qualifiers from the type. 4878 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 4879 EPI.TypeQuals = 0; 4880 EPI.RefQualifier = RQ_None; 4881 4882 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), 4883 EPI); 4884 // Rebuild any parens around the identifier in the function type. 4885 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4886 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 4887 break; 4888 T = S.BuildParenType(T); 4889 } 4890 } 4891 } 4892 4893 // Apply any undistributed attributes from the declarator. 4894 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); 4895 4896 // Diagnose any ignored type attributes. 4897 state.diagnoseIgnoredTypeAttrs(T); 4898 4899 // C++0x [dcl.constexpr]p9: 4900 // A constexpr specifier used in an object declaration declares the object 4901 // as const. 4902 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 4903 T.addConst(); 4904 } 4905 4906 // If there was an ellipsis in the declarator, the declaration declares a 4907 // parameter pack whose type may be a pack expansion type. 4908 if (D.hasEllipsis()) { 4909 // C++0x [dcl.fct]p13: 4910 // A declarator-id or abstract-declarator containing an ellipsis shall 4911 // only be used in a parameter-declaration. Such a parameter-declaration 4912 // is a parameter pack (14.5.3). [...] 4913 switch (D.getContext()) { 4914 case DeclaratorContext::PrototypeContext: 4915 case DeclaratorContext::LambdaExprParameterContext: 4916 // C++0x [dcl.fct]p13: 4917 // [...] When it is part of a parameter-declaration-clause, the 4918 // parameter pack is a function parameter pack (14.5.3). The type T 4919 // of the declarator-id of the function parameter pack shall contain 4920 // a template parameter pack; each template parameter pack in T is 4921 // expanded by the function parameter pack. 4922 // 4923 // We represent function parameter packs as function parameters whose 4924 // type is a pack expansion. 4925 if (!T->containsUnexpandedParameterPack()) { 4926 S.Diag(D.getEllipsisLoc(), 4927 diag::err_function_parameter_pack_without_parameter_packs) 4928 << T << D.getSourceRange(); 4929 D.setEllipsisLoc(SourceLocation()); 4930 } else { 4931 T = Context.getPackExpansionType(T, None); 4932 } 4933 break; 4934 case DeclaratorContext::TemplateParamContext: 4935 // C++0x [temp.param]p15: 4936 // If a template-parameter is a [...] is a parameter-declaration that 4937 // declares a parameter pack (8.3.5), then the template-parameter is a 4938 // template parameter pack (14.5.3). 4939 // 4940 // Note: core issue 778 clarifies that, if there are any unexpanded 4941 // parameter packs in the type of the non-type template parameter, then 4942 // it expands those parameter packs. 4943 if (T->containsUnexpandedParameterPack()) 4944 T = Context.getPackExpansionType(T, None); 4945 else 4946 S.Diag(D.getEllipsisLoc(), 4947 LangOpts.CPlusPlus11 4948 ? diag::warn_cxx98_compat_variadic_templates 4949 : diag::ext_variadic_templates); 4950 break; 4951 4952 case DeclaratorContext::FileContext: 4953 case DeclaratorContext::KNRTypeListContext: 4954 case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic 4955 // here? 4956 case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic 4957 // here? 4958 case DeclaratorContext::TypeNameContext: 4959 case DeclaratorContext::FunctionalCastContext: 4960 case DeclaratorContext::CXXNewContext: 4961 case DeclaratorContext::AliasDeclContext: 4962 case DeclaratorContext::AliasTemplateContext: 4963 case DeclaratorContext::MemberContext: 4964 case DeclaratorContext::BlockContext: 4965 case DeclaratorContext::ForContext: 4966 case DeclaratorContext::InitStmtContext: 4967 case DeclaratorContext::ConditionContext: 4968 case DeclaratorContext::CXXCatchContext: 4969 case DeclaratorContext::ObjCCatchContext: 4970 case DeclaratorContext::BlockLiteralContext: 4971 case DeclaratorContext::LambdaExprContext: 4972 case DeclaratorContext::ConversionIdContext: 4973 case DeclaratorContext::TrailingReturnContext: 4974 case DeclaratorContext::TrailingReturnVarContext: 4975 case DeclaratorContext::TemplateArgContext: 4976 case DeclaratorContext::TemplateTypeArgContext: 4977 // FIXME: We may want to allow parameter packs in block-literal contexts 4978 // in the future. 4979 S.Diag(D.getEllipsisLoc(), 4980 diag::err_ellipsis_in_declarator_not_parameter); 4981 D.setEllipsisLoc(SourceLocation()); 4982 break; 4983 } 4984 } 4985 4986 assert(!T.isNull() && "T must not be null at the end of this function"); 4987 if (D.isInvalidType()) 4988 return Context.getTrivialTypeSourceInfo(T); 4989 4990 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 4991 } 4992 4993 /// GetTypeForDeclarator - Convert the type for the specified 4994 /// declarator to Type instances. 4995 /// 4996 /// The result of this call will never be null, but the associated 4997 /// type may be a null type if there's an unrecoverable error. 4998 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 4999 // Determine the type of the declarator. Not all forms of declarator 5000 // have a type. 5001 5002 TypeProcessingState state(*this, D); 5003 5004 TypeSourceInfo *ReturnTypeInfo = nullptr; 5005 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 5006 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 5007 inferARCWriteback(state, T); 5008 5009 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 5010 } 5011 5012 static void transferARCOwnershipToDeclSpec(Sema &S, 5013 QualType &declSpecTy, 5014 Qualifiers::ObjCLifetime ownership) { 5015 if (declSpecTy->isObjCRetainableType() && 5016 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 5017 Qualifiers qs; 5018 qs.addObjCLifetime(ownership); 5019 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 5020 } 5021 } 5022 5023 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 5024 Qualifiers::ObjCLifetime ownership, 5025 unsigned chunkIndex) { 5026 Sema &S = state.getSema(); 5027 Declarator &D = state.getDeclarator(); 5028 5029 // Look for an explicit lifetime attribute. 5030 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 5031 for (const AttributeList *attr = chunk.getAttrs(); attr; 5032 attr = attr->getNext()) 5033 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 5034 return; 5035 5036 const char *attrStr = nullptr; 5037 switch (ownership) { 5038 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 5039 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 5040 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 5041 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 5042 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 5043 } 5044 5045 IdentifierLoc *Arg = new (S.Context) IdentifierLoc; 5046 Arg->Ident = &S.Context.Idents.get(attrStr); 5047 Arg->Loc = SourceLocation(); 5048 5049 ArgsUnion Args(Arg); 5050 5051 // If there wasn't one, add one (with an invalid source location 5052 // so that we don't make an AttributedType for it). 5053 AttributeList *attr = D.getAttributePool() 5054 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 5055 /*scope*/ nullptr, SourceLocation(), 5056 /*args*/ &Args, 1, AttributeList::AS_GNU); 5057 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 5058 5059 // TODO: mark whether we did this inference? 5060 } 5061 5062 /// \brief Used for transferring ownership in casts resulting in l-values. 5063 static void transferARCOwnership(TypeProcessingState &state, 5064 QualType &declSpecTy, 5065 Qualifiers::ObjCLifetime ownership) { 5066 Sema &S = state.getSema(); 5067 Declarator &D = state.getDeclarator(); 5068 5069 int inner = -1; 5070 bool hasIndirection = false; 5071 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5072 DeclaratorChunk &chunk = D.getTypeObject(i); 5073 switch (chunk.Kind) { 5074 case DeclaratorChunk::Paren: 5075 // Ignore parens. 5076 break; 5077 5078 case DeclaratorChunk::Array: 5079 case DeclaratorChunk::Reference: 5080 case DeclaratorChunk::Pointer: 5081 if (inner != -1) 5082 hasIndirection = true; 5083 inner = i; 5084 break; 5085 5086 case DeclaratorChunk::BlockPointer: 5087 if (inner != -1) 5088 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 5089 return; 5090 5091 case DeclaratorChunk::Function: 5092 case DeclaratorChunk::MemberPointer: 5093 case DeclaratorChunk::Pipe: 5094 return; 5095 } 5096 } 5097 5098 if (inner == -1) 5099 return; 5100 5101 DeclaratorChunk &chunk = D.getTypeObject(inner); 5102 if (chunk.Kind == DeclaratorChunk::Pointer) { 5103 if (declSpecTy->isObjCRetainableType()) 5104 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 5105 if (declSpecTy->isObjCObjectType() && hasIndirection) 5106 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 5107 } else { 5108 assert(chunk.Kind == DeclaratorChunk::Array || 5109 chunk.Kind == DeclaratorChunk::Reference); 5110 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 5111 } 5112 } 5113 5114 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 5115 TypeProcessingState state(*this, D); 5116 5117 TypeSourceInfo *ReturnTypeInfo = nullptr; 5118 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 5119 5120 if (getLangOpts().ObjC1) { 5121 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 5122 if (ownership != Qualifiers::OCL_None) 5123 transferARCOwnership(state, declSpecTy, ownership); 5124 } 5125 5126 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 5127 } 5128 5129 /// Map an AttributedType::Kind to an AttributeList::Kind. 5130 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 5131 switch (kind) { 5132 case AttributedType::attr_address_space: 5133 return AttributeList::AT_AddressSpace; 5134 case AttributedType::attr_regparm: 5135 return AttributeList::AT_Regparm; 5136 case AttributedType::attr_vector_size: 5137 return AttributeList::AT_VectorSize; 5138 case AttributedType::attr_neon_vector_type: 5139 return AttributeList::AT_NeonVectorType; 5140 case AttributedType::attr_neon_polyvector_type: 5141 return AttributeList::AT_NeonPolyVectorType; 5142 case AttributedType::attr_objc_gc: 5143 return AttributeList::AT_ObjCGC; 5144 case AttributedType::attr_objc_ownership: 5145 case AttributedType::attr_objc_inert_unsafe_unretained: 5146 return AttributeList::AT_ObjCOwnership; 5147 case AttributedType::attr_noreturn: 5148 return AttributeList::AT_NoReturn; 5149 case AttributedType::attr_nocf_check: 5150 return AttributeList::AT_AnyX86NoCfCheck; 5151 case AttributedType::attr_cdecl: 5152 return AttributeList::AT_CDecl; 5153 case AttributedType::attr_fastcall: 5154 return AttributeList::AT_FastCall; 5155 case AttributedType::attr_stdcall: 5156 return AttributeList::AT_StdCall; 5157 case AttributedType::attr_thiscall: 5158 return AttributeList::AT_ThisCall; 5159 case AttributedType::attr_regcall: 5160 return AttributeList::AT_RegCall; 5161 case AttributedType::attr_pascal: 5162 return AttributeList::AT_Pascal; 5163 case AttributedType::attr_swiftcall: 5164 return AttributeList::AT_SwiftCall; 5165 case AttributedType::attr_vectorcall: 5166 return AttributeList::AT_VectorCall; 5167 case AttributedType::attr_pcs: 5168 case AttributedType::attr_pcs_vfp: 5169 return AttributeList::AT_Pcs; 5170 case AttributedType::attr_inteloclbicc: 5171 return AttributeList::AT_IntelOclBicc; 5172 case AttributedType::attr_ms_abi: 5173 return AttributeList::AT_MSABI; 5174 case AttributedType::attr_sysv_abi: 5175 return AttributeList::AT_SysVABI; 5176 case AttributedType::attr_preserve_most: 5177 return AttributeList::AT_PreserveMost; 5178 case AttributedType::attr_preserve_all: 5179 return AttributeList::AT_PreserveAll; 5180 case AttributedType::attr_ptr32: 5181 return AttributeList::AT_Ptr32; 5182 case AttributedType::attr_ptr64: 5183 return AttributeList::AT_Ptr64; 5184 case AttributedType::attr_sptr: 5185 return AttributeList::AT_SPtr; 5186 case AttributedType::attr_uptr: 5187 return AttributeList::AT_UPtr; 5188 case AttributedType::attr_nonnull: 5189 return AttributeList::AT_TypeNonNull; 5190 case AttributedType::attr_nullable: 5191 return AttributeList::AT_TypeNullable; 5192 case AttributedType::attr_null_unspecified: 5193 return AttributeList::AT_TypeNullUnspecified; 5194 case AttributedType::attr_objc_kindof: 5195 return AttributeList::AT_ObjCKindOf; 5196 case AttributedType::attr_ns_returns_retained: 5197 return AttributeList::AT_NSReturnsRetained; 5198 } 5199 llvm_unreachable("unexpected attribute kind!"); 5200 } 5201 5202 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 5203 const AttributeList *attrs, 5204 const AttributeList *DeclAttrs = nullptr) { 5205 // DeclAttrs and attrs cannot be both empty. 5206 assert((attrs || DeclAttrs) && 5207 "no type attributes in the expected location!"); 5208 5209 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind()); 5210 // Try to search for an attribute of matching kind in attrs list. 5211 while (attrs && attrs->getKind() != parsedKind) 5212 attrs = attrs->getNext(); 5213 if (!attrs) { 5214 // No matching type attribute in attrs list found. 5215 // Try searching through C++11 attributes in the declarator attribute list. 5216 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() || 5217 DeclAttrs->getKind() != parsedKind)) 5218 DeclAttrs = DeclAttrs->getNext(); 5219 attrs = DeclAttrs; 5220 } 5221 5222 assert(attrs && "no matching type attribute in expected location!"); 5223 5224 TL.setAttrNameLoc(attrs->getLoc()); 5225 if (TL.hasAttrExprOperand()) { 5226 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind"); 5227 TL.setAttrExprOperand(attrs->getArgAsExpr(0)); 5228 } else if (TL.hasAttrEnumOperand()) { 5229 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) && 5230 "unexpected attribute operand kind"); 5231 if (attrs->isArgIdent(0)) 5232 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc); 5233 else 5234 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc()); 5235 } 5236 5237 // FIXME: preserve this information to here. 5238 if (TL.hasAttrOperand()) 5239 TL.setAttrOperandParensRange(SourceRange()); 5240 } 5241 5242 namespace { 5243 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 5244 ASTContext &Context; 5245 const DeclSpec &DS; 5246 5247 public: 5248 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 5249 : Context(Context), DS(DS) {} 5250 5251 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 5252 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 5253 Visit(TL.getModifiedLoc()); 5254 } 5255 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 5256 Visit(TL.getUnqualifiedLoc()); 5257 } 5258 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 5259 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5260 } 5261 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 5262 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5263 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 5264 // addition field. What we have is good enough for dispay of location 5265 // of 'fixit' on interface name. 5266 TL.setNameEndLoc(DS.getLocEnd()); 5267 } 5268 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 5269 TypeSourceInfo *RepTInfo = nullptr; 5270 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5271 TL.copy(RepTInfo->getTypeLoc()); 5272 } 5273 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 5274 TypeSourceInfo *RepTInfo = nullptr; 5275 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5276 TL.copy(RepTInfo->getTypeLoc()); 5277 } 5278 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 5279 TypeSourceInfo *TInfo = nullptr; 5280 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5281 5282 // If we got no declarator info from previous Sema routines, 5283 // just fill with the typespec loc. 5284 if (!TInfo) { 5285 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 5286 return; 5287 } 5288 5289 TypeLoc OldTL = TInfo->getTypeLoc(); 5290 if (TInfo->getType()->getAs<ElaboratedType>()) { 5291 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 5292 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 5293 .castAs<TemplateSpecializationTypeLoc>(); 5294 TL.copy(NamedTL); 5295 } else { 5296 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 5297 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 5298 } 5299 5300 } 5301 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 5302 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 5303 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 5304 TL.setParensRange(DS.getTypeofParensRange()); 5305 } 5306 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 5307 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 5308 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 5309 TL.setParensRange(DS.getTypeofParensRange()); 5310 assert(DS.getRepAsType()); 5311 TypeSourceInfo *TInfo = nullptr; 5312 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5313 TL.setUnderlyingTInfo(TInfo); 5314 } 5315 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 5316 // FIXME: This holds only because we only have one unary transform. 5317 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 5318 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 5319 TL.setParensRange(DS.getTypeofParensRange()); 5320 assert(DS.getRepAsType()); 5321 TypeSourceInfo *TInfo = nullptr; 5322 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5323 TL.setUnderlyingTInfo(TInfo); 5324 } 5325 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 5326 // By default, use the source location of the type specifier. 5327 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 5328 if (TL.needsExtraLocalData()) { 5329 // Set info for the written builtin specifiers. 5330 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 5331 // Try to have a meaningful source location. 5332 if (TL.getWrittenSignSpec() != TSS_unspecified) 5333 TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); 5334 if (TL.getWrittenWidthSpec() != TSW_unspecified) 5335 TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); 5336 } 5337 } 5338 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 5339 ElaboratedTypeKeyword Keyword 5340 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 5341 if (DS.getTypeSpecType() == TST_typename) { 5342 TypeSourceInfo *TInfo = nullptr; 5343 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5344 if (TInfo) { 5345 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 5346 return; 5347 } 5348 } 5349 TL.setElaboratedKeywordLoc(Keyword != ETK_None 5350 ? DS.getTypeSpecTypeLoc() 5351 : SourceLocation()); 5352 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 5353 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 5354 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 5355 } 5356 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 5357 assert(DS.getTypeSpecType() == TST_typename); 5358 TypeSourceInfo *TInfo = nullptr; 5359 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5360 assert(TInfo); 5361 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 5362 } 5363 void VisitDependentTemplateSpecializationTypeLoc( 5364 DependentTemplateSpecializationTypeLoc TL) { 5365 assert(DS.getTypeSpecType() == TST_typename); 5366 TypeSourceInfo *TInfo = nullptr; 5367 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5368 assert(TInfo); 5369 TL.copy( 5370 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 5371 } 5372 void VisitTagTypeLoc(TagTypeLoc TL) { 5373 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 5374 } 5375 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 5376 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 5377 // or an _Atomic qualifier. 5378 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 5379 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 5380 TL.setParensRange(DS.getTypeofParensRange()); 5381 5382 TypeSourceInfo *TInfo = nullptr; 5383 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5384 assert(TInfo); 5385 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 5386 } else { 5387 TL.setKWLoc(DS.getAtomicSpecLoc()); 5388 // No parens, to indicate this was spelled as an _Atomic qualifier. 5389 TL.setParensRange(SourceRange()); 5390 Visit(TL.getValueLoc()); 5391 } 5392 } 5393 5394 void VisitPipeTypeLoc(PipeTypeLoc TL) { 5395 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 5396 5397 TypeSourceInfo *TInfo = nullptr; 5398 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5399 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 5400 } 5401 5402 void VisitTypeLoc(TypeLoc TL) { 5403 // FIXME: add other typespec types and change this to an assert. 5404 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 5405 } 5406 }; 5407 5408 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 5409 ASTContext &Context; 5410 const DeclaratorChunk &Chunk; 5411 5412 public: 5413 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 5414 : Context(Context), Chunk(Chunk) {} 5415 5416 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 5417 llvm_unreachable("qualified type locs not expected here!"); 5418 } 5419 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 5420 llvm_unreachable("decayed type locs not expected here!"); 5421 } 5422 5423 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 5424 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 5425 } 5426 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 5427 // nothing 5428 } 5429 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 5430 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 5431 TL.setCaretLoc(Chunk.Loc); 5432 } 5433 void VisitPointerTypeLoc(PointerTypeLoc TL) { 5434 assert(Chunk.Kind == DeclaratorChunk::Pointer); 5435 TL.setStarLoc(Chunk.Loc); 5436 } 5437 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 5438 assert(Chunk.Kind == DeclaratorChunk::Pointer); 5439 TL.setStarLoc(Chunk.Loc); 5440 } 5441 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 5442 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 5443 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 5444 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 5445 5446 const Type* ClsTy = TL.getClass(); 5447 QualType ClsQT = QualType(ClsTy, 0); 5448 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 5449 // Now copy source location info into the type loc component. 5450 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 5451 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 5452 case NestedNameSpecifier::Identifier: 5453 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 5454 { 5455 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 5456 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 5457 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 5458 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 5459 } 5460 break; 5461 5462 case NestedNameSpecifier::TypeSpec: 5463 case NestedNameSpecifier::TypeSpecWithTemplate: 5464 if (isa<ElaboratedType>(ClsTy)) { 5465 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 5466 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 5467 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 5468 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 5469 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 5470 } else { 5471 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 5472 } 5473 break; 5474 5475 case NestedNameSpecifier::Namespace: 5476 case NestedNameSpecifier::NamespaceAlias: 5477 case NestedNameSpecifier::Global: 5478 case NestedNameSpecifier::Super: 5479 llvm_unreachable("Nested-name-specifier must name a type"); 5480 } 5481 5482 // Finally fill in MemberPointerLocInfo fields. 5483 TL.setStarLoc(Chunk.Loc); 5484 TL.setClassTInfo(ClsTInfo); 5485 } 5486 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 5487 assert(Chunk.Kind == DeclaratorChunk::Reference); 5488 // 'Amp' is misleading: this might have been originally 5489 /// spelled with AmpAmp. 5490 TL.setAmpLoc(Chunk.Loc); 5491 } 5492 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 5493 assert(Chunk.Kind == DeclaratorChunk::Reference); 5494 assert(!Chunk.Ref.LValueRef); 5495 TL.setAmpAmpLoc(Chunk.Loc); 5496 } 5497 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 5498 assert(Chunk.Kind == DeclaratorChunk::Array); 5499 TL.setLBracketLoc(Chunk.Loc); 5500 TL.setRBracketLoc(Chunk.EndLoc); 5501 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 5502 } 5503 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 5504 assert(Chunk.Kind == DeclaratorChunk::Function); 5505 TL.setLocalRangeBegin(Chunk.Loc); 5506 TL.setLocalRangeEnd(Chunk.EndLoc); 5507 5508 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 5509 TL.setLParenLoc(FTI.getLParenLoc()); 5510 TL.setRParenLoc(FTI.getRParenLoc()); 5511 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { 5512 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 5513 TL.setParam(tpi++, Param); 5514 } 5515 TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); 5516 } 5517 void VisitParenTypeLoc(ParenTypeLoc TL) { 5518 assert(Chunk.Kind == DeclaratorChunk::Paren); 5519 TL.setLParenLoc(Chunk.Loc); 5520 TL.setRParenLoc(Chunk.EndLoc); 5521 } 5522 void VisitPipeTypeLoc(PipeTypeLoc TL) { 5523 assert(Chunk.Kind == DeclaratorChunk::Pipe); 5524 TL.setKWLoc(Chunk.Loc); 5525 } 5526 5527 void VisitTypeLoc(TypeLoc TL) { 5528 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 5529 } 5530 }; 5531 } // end anonymous namespace 5532 5533 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 5534 SourceLocation Loc; 5535 switch (Chunk.Kind) { 5536 case DeclaratorChunk::Function: 5537 case DeclaratorChunk::Array: 5538 case DeclaratorChunk::Paren: 5539 case DeclaratorChunk::Pipe: 5540 llvm_unreachable("cannot be _Atomic qualified"); 5541 5542 case DeclaratorChunk::Pointer: 5543 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); 5544 break; 5545 5546 case DeclaratorChunk::BlockPointer: 5547 case DeclaratorChunk::Reference: 5548 case DeclaratorChunk::MemberPointer: 5549 // FIXME: Provide a source location for the _Atomic keyword. 5550 break; 5551 } 5552 5553 ATL.setKWLoc(Loc); 5554 ATL.setParensRange(SourceRange()); 5555 } 5556 5557 static void fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, 5558 const AttributeList *Attrs) { 5559 while (Attrs && Attrs->getKind() != AttributeList::AT_AddressSpace) 5560 Attrs = Attrs->getNext(); 5561 5562 assert(Attrs && "no address_space attribute found at the expected location!"); 5563 5564 DASTL.setAttrNameLoc(Attrs->getLoc()); 5565 DASTL.setAttrExprOperand(Attrs->getArgAsExpr(0)); 5566 DASTL.setAttrOperandParensRange(SourceRange()); 5567 } 5568 5569 /// \brief Create and instantiate a TypeSourceInfo with type source information. 5570 /// 5571 /// \param T QualType referring to the type as written in source code. 5572 /// 5573 /// \param ReturnTypeInfo For declarators whose return type does not show 5574 /// up in the normal place in the declaration specifiers (such as a C++ 5575 /// conversion function), this pointer will refer to a type source information 5576 /// for that return type. 5577 TypeSourceInfo * 5578 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 5579 TypeSourceInfo *ReturnTypeInfo) { 5580 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 5581 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 5582 const AttributeList *DeclAttrs = D.getAttributes(); 5583 5584 // Handle parameter packs whose type is a pack expansion. 5585 if (isa<PackExpansionType>(T)) { 5586 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 5587 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 5588 } 5589 5590 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5591 5592 if (DependentAddressSpaceTypeLoc DASTL = 5593 CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { 5594 fillDependentAddressSpaceTypeLoc(DASTL, D.getTypeObject(i).getAttrs()); 5595 CurrTL = DASTL.getPointeeTypeLoc().getUnqualifiedLoc(); 5596 } 5597 5598 // An AtomicTypeLoc might be produced by an atomic qualifier in this 5599 // declarator chunk. 5600 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 5601 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 5602 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 5603 } 5604 5605 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 5606 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs); 5607 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 5608 } 5609 5610 // FIXME: Ordering here? 5611 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) 5612 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 5613 5614 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 5615 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 5616 } 5617 5618 // If we have different source information for the return type, use 5619 // that. This really only applies to C++ conversion functions. 5620 if (ReturnTypeInfo) { 5621 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 5622 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 5623 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 5624 } else { 5625 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 5626 } 5627 5628 return TInfo; 5629 } 5630 5631 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 5632 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 5633 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 5634 // and Sema during declaration parsing. Try deallocating/caching them when 5635 // it's appropriate, instead of allocating them and keeping them around. 5636 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 5637 TypeAlignment); 5638 new (LocT) LocInfoType(T, TInfo); 5639 assert(LocT->getTypeClass() != T->getTypeClass() && 5640 "LocInfoType's TypeClass conflicts with an existing Type class"); 5641 return ParsedType::make(QualType(LocT, 0)); 5642 } 5643 5644 void LocInfoType::getAsStringInternal(std::string &Str, 5645 const PrintingPolicy &Policy) const { 5646 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 5647 " was used directly instead of getting the QualType through" 5648 " GetTypeFromParser"); 5649 } 5650 5651 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 5652 // C99 6.7.6: Type names have no identifier. This is already validated by 5653 // the parser. 5654 assert(D.getIdentifier() == nullptr && 5655 "Type name should have no identifier!"); 5656 5657 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5658 QualType T = TInfo->getType(); 5659 if (D.isInvalidType()) 5660 return true; 5661 5662 // Make sure there are no unused decl attributes on the declarator. 5663 // We don't want to do this for ObjC parameters because we're going 5664 // to apply them to the actual parameter declaration. 5665 // Likewise, we don't want to do this for alias declarations, because 5666 // we are actually going to build a declaration from this eventually. 5667 if (D.getContext() != DeclaratorContext::ObjCParameterContext && 5668 D.getContext() != DeclaratorContext::AliasDeclContext && 5669 D.getContext() != DeclaratorContext::AliasTemplateContext) 5670 checkUnusedDeclAttributes(D); 5671 5672 if (getLangOpts().CPlusPlus) { 5673 // Check that there are no default arguments (C++ only). 5674 CheckExtraCXXDefaultArguments(D); 5675 } 5676 5677 return CreateParsedType(T, TInfo); 5678 } 5679 5680 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 5681 QualType T = Context.getObjCInstanceType(); 5682 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 5683 return CreateParsedType(T, TInfo); 5684 } 5685 5686 //===----------------------------------------------------------------------===// 5687 // Type Attribute Processing 5688 //===----------------------------------------------------------------------===// 5689 5690 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression 5691 /// is uninstantiated. If instantiated it will apply the appropriate address space 5692 /// to the type. This function allows dependent template variables to be used in 5693 /// conjunction with the address_space attribute 5694 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, 5695 SourceLocation AttrLoc) { 5696 if (!AddrSpace->isValueDependent()) { 5697 5698 // If this type is already address space qualified, reject it. 5699 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified 5700 // by qualifiers for two or more different address spaces." 5701 if (T.getAddressSpace() != LangAS::Default) { 5702 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); 5703 return QualType(); 5704 } 5705 5706 llvm::APSInt addrSpace(32); 5707 if (!AddrSpace->isIntegerConstantExpr(addrSpace, Context)) { 5708 Diag(AttrLoc, diag::err_attribute_argument_type) 5709 << "'address_space'" << AANT_ArgumentIntegerConstant 5710 << AddrSpace->getSourceRange(); 5711 return QualType(); 5712 } 5713 5714 // Bounds checking. 5715 if (addrSpace.isSigned()) { 5716 if (addrSpace.isNegative()) { 5717 Diag(AttrLoc, diag::err_attribute_address_space_negative) 5718 << AddrSpace->getSourceRange(); 5719 return QualType(); 5720 } 5721 addrSpace.setIsSigned(false); 5722 } 5723 5724 llvm::APSInt max(addrSpace.getBitWidth()); 5725 max = 5726 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; 5727 if (addrSpace > max) { 5728 Diag(AttrLoc, diag::err_attribute_address_space_too_high) 5729 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); 5730 return QualType(); 5731 } 5732 5733 LangAS ASIdx = 5734 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue())); 5735 5736 return Context.getAddrSpaceQualType(T, ASIdx); 5737 } 5738 5739 // A check with similar intentions as checking if a type already has an 5740 // address space except for on a dependent types, basically if the 5741 // current type is already a DependentAddressSpaceType then its already 5742 // lined up to have another address space on it and we can't have 5743 // multiple address spaces on the one pointer indirection 5744 if (T->getAs<DependentAddressSpaceType>()) { 5745 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); 5746 return QualType(); 5747 } 5748 5749 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc); 5750 } 5751 5752 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 5753 /// specified type. The attribute contains 1 argument, the id of the address 5754 /// space for the type. 5755 static void HandleAddressSpaceTypeAttribute(QualType &Type, 5756 const AttributeList &Attr, Sema &S){ 5757 // If this type is already address space qualified, reject it. 5758 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 5759 // qualifiers for two or more different address spaces." 5760 if (Type.getAddressSpace() != LangAS::Default) { 5761 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 5762 Attr.setInvalid(); 5763 return; 5764 } 5765 5766 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 5767 // qualified by an address-space qualifier." 5768 if (Type->isFunctionType()) { 5769 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 5770 Attr.setInvalid(); 5771 return; 5772 } 5773 5774 LangAS ASIdx; 5775 if (Attr.getKind() == AttributeList::AT_AddressSpace) { 5776 5777 // Check the attribute arguments. 5778 if (Attr.getNumArgs() != 1) { 5779 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 5780 << Attr.getName() << 1; 5781 Attr.setInvalid(); 5782 return; 5783 } 5784 5785 Expr *ASArgExpr; 5786 if (Attr.isArgIdent(0)) { 5787 // Special case where the argument is a template id. 5788 CXXScopeSpec SS; 5789 SourceLocation TemplateKWLoc; 5790 UnqualifiedId id; 5791 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); 5792 5793 ExprResult AddrSpace = S.ActOnIdExpression( 5794 S.getCurScope(), SS, TemplateKWLoc, id, false, false); 5795 if (AddrSpace.isInvalid()) 5796 return; 5797 5798 ASArgExpr = static_cast<Expr *>(AddrSpace.get()); 5799 } else { 5800 ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 5801 } 5802 5803 // Create the DependentAddressSpaceType or append an address space onto 5804 // the type. 5805 QualType T = S.BuildAddressSpaceAttr(Type, ASArgExpr, Attr.getLoc()); 5806 5807 if (!T.isNull()) 5808 Type = T; 5809 else 5810 Attr.setInvalid(); 5811 } else { 5812 // The keyword-based type attributes imply which address space to use. 5813 switch (Attr.getKind()) { 5814 case AttributeList::AT_OpenCLGlobalAddressSpace: 5815 ASIdx = LangAS::opencl_global; break; 5816 case AttributeList::AT_OpenCLLocalAddressSpace: 5817 ASIdx = LangAS::opencl_local; break; 5818 case AttributeList::AT_OpenCLConstantAddressSpace: 5819 ASIdx = LangAS::opencl_constant; break; 5820 case AttributeList::AT_OpenCLGenericAddressSpace: 5821 ASIdx = LangAS::opencl_generic; break; 5822 case AttributeList::AT_OpenCLPrivateAddressSpace: 5823 ASIdx = LangAS::opencl_private; break; 5824 default: 5825 llvm_unreachable("Invalid address space"); 5826 } 5827 5828 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 5829 } 5830 } 5831 5832 /// Does this type have a "direct" ownership qualifier? That is, 5833 /// is it written like "__strong id", as opposed to something like 5834 /// "typeof(foo)", where that happens to be strong? 5835 static bool hasDirectOwnershipQualifier(QualType type) { 5836 // Fast path: no qualifier at all. 5837 assert(type.getQualifiers().hasObjCLifetime()); 5838 5839 while (true) { 5840 // __strong id 5841 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 5842 if (attr->getAttrKind() == AttributedType::attr_objc_ownership) 5843 return true; 5844 5845 type = attr->getModifiedType(); 5846 5847 // X *__strong (...) 5848 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 5849 type = paren->getInnerType(); 5850 5851 // That's it for things we want to complain about. In particular, 5852 // we do not want to look through typedefs, typeof(expr), 5853 // typeof(type), or any other way that the type is somehow 5854 // abstracted. 5855 } else { 5856 5857 return false; 5858 } 5859 } 5860 } 5861 5862 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 5863 /// attribute on the specified type. 5864 /// 5865 /// Returns 'true' if the attribute was handled. 5866 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 5867 AttributeList &attr, 5868 QualType &type) { 5869 bool NonObjCPointer = false; 5870 5871 if (!type->isDependentType() && !type->isUndeducedType()) { 5872 if (const PointerType *ptr = type->getAs<PointerType>()) { 5873 QualType pointee = ptr->getPointeeType(); 5874 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 5875 return false; 5876 // It is important not to lose the source info that there was an attribute 5877 // applied to non-objc pointer. We will create an attributed type but 5878 // its type will be the same as the original type. 5879 NonObjCPointer = true; 5880 } else if (!type->isObjCRetainableType()) { 5881 return false; 5882 } 5883 5884 // Don't accept an ownership attribute in the declspec if it would 5885 // just be the return type of a block pointer. 5886 if (state.isProcessingDeclSpec()) { 5887 Declarator &D = state.getDeclarator(); 5888 if (maybeMovePastReturnType(D, D.getNumTypeObjects(), 5889 /*onlyBlockPointers=*/true)) 5890 return false; 5891 } 5892 } 5893 5894 Sema &S = state.getSema(); 5895 SourceLocation AttrLoc = attr.getLoc(); 5896 if (AttrLoc.isMacroID()) 5897 AttrLoc = 5898 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin(); 5899 5900 if (!attr.isArgIdent(0)) { 5901 S.Diag(AttrLoc, diag::err_attribute_argument_type) 5902 << attr.getName() << AANT_ArgumentString; 5903 attr.setInvalid(); 5904 return true; 5905 } 5906 5907 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 5908 Qualifiers::ObjCLifetime lifetime; 5909 if (II->isStr("none")) 5910 lifetime = Qualifiers::OCL_ExplicitNone; 5911 else if (II->isStr("strong")) 5912 lifetime = Qualifiers::OCL_Strong; 5913 else if (II->isStr("weak")) 5914 lifetime = Qualifiers::OCL_Weak; 5915 else if (II->isStr("autoreleasing")) 5916 lifetime = Qualifiers::OCL_Autoreleasing; 5917 else { 5918 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 5919 << attr.getName() << II; 5920 attr.setInvalid(); 5921 return true; 5922 } 5923 5924 // Just ignore lifetime attributes other than __weak and __unsafe_unretained 5925 // outside of ARC mode. 5926 if (!S.getLangOpts().ObjCAutoRefCount && 5927 lifetime != Qualifiers::OCL_Weak && 5928 lifetime != Qualifiers::OCL_ExplicitNone) { 5929 return true; 5930 } 5931 5932 SplitQualType underlyingType = type.split(); 5933 5934 // Check for redundant/conflicting ownership qualifiers. 5935 if (Qualifiers::ObjCLifetime previousLifetime 5936 = type.getQualifiers().getObjCLifetime()) { 5937 // If it's written directly, that's an error. 5938 if (hasDirectOwnershipQualifier(type)) { 5939 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 5940 << type; 5941 return true; 5942 } 5943 5944 // Otherwise, if the qualifiers actually conflict, pull sugar off 5945 // and remove the ObjCLifetime qualifiers. 5946 if (previousLifetime != lifetime) { 5947 // It's possible to have multiple local ObjCLifetime qualifiers. We 5948 // can't stop after we reach a type that is directly qualified. 5949 const Type *prevTy = nullptr; 5950 while (!prevTy || prevTy != underlyingType.Ty) { 5951 prevTy = underlyingType.Ty; 5952 underlyingType = underlyingType.getSingleStepDesugaredType(); 5953 } 5954 underlyingType.Quals.removeObjCLifetime(); 5955 } 5956 } 5957 5958 underlyingType.Quals.addObjCLifetime(lifetime); 5959 5960 if (NonObjCPointer) { 5961 StringRef name = attr.getName()->getName(); 5962 switch (lifetime) { 5963 case Qualifiers::OCL_None: 5964 case Qualifiers::OCL_ExplicitNone: 5965 break; 5966 case Qualifiers::OCL_Strong: name = "__strong"; break; 5967 case Qualifiers::OCL_Weak: name = "__weak"; break; 5968 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 5969 } 5970 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 5971 << TDS_ObjCObjOrBlock << type; 5972 } 5973 5974 // Don't actually add the __unsafe_unretained qualifier in non-ARC files, 5975 // because having both 'T' and '__unsafe_unretained T' exist in the type 5976 // system causes unfortunate widespread consistency problems. (For example, 5977 // they're not considered compatible types, and we mangle them identicially 5978 // as template arguments.) These problems are all individually fixable, 5979 // but it's easier to just not add the qualifier and instead sniff it out 5980 // in specific places using isObjCInertUnsafeUnretainedType(). 5981 // 5982 // Doing this does means we miss some trivial consistency checks that 5983 // would've triggered in ARC, but that's better than trying to solve all 5984 // the coexistence problems with __unsafe_unretained. 5985 if (!S.getLangOpts().ObjCAutoRefCount && 5986 lifetime == Qualifiers::OCL_ExplicitNone) { 5987 type = S.Context.getAttributedType( 5988 AttributedType::attr_objc_inert_unsafe_unretained, 5989 type, type); 5990 return true; 5991 } 5992 5993 QualType origType = type; 5994 if (!NonObjCPointer) 5995 type = S.Context.getQualifiedType(underlyingType); 5996 5997 // If we have a valid source location for the attribute, use an 5998 // AttributedType instead. 5999 if (AttrLoc.isValid()) 6000 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 6001 origType, type); 6002 6003 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, 6004 unsigned diagnostic, QualType type) { 6005 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 6006 S.DelayedDiagnostics.add( 6007 sema::DelayedDiagnostic::makeForbiddenType( 6008 S.getSourceManager().getExpansionLoc(loc), 6009 diagnostic, type, /*ignored*/ 0)); 6010 } else { 6011 S.Diag(loc, diagnostic); 6012 } 6013 }; 6014 6015 // Sometimes, __weak isn't allowed. 6016 if (lifetime == Qualifiers::OCL_Weak && 6017 !S.getLangOpts().ObjCWeak && !NonObjCPointer) { 6018 6019 // Use a specialized diagnostic if the runtime just doesn't support them. 6020 unsigned diagnostic = 6021 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled 6022 : diag::err_arc_weak_no_runtime); 6023 6024 // In any case, delay the diagnostic until we know what we're parsing. 6025 diagnoseOrDelay(S, AttrLoc, diagnostic, type); 6026 6027 attr.setInvalid(); 6028 return true; 6029 } 6030 6031 // Forbid __weak for class objects marked as 6032 // objc_arc_weak_reference_unavailable 6033 if (lifetime == Qualifiers::OCL_Weak) { 6034 if (const ObjCObjectPointerType *ObjT = 6035 type->getAs<ObjCObjectPointerType>()) { 6036 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 6037 if (Class->isArcWeakrefUnavailable()) { 6038 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 6039 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 6040 diag::note_class_declared); 6041 } 6042 } 6043 } 6044 } 6045 6046 return true; 6047 } 6048 6049 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 6050 /// attribute on the specified type. Returns true to indicate that 6051 /// the attribute was handled, false to indicate that the type does 6052 /// not permit the attribute. 6053 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 6054 AttributeList &attr, 6055 QualType &type) { 6056 Sema &S = state.getSema(); 6057 6058 // Delay if this isn't some kind of pointer. 6059 if (!type->isPointerType() && 6060 !type->isObjCObjectPointerType() && 6061 !type->isBlockPointerType()) 6062 return false; 6063 6064 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 6065 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 6066 attr.setInvalid(); 6067 return true; 6068 } 6069 6070 // Check the attribute arguments. 6071 if (!attr.isArgIdent(0)) { 6072 S.Diag(attr.getLoc(), diag::err_attribute_argument_type) 6073 << attr.getName() << AANT_ArgumentString; 6074 attr.setInvalid(); 6075 return true; 6076 } 6077 Qualifiers::GC GCAttr; 6078 if (attr.getNumArgs() > 1) { 6079 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6080 << attr.getName() << 1; 6081 attr.setInvalid(); 6082 return true; 6083 } 6084 6085 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 6086 if (II->isStr("weak")) 6087 GCAttr = Qualifiers::Weak; 6088 else if (II->isStr("strong")) 6089 GCAttr = Qualifiers::Strong; 6090 else { 6091 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 6092 << attr.getName() << II; 6093 attr.setInvalid(); 6094 return true; 6095 } 6096 6097 QualType origType = type; 6098 type = S.Context.getObjCGCQualType(origType, GCAttr); 6099 6100 // Make an attributed type to preserve the source information. 6101 if (attr.getLoc().isValid()) 6102 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 6103 origType, type); 6104 6105 return true; 6106 } 6107 6108 namespace { 6109 /// A helper class to unwrap a type down to a function for the 6110 /// purposes of applying attributes there. 6111 /// 6112 /// Use: 6113 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 6114 /// if (unwrapped.isFunctionType()) { 6115 /// const FunctionType *fn = unwrapped.get(); 6116 /// // change fn somehow 6117 /// T = unwrapped.wrap(fn); 6118 /// } 6119 struct FunctionTypeUnwrapper { 6120 enum WrapKind { 6121 Desugar, 6122 Attributed, 6123 Parens, 6124 Pointer, 6125 BlockPointer, 6126 Reference, 6127 MemberPointer 6128 }; 6129 6130 QualType Original; 6131 const FunctionType *Fn; 6132 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 6133 6134 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 6135 while (true) { 6136 const Type *Ty = T.getTypePtr(); 6137 if (isa<FunctionType>(Ty)) { 6138 Fn = cast<FunctionType>(Ty); 6139 return; 6140 } else if (isa<ParenType>(Ty)) { 6141 T = cast<ParenType>(Ty)->getInnerType(); 6142 Stack.push_back(Parens); 6143 } else if (isa<PointerType>(Ty)) { 6144 T = cast<PointerType>(Ty)->getPointeeType(); 6145 Stack.push_back(Pointer); 6146 } else if (isa<BlockPointerType>(Ty)) { 6147 T = cast<BlockPointerType>(Ty)->getPointeeType(); 6148 Stack.push_back(BlockPointer); 6149 } else if (isa<MemberPointerType>(Ty)) { 6150 T = cast<MemberPointerType>(Ty)->getPointeeType(); 6151 Stack.push_back(MemberPointer); 6152 } else if (isa<ReferenceType>(Ty)) { 6153 T = cast<ReferenceType>(Ty)->getPointeeType(); 6154 Stack.push_back(Reference); 6155 } else if (isa<AttributedType>(Ty)) { 6156 T = cast<AttributedType>(Ty)->getEquivalentType(); 6157 Stack.push_back(Attributed); 6158 } else { 6159 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 6160 if (Ty == DTy) { 6161 Fn = nullptr; 6162 return; 6163 } 6164 6165 T = QualType(DTy, 0); 6166 Stack.push_back(Desugar); 6167 } 6168 } 6169 } 6170 6171 bool isFunctionType() const { return (Fn != nullptr); } 6172 const FunctionType *get() const { return Fn; } 6173 6174 QualType wrap(Sema &S, const FunctionType *New) { 6175 // If T wasn't modified from the unwrapped type, do nothing. 6176 if (New == get()) return Original; 6177 6178 Fn = New; 6179 return wrap(S.Context, Original, 0); 6180 } 6181 6182 private: 6183 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 6184 if (I == Stack.size()) 6185 return C.getQualifiedType(Fn, Old.getQualifiers()); 6186 6187 // Build up the inner type, applying the qualifiers from the old 6188 // type to the new type. 6189 SplitQualType SplitOld = Old.split(); 6190 6191 // As a special case, tail-recurse if there are no qualifiers. 6192 if (SplitOld.Quals.empty()) 6193 return wrap(C, SplitOld.Ty, I); 6194 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 6195 } 6196 6197 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 6198 if (I == Stack.size()) return QualType(Fn, 0); 6199 6200 switch (static_cast<WrapKind>(Stack[I++])) { 6201 case Desugar: 6202 // This is the point at which we potentially lose source 6203 // information. 6204 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 6205 6206 case Attributed: 6207 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); 6208 6209 case Parens: { 6210 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 6211 return C.getParenType(New); 6212 } 6213 6214 case Pointer: { 6215 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 6216 return C.getPointerType(New); 6217 } 6218 6219 case BlockPointer: { 6220 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 6221 return C.getBlockPointerType(New); 6222 } 6223 6224 case MemberPointer: { 6225 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 6226 QualType New = wrap(C, OldMPT->getPointeeType(), I); 6227 return C.getMemberPointerType(New, OldMPT->getClass()); 6228 } 6229 6230 case Reference: { 6231 const ReferenceType *OldRef = cast<ReferenceType>(Old); 6232 QualType New = wrap(C, OldRef->getPointeeType(), I); 6233 if (isa<LValueReferenceType>(OldRef)) 6234 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 6235 else 6236 return C.getRValueReferenceType(New); 6237 } 6238 } 6239 6240 llvm_unreachable("unknown wrapping kind"); 6241 } 6242 }; 6243 } // end anonymous namespace 6244 6245 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 6246 AttributeList &Attr, 6247 QualType &Type) { 6248 Sema &S = State.getSema(); 6249 6250 AttributeList::Kind Kind = Attr.getKind(); 6251 QualType Desugared = Type; 6252 const AttributedType *AT = dyn_cast<AttributedType>(Type); 6253 while (AT) { 6254 AttributedType::Kind CurAttrKind = AT->getAttrKind(); 6255 6256 // You cannot specify duplicate type attributes, so if the attribute has 6257 // already been applied, flag it. 6258 if (getAttrListKind(CurAttrKind) == Kind) { 6259 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact) 6260 << Attr.getName(); 6261 return true; 6262 } 6263 6264 // You cannot have both __sptr and __uptr on the same type, nor can you 6265 // have __ptr32 and __ptr64. 6266 if ((CurAttrKind == AttributedType::attr_ptr32 && 6267 Kind == AttributeList::AT_Ptr64) || 6268 (CurAttrKind == AttributedType::attr_ptr64 && 6269 Kind == AttributeList::AT_Ptr32)) { 6270 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 6271 << "'__ptr32'" << "'__ptr64'"; 6272 return true; 6273 } else if ((CurAttrKind == AttributedType::attr_sptr && 6274 Kind == AttributeList::AT_UPtr) || 6275 (CurAttrKind == AttributedType::attr_uptr && 6276 Kind == AttributeList::AT_SPtr)) { 6277 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 6278 << "'__sptr'" << "'__uptr'"; 6279 return true; 6280 } 6281 6282 Desugared = AT->getEquivalentType(); 6283 AT = dyn_cast<AttributedType>(Desugared); 6284 } 6285 6286 // Pointer type qualifiers can only operate on pointer types, but not 6287 // pointer-to-member types. 6288 if (!isa<PointerType>(Desugared)) { 6289 if (Type->isMemberPointerType()) 6290 S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers) 6291 << Attr.getName(); 6292 else 6293 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only) 6294 << Attr.getName() << 0; 6295 return true; 6296 } 6297 6298 AttributedType::Kind TAK; 6299 switch (Kind) { 6300 default: llvm_unreachable("Unknown attribute kind"); 6301 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break; 6302 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break; 6303 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break; 6304 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break; 6305 } 6306 6307 Type = S.Context.getAttributedType(TAK, Type, Type); 6308 return false; 6309 } 6310 6311 bool Sema::checkNullabilityTypeSpecifier(QualType &type, 6312 NullabilityKind nullability, 6313 SourceLocation nullabilityLoc, 6314 bool isContextSensitive, 6315 bool allowOnArrayType) { 6316 recordNullabilitySeen(*this, nullabilityLoc); 6317 6318 // Check for existing nullability attributes on the type. 6319 QualType desugared = type; 6320 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { 6321 // Check whether there is already a null 6322 if (auto existingNullability = attributed->getImmediateNullability()) { 6323 // Duplicated nullability. 6324 if (nullability == *existingNullability) { 6325 Diag(nullabilityLoc, diag::warn_nullability_duplicate) 6326 << DiagNullabilityKind(nullability, isContextSensitive) 6327 << FixItHint::CreateRemoval(nullabilityLoc); 6328 6329 break; 6330 } 6331 6332 // Conflicting nullability. 6333 Diag(nullabilityLoc, diag::err_nullability_conflicting) 6334 << DiagNullabilityKind(nullability, isContextSensitive) 6335 << DiagNullabilityKind(*existingNullability, false); 6336 return true; 6337 } 6338 6339 desugared = attributed->getModifiedType(); 6340 } 6341 6342 // If there is already a different nullability specifier, complain. 6343 // This (unlike the code above) looks through typedefs that might 6344 // have nullability specifiers on them, which means we cannot 6345 // provide a useful Fix-It. 6346 if (auto existingNullability = desugared->getNullability(Context)) { 6347 if (nullability != *existingNullability) { 6348 Diag(nullabilityLoc, diag::err_nullability_conflicting) 6349 << DiagNullabilityKind(nullability, isContextSensitive) 6350 << DiagNullabilityKind(*existingNullability, false); 6351 6352 // Try to find the typedef with the existing nullability specifier. 6353 if (auto typedefType = desugared->getAs<TypedefType>()) { 6354 TypedefNameDecl *typedefDecl = typedefType->getDecl(); 6355 QualType underlyingType = typedefDecl->getUnderlyingType(); 6356 if (auto typedefNullability 6357 = AttributedType::stripOuterNullability(underlyingType)) { 6358 if (*typedefNullability == *existingNullability) { 6359 Diag(typedefDecl->getLocation(), diag::note_nullability_here) 6360 << DiagNullabilityKind(*existingNullability, false); 6361 } 6362 } 6363 } 6364 6365 return true; 6366 } 6367 } 6368 6369 // If this definitely isn't a pointer type, reject the specifier. 6370 if (!desugared->canHaveNullability() && 6371 !(allowOnArrayType && desugared->isArrayType())) { 6372 Diag(nullabilityLoc, diag::err_nullability_nonpointer) 6373 << DiagNullabilityKind(nullability, isContextSensitive) << type; 6374 return true; 6375 } 6376 6377 // For the context-sensitive keywords/Objective-C property 6378 // attributes, require that the type be a single-level pointer. 6379 if (isContextSensitive) { 6380 // Make sure that the pointee isn't itself a pointer type. 6381 const Type *pointeeType; 6382 if (desugared->isArrayType()) 6383 pointeeType = desugared->getArrayElementTypeNoTypeQual(); 6384 else 6385 pointeeType = desugared->getPointeeType().getTypePtr(); 6386 6387 if (pointeeType->isAnyPointerType() || 6388 pointeeType->isObjCObjectPointerType() || 6389 pointeeType->isMemberPointerType()) { 6390 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) 6391 << DiagNullabilityKind(nullability, true) 6392 << type; 6393 Diag(nullabilityLoc, diag::note_nullability_type_specifier) 6394 << DiagNullabilityKind(nullability, false) 6395 << type 6396 << FixItHint::CreateReplacement(nullabilityLoc, 6397 getNullabilitySpelling(nullability)); 6398 return true; 6399 } 6400 } 6401 6402 // Form the attributed type. 6403 type = Context.getAttributedType( 6404 AttributedType::getNullabilityAttrKind(nullability), type, type); 6405 return false; 6406 } 6407 6408 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) { 6409 if (isa<ObjCTypeParamType>(type)) { 6410 // Build the attributed type to record where __kindof occurred. 6411 type = Context.getAttributedType(AttributedType::attr_objc_kindof, 6412 type, type); 6413 return false; 6414 } 6415 6416 // Find out if it's an Objective-C object or object pointer type; 6417 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); 6418 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() 6419 : type->getAs<ObjCObjectType>(); 6420 6421 // If not, we can't apply __kindof. 6422 if (!objType) { 6423 // FIXME: Handle dependent types that aren't yet object types. 6424 Diag(loc, diag::err_objc_kindof_nonobject) 6425 << type; 6426 return true; 6427 } 6428 6429 // Rebuild the "equivalent" type, which pushes __kindof down into 6430 // the object type. 6431 // There is no need to apply kindof on an unqualified id type. 6432 QualType equivType = Context.getObjCObjectType( 6433 objType->getBaseType(), objType->getTypeArgsAsWritten(), 6434 objType->getProtocols(), 6435 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); 6436 6437 // If we started with an object pointer type, rebuild it. 6438 if (ptrType) { 6439 equivType = Context.getObjCObjectPointerType(equivType); 6440 if (auto nullability = type->getNullability(Context)) { 6441 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability); 6442 equivType = Context.getAttributedType(attrKind, equivType, equivType); 6443 } 6444 } 6445 6446 // Build the attributed type to record where __kindof occurred. 6447 type = Context.getAttributedType(AttributedType::attr_objc_kindof, 6448 type, 6449 equivType); 6450 6451 return false; 6452 } 6453 6454 /// Map a nullability attribute kind to a nullability kind. 6455 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) { 6456 switch (kind) { 6457 case AttributeList::AT_TypeNonNull: 6458 return NullabilityKind::NonNull; 6459 6460 case AttributeList::AT_TypeNullable: 6461 return NullabilityKind::Nullable; 6462 6463 case AttributeList::AT_TypeNullUnspecified: 6464 return NullabilityKind::Unspecified; 6465 6466 default: 6467 llvm_unreachable("not a nullability attribute kind"); 6468 } 6469 } 6470 6471 /// Distribute a nullability type attribute that cannot be applied to 6472 /// the type specifier to a pointer, block pointer, or member pointer 6473 /// declarator, complaining if necessary. 6474 /// 6475 /// \returns true if the nullability annotation was distributed, false 6476 /// otherwise. 6477 static bool distributeNullabilityTypeAttr(TypeProcessingState &state, 6478 QualType type, 6479 AttributeList &attr) { 6480 Declarator &declarator = state.getDeclarator(); 6481 6482 /// Attempt to move the attribute to the specified chunk. 6483 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { 6484 // If there is already a nullability attribute there, don't add 6485 // one. 6486 if (hasNullabilityAttr(chunk.getAttrListRef())) 6487 return false; 6488 6489 // Complain about the nullability qualifier being in the wrong 6490 // place. 6491 enum { 6492 PK_Pointer, 6493 PK_BlockPointer, 6494 PK_MemberPointer, 6495 PK_FunctionPointer, 6496 PK_MemberFunctionPointer, 6497 } pointerKind 6498 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer 6499 : PK_Pointer) 6500 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer 6501 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; 6502 6503 auto diag = state.getSema().Diag(attr.getLoc(), 6504 diag::warn_nullability_declspec) 6505 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), 6506 attr.isContextSensitiveKeywordAttribute()) 6507 << type 6508 << static_cast<unsigned>(pointerKind); 6509 6510 // FIXME: MemberPointer chunks don't carry the location of the *. 6511 if (chunk.Kind != DeclaratorChunk::MemberPointer) { 6512 diag << FixItHint::CreateRemoval(attr.getLoc()) 6513 << FixItHint::CreateInsertion( 6514 state.getSema().getPreprocessor() 6515 .getLocForEndOfToken(chunk.Loc), 6516 " " + attr.getName()->getName().str() + " "); 6517 } 6518 6519 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 6520 chunk.getAttrListRef()); 6521 return true; 6522 }; 6523 6524 // Move it to the outermost pointer, member pointer, or block 6525 // pointer declarator. 6526 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 6527 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 6528 switch (chunk.Kind) { 6529 case DeclaratorChunk::Pointer: 6530 case DeclaratorChunk::BlockPointer: 6531 case DeclaratorChunk::MemberPointer: 6532 return moveToChunk(chunk, false); 6533 6534 case DeclaratorChunk::Paren: 6535 case DeclaratorChunk::Array: 6536 continue; 6537 6538 case DeclaratorChunk::Function: 6539 // Try to move past the return type to a function/block/member 6540 // function pointer. 6541 if (DeclaratorChunk *dest = maybeMovePastReturnType( 6542 declarator, i, 6543 /*onlyBlockPointers=*/false)) { 6544 return moveToChunk(*dest, true); 6545 } 6546 6547 return false; 6548 6549 // Don't walk through these. 6550 case DeclaratorChunk::Reference: 6551 case DeclaratorChunk::Pipe: 6552 return false; 6553 } 6554 } 6555 6556 return false; 6557 } 6558 6559 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) { 6560 assert(!Attr.isInvalid()); 6561 switch (Attr.getKind()) { 6562 default: 6563 llvm_unreachable("not a calling convention attribute"); 6564 case AttributeList::AT_CDecl: 6565 return AttributedType::attr_cdecl; 6566 case AttributeList::AT_FastCall: 6567 return AttributedType::attr_fastcall; 6568 case AttributeList::AT_StdCall: 6569 return AttributedType::attr_stdcall; 6570 case AttributeList::AT_ThisCall: 6571 return AttributedType::attr_thiscall; 6572 case AttributeList::AT_RegCall: 6573 return AttributedType::attr_regcall; 6574 case AttributeList::AT_Pascal: 6575 return AttributedType::attr_pascal; 6576 case AttributeList::AT_SwiftCall: 6577 return AttributedType::attr_swiftcall; 6578 case AttributeList::AT_VectorCall: 6579 return AttributedType::attr_vectorcall; 6580 case AttributeList::AT_Pcs: { 6581 // The attribute may have had a fixit applied where we treated an 6582 // identifier as a string literal. The contents of the string are valid, 6583 // but the form may not be. 6584 StringRef Str; 6585 if (Attr.isArgExpr(0)) 6586 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); 6587 else 6588 Str = Attr.getArgAsIdent(0)->Ident->getName(); 6589 return llvm::StringSwitch<AttributedType::Kind>(Str) 6590 .Case("aapcs", AttributedType::attr_pcs) 6591 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp); 6592 } 6593 case AttributeList::AT_IntelOclBicc: 6594 return AttributedType::attr_inteloclbicc; 6595 case AttributeList::AT_MSABI: 6596 return AttributedType::attr_ms_abi; 6597 case AttributeList::AT_SysVABI: 6598 return AttributedType::attr_sysv_abi; 6599 case AttributeList::AT_PreserveMost: 6600 return AttributedType::attr_preserve_most; 6601 case AttributeList::AT_PreserveAll: 6602 return AttributedType::attr_preserve_all; 6603 } 6604 llvm_unreachable("unexpected attribute kind!"); 6605 } 6606 6607 /// Process an individual function attribute. Returns true to 6608 /// indicate that the attribute was handled, false if it wasn't. 6609 static bool handleFunctionTypeAttr(TypeProcessingState &state, 6610 AttributeList &attr, 6611 QualType &type) { 6612 Sema &S = state.getSema(); 6613 6614 FunctionTypeUnwrapper unwrapped(S, type); 6615 6616 if (attr.getKind() == AttributeList::AT_NoReturn) { 6617 if (S.CheckAttrNoArgs(attr)) 6618 return true; 6619 6620 // Delay if this is not a function type. 6621 if (!unwrapped.isFunctionType()) 6622 return false; 6623 6624 // Otherwise we can process right away. 6625 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 6626 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6627 return true; 6628 } 6629 6630 // ns_returns_retained is not always a type attribute, but if we got 6631 // here, we're treating it as one right now. 6632 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) { 6633 if (attr.getNumArgs()) return true; 6634 6635 // Delay if this is not a function type. 6636 if (!unwrapped.isFunctionType()) 6637 return false; 6638 6639 // Check whether the return type is reasonable. 6640 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(), 6641 unwrapped.get()->getReturnType())) 6642 return true; 6643 6644 // Only actually change the underlying type in ARC builds. 6645 QualType origType = type; 6646 if (state.getSema().getLangOpts().ObjCAutoRefCount) { 6647 FunctionType::ExtInfo EI 6648 = unwrapped.get()->getExtInfo().withProducesResult(true); 6649 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6650 } 6651 type = S.Context.getAttributedType(AttributedType::attr_ns_returns_retained, 6652 origType, type); 6653 return true; 6654 } 6655 6656 if (attr.getKind() == AttributeList::AT_AnyX86NoCallerSavedRegisters) { 6657 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) 6658 return true; 6659 6660 // Delay if this is not a function type. 6661 if (!unwrapped.isFunctionType()) 6662 return false; 6663 6664 FunctionType::ExtInfo EI = 6665 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); 6666 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6667 return true; 6668 } 6669 6670 if (attr.getKind() == AttributeList::AT_AnyX86NoCfCheck) { 6671 if (!S.getLangOpts().CFProtectionBranch) { 6672 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored); 6673 attr.setInvalid(); 6674 return true; 6675 } 6676 6677 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) 6678 return true; 6679 6680 // If this is not a function type, warning will be asserted by subject 6681 // check. 6682 if (!unwrapped.isFunctionType()) 6683 return true; 6684 6685 FunctionType::ExtInfo EI = 6686 unwrapped.get()->getExtInfo().withNoCfCheck(true); 6687 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6688 return true; 6689 } 6690 6691 if (attr.getKind() == AttributeList::AT_Regparm) { 6692 unsigned value; 6693 if (S.CheckRegparmAttr(attr, value)) 6694 return true; 6695 6696 // Delay if this is not a function type. 6697 if (!unwrapped.isFunctionType()) 6698 return false; 6699 6700 // Diagnose regparm with fastcall. 6701 const FunctionType *fn = unwrapped.get(); 6702 CallingConv CC = fn->getCallConv(); 6703 if (CC == CC_X86FastCall) { 6704 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6705 << FunctionType::getNameForCallConv(CC) 6706 << "regparm"; 6707 attr.setInvalid(); 6708 return true; 6709 } 6710 6711 FunctionType::ExtInfo EI = 6712 unwrapped.get()->getExtInfo().withRegParm(value); 6713 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6714 return true; 6715 } 6716 6717 // Delay if the type didn't work out to a function. 6718 if (!unwrapped.isFunctionType()) return false; 6719 6720 // Otherwise, a calling convention. 6721 CallingConv CC; 6722 if (S.CheckCallingConvAttr(attr, CC)) 6723 return true; 6724 6725 const FunctionType *fn = unwrapped.get(); 6726 CallingConv CCOld = fn->getCallConv(); 6727 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr); 6728 6729 if (CCOld != CC) { 6730 // Error out on when there's already an attribute on the type 6731 // and the CCs don't match. 6732 const AttributedType *AT = S.getCallingConvAttributedType(type); 6733 if (AT && AT->getAttrKind() != CCAttrKind) { 6734 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6735 << FunctionType::getNameForCallConv(CC) 6736 << FunctionType::getNameForCallConv(CCOld); 6737 attr.setInvalid(); 6738 return true; 6739 } 6740 } 6741 6742 // Diagnose use of variadic functions with calling conventions that 6743 // don't support them (e.g. because they're callee-cleanup). 6744 // We delay warning about this on unprototyped function declarations 6745 // until after redeclaration checking, just in case we pick up a 6746 // prototype that way. And apparently we also "delay" warning about 6747 // unprototyped function types in general, despite not necessarily having 6748 // much ability to diagnose it later. 6749 if (!supportsVariadicCall(CC)) { 6750 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); 6751 if (FnP && FnP->isVariadic()) { 6752 unsigned DiagID = diag::err_cconv_varargs; 6753 6754 // stdcall and fastcall are ignored with a warning for GCC and MS 6755 // compatibility. 6756 bool IsInvalid = true; 6757 if (CC == CC_X86StdCall || CC == CC_X86FastCall) { 6758 DiagID = diag::warn_cconv_varargs; 6759 IsInvalid = false; 6760 } 6761 6762 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC); 6763 if (IsInvalid) attr.setInvalid(); 6764 return true; 6765 } 6766 } 6767 6768 // Also diagnose fastcall with regparm. 6769 if (CC == CC_X86FastCall && fn->getHasRegParm()) { 6770 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6771 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); 6772 attr.setInvalid(); 6773 return true; 6774 } 6775 6776 // Modify the CC from the wrapped function type, wrap it all back, and then 6777 // wrap the whole thing in an AttributedType as written. The modified type 6778 // might have a different CC if we ignored the attribute. 6779 QualType Equivalent; 6780 if (CCOld == CC) { 6781 Equivalent = type; 6782 } else { 6783 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 6784 Equivalent = 6785 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6786 } 6787 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent); 6788 return true; 6789 } 6790 6791 bool Sema::hasExplicitCallingConv(QualType &T) { 6792 QualType R = T.IgnoreParens(); 6793 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) { 6794 if (AT->isCallingConv()) 6795 return true; 6796 R = AT->getModifiedType().IgnoreParens(); 6797 } 6798 return false; 6799 } 6800 6801 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 6802 SourceLocation Loc) { 6803 FunctionTypeUnwrapper Unwrapped(*this, T); 6804 const FunctionType *FT = Unwrapped.get(); 6805 bool IsVariadic = (isa<FunctionProtoType>(FT) && 6806 cast<FunctionProtoType>(FT)->isVariadic()); 6807 CallingConv CurCC = FT->getCallConv(); 6808 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); 6809 6810 if (CurCC == ToCC) 6811 return; 6812 6813 // MS compiler ignores explicit calling convention attributes on structors. We 6814 // should do the same. 6815 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { 6816 // Issue a warning on ignored calling convention -- except of __stdcall. 6817 // Again, this is what MS compiler does. 6818 if (CurCC != CC_X86StdCall) 6819 Diag(Loc, diag::warn_cconv_structors) 6820 << FunctionType::getNameForCallConv(CurCC); 6821 // Default adjustment. 6822 } else { 6823 // Only adjust types with the default convention. For example, on Windows 6824 // we should adjust a __cdecl type to __thiscall for instance methods, and a 6825 // __thiscall type to __cdecl for static methods. 6826 CallingConv DefaultCC = 6827 Context.getDefaultCallingConvention(IsVariadic, IsStatic); 6828 6829 if (CurCC != DefaultCC || DefaultCC == ToCC) 6830 return; 6831 6832 if (hasExplicitCallingConv(T)) 6833 return; 6834 } 6835 6836 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); 6837 QualType Wrapped = Unwrapped.wrap(*this, FT); 6838 T = Context.getAdjustedType(T, Wrapped); 6839 } 6840 6841 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 6842 /// and float scalars, although arrays, pointers, and function return values are 6843 /// allowed in conjunction with this construct. Aggregates with this attribute 6844 /// are invalid, even if they are of the same size as a corresponding scalar. 6845 /// The raw attribute should contain precisely 1 argument, the vector size for 6846 /// the variable, measured in bytes. If curType and rawAttr are well formed, 6847 /// this routine will return a new vector type. 6848 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 6849 Sema &S) { 6850 // Check the attribute arguments. 6851 if (Attr.getNumArgs() != 1) { 6852 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6853 << Attr.getName() << 1; 6854 Attr.setInvalid(); 6855 return; 6856 } 6857 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6858 llvm::APSInt vecSize(32); 6859 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 6860 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 6861 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6862 << Attr.getName() << AANT_ArgumentIntegerConstant 6863 << sizeExpr->getSourceRange(); 6864 Attr.setInvalid(); 6865 return; 6866 } 6867 // The base type must be integer (not Boolean or enumeration) or float, and 6868 // can't already be a vector. 6869 if (!CurType->isBuiltinType() || CurType->isBooleanType() || 6870 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) { 6871 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 6872 Attr.setInvalid(); 6873 return; 6874 } 6875 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 6876 // vecSize is specified in bytes - convert to bits. 6877 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 6878 6879 // the vector size needs to be an integral multiple of the type size. 6880 if (vectorSize % typeSize) { 6881 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 6882 << sizeExpr->getSourceRange(); 6883 Attr.setInvalid(); 6884 return; 6885 } 6886 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) { 6887 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large) 6888 << sizeExpr->getSourceRange(); 6889 Attr.setInvalid(); 6890 return; 6891 } 6892 if (vectorSize == 0) { 6893 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 6894 << sizeExpr->getSourceRange(); 6895 Attr.setInvalid(); 6896 return; 6897 } 6898 6899 // Success! Instantiate the vector type, the number of elements is > 0, and 6900 // not required to be a power of 2, unlike GCC. 6901 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 6902 VectorType::GenericVector); 6903 } 6904 6905 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 6906 /// a type. 6907 static void HandleExtVectorTypeAttr(QualType &CurType, 6908 const AttributeList &Attr, 6909 Sema &S) { 6910 // check the attribute arguments. 6911 if (Attr.getNumArgs() != 1) { 6912 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6913 << Attr.getName() << 1; 6914 return; 6915 } 6916 6917 Expr *sizeExpr; 6918 6919 // Special case where the argument is a template id. 6920 if (Attr.isArgIdent(0)) { 6921 CXXScopeSpec SS; 6922 SourceLocation TemplateKWLoc; 6923 UnqualifiedId id; 6924 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); 6925 6926 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 6927 id, false, false); 6928 if (Size.isInvalid()) 6929 return; 6930 6931 sizeExpr = Size.get(); 6932 } else { 6933 sizeExpr = Attr.getArgAsExpr(0); 6934 } 6935 6936 // Create the vector type. 6937 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 6938 if (!T.isNull()) 6939 CurType = T; 6940 } 6941 6942 static bool isPermittedNeonBaseType(QualType &Ty, 6943 VectorType::VectorKind VecKind, Sema &S) { 6944 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 6945 if (!BTy) 6946 return false; 6947 6948 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 6949 6950 // Signed poly is mathematically wrong, but has been baked into some ABIs by 6951 // now. 6952 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || 6953 Triple.getArch() == llvm::Triple::aarch64_be; 6954 if (VecKind == VectorType::NeonPolyVector) { 6955 if (IsPolyUnsigned) { 6956 // AArch64 polynomial vectors are unsigned and support poly64. 6957 return BTy->getKind() == BuiltinType::UChar || 6958 BTy->getKind() == BuiltinType::UShort || 6959 BTy->getKind() == BuiltinType::ULong || 6960 BTy->getKind() == BuiltinType::ULongLong; 6961 } else { 6962 // AArch32 polynomial vector are signed. 6963 return BTy->getKind() == BuiltinType::SChar || 6964 BTy->getKind() == BuiltinType::Short; 6965 } 6966 } 6967 6968 // Non-polynomial vector types: the usual suspects are allowed, as well as 6969 // float64_t on AArch64. 6970 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 || 6971 Triple.getArch() == llvm::Triple::aarch64_be; 6972 6973 if (Is64Bit && BTy->getKind() == BuiltinType::Double) 6974 return true; 6975 6976 return BTy->getKind() == BuiltinType::SChar || 6977 BTy->getKind() == BuiltinType::UChar || 6978 BTy->getKind() == BuiltinType::Short || 6979 BTy->getKind() == BuiltinType::UShort || 6980 BTy->getKind() == BuiltinType::Int || 6981 BTy->getKind() == BuiltinType::UInt || 6982 BTy->getKind() == BuiltinType::Long || 6983 BTy->getKind() == BuiltinType::ULong || 6984 BTy->getKind() == BuiltinType::LongLong || 6985 BTy->getKind() == BuiltinType::ULongLong || 6986 BTy->getKind() == BuiltinType::Float || 6987 BTy->getKind() == BuiltinType::Half; 6988 } 6989 6990 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 6991 /// "neon_polyvector_type" attributes are used to create vector types that 6992 /// are mangled according to ARM's ABI. Otherwise, these types are identical 6993 /// to those created with the "vector_size" attribute. Unlike "vector_size" 6994 /// the argument to these Neon attributes is the number of vector elements, 6995 /// not the vector size in bytes. The vector width and element type must 6996 /// match one of the standard Neon vector types. 6997 static void HandleNeonVectorTypeAttr(QualType& CurType, 6998 const AttributeList &Attr, Sema &S, 6999 VectorType::VectorKind VecKind) { 7000 // Target must have NEON 7001 if (!S.Context.getTargetInfo().hasFeature("neon")) { 7002 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName(); 7003 Attr.setInvalid(); 7004 return; 7005 } 7006 // Check the attribute arguments. 7007 if (Attr.getNumArgs() != 1) { 7008 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 7009 << Attr.getName() << 1; 7010 Attr.setInvalid(); 7011 return; 7012 } 7013 // The number of elements must be an ICE. 7014 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 7015 llvm::APSInt numEltsInt(32); 7016 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 7017 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 7018 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 7019 << Attr.getName() << AANT_ArgumentIntegerConstant 7020 << numEltsExpr->getSourceRange(); 7021 Attr.setInvalid(); 7022 return; 7023 } 7024 // Only certain element types are supported for Neon vectors. 7025 if (!isPermittedNeonBaseType(CurType, VecKind, S)) { 7026 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 7027 Attr.setInvalid(); 7028 return; 7029 } 7030 7031 // The total size of the vector must be 64 or 128 bits. 7032 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 7033 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 7034 unsigned vecSize = typeSize * numElts; 7035 if (vecSize != 64 && vecSize != 128) { 7036 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 7037 Attr.setInvalid(); 7038 return; 7039 } 7040 7041 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 7042 } 7043 7044 /// Handle OpenCL Access Qualifier Attribute. 7045 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr, 7046 Sema &S) { 7047 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. 7048 if (!(CurType->isImageType() || CurType->isPipeType())) { 7049 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); 7050 Attr.setInvalid(); 7051 return; 7052 } 7053 7054 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { 7055 QualType PointeeTy = TypedefTy->desugar(); 7056 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); 7057 7058 std::string PrevAccessQual; 7059 switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) { 7060 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7061 case BuiltinType::Id: \ 7062 PrevAccessQual = #Access; \ 7063 break; 7064 #include "clang/Basic/OpenCLImageTypes.def" 7065 default: 7066 assert(0 && "Unable to find corresponding image type."); 7067 } 7068 7069 S.Diag(TypedefTy->getDecl()->getLocStart(), 7070 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; 7071 } else if (CurType->isPipeType()) { 7072 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { 7073 QualType ElemType = CurType->getAs<PipeType>()->getElementType(); 7074 CurType = S.Context.getWritePipeType(ElemType); 7075 } 7076 } 7077 } 7078 7079 static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State, 7080 QualType &T, TypeAttrLocation TAL) { 7081 Declarator &D = State.getDeclarator(); 7082 7083 // Handle the cases where address space should not be deduced. 7084 // 7085 // The pointee type of a pointer type is always deduced since a pointer always 7086 // points to some memory location which should has an address space. 7087 // 7088 // There are situations that at the point of certain declarations, the address 7089 // space may be unknown and better to be left as default. For example, when 7090 // defining a typedef or struct type, they are not associated with any 7091 // specific address space. Later on, they may be used with any address space 7092 // to declare a variable. 7093 // 7094 // The return value of a function is r-value, therefore should not have 7095 // address space. 7096 // 7097 // The void type does not occupy memory, therefore should not have address 7098 // space, except when it is used as a pointee type. 7099 // 7100 // Since LLVM assumes function type is in default address space, it should not 7101 // have address space. 7102 auto ChunkIndex = State.getCurrentChunkIndex(); 7103 bool IsPointee = 7104 ChunkIndex > 0 && 7105 (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer || 7106 D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer); 7107 bool IsFuncReturnType = 7108 ChunkIndex > 0 && 7109 D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function; 7110 bool IsFuncType = 7111 ChunkIndex < D.getNumTypeObjects() && 7112 D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function; 7113 if ( // Do not deduce addr space for function return type and function type, 7114 // otherwise it will fail some sema check. 7115 IsFuncReturnType || IsFuncType || 7116 // Do not deduce addr space for member types of struct, except the pointee 7117 // type of a pointer member type. 7118 (D.getContext() == DeclaratorContext::MemberContext && !IsPointee) || 7119 // Do not deduce addr space for types used to define a typedef and the 7120 // typedef itself, except the pointee type of a pointer type which is used 7121 // to define the typedef. 7122 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef && 7123 !IsPointee) || 7124 // Do not deduce addr space of the void type, e.g. in f(void), otherwise 7125 // it will fail some sema check. 7126 (T->isVoidType() && !IsPointee)) 7127 return; 7128 7129 LangAS ImpAddr; 7130 // Put OpenCL automatic variable in private address space. 7131 // OpenCL v1.2 s6.5: 7132 // The default address space name for arguments to a function in a 7133 // program, or local variables of a function is __private. All function 7134 // arguments shall be in the __private address space. 7135 if (State.getSema().getLangOpts().OpenCLVersion <= 120) { 7136 ImpAddr = LangAS::opencl_private; 7137 } else { 7138 // If address space is not set, OpenCL 2.0 defines non private default 7139 // address spaces for some cases: 7140 // OpenCL 2.0, section 6.5: 7141 // The address space for a variable at program scope or a static variable 7142 // inside a function can either be __global or __constant, but defaults to 7143 // __global if not specified. 7144 // (...) 7145 // Pointers that are declared without pointing to a named address space 7146 // point to the generic address space. 7147 if (IsPointee) { 7148 ImpAddr = LangAS::opencl_generic; 7149 } else { 7150 if (D.getContext() == DeclaratorContext::FileContext) { 7151 ImpAddr = LangAS::opencl_global; 7152 } else { 7153 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || 7154 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) { 7155 ImpAddr = LangAS::opencl_global; 7156 } else { 7157 ImpAddr = LangAS::opencl_private; 7158 } 7159 } 7160 } 7161 } 7162 T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr); 7163 } 7164 7165 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 7166 TypeAttrLocation TAL, AttributeList *attrs) { 7167 // Scan through and apply attributes to this type where it makes sense. Some 7168 // attributes (such as __address_space__, __vector_size__, etc) apply to the 7169 // type, but others can be present in the type specifiers even though they 7170 // apply to the decl. Here we apply type attributes and ignore the rest. 7171 7172 while (attrs) { 7173 AttributeList &attr = *attrs; 7174 attrs = attr.getNext(); // reset to the next here due to early loop continue 7175 // stmts 7176 7177 // Skip attributes that were marked to be invalid. 7178 if (attr.isInvalid()) 7179 continue; 7180 7181 if (attr.isCXX11Attribute()) { 7182 // [[gnu::...]] attributes are treated as declaration attributes, so may 7183 // not appertain to a DeclaratorChunk, even if we handle them as type 7184 // attributes. 7185 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) { 7186 if (TAL == TAL_DeclChunk) { 7187 state.getSema().Diag(attr.getLoc(), 7188 diag::warn_cxx11_gnu_attribute_on_type) 7189 << attr.getName(); 7190 continue; 7191 } 7192 } else if (TAL != TAL_DeclChunk) { 7193 // Otherwise, only consider type processing for a C++11 attribute if 7194 // it's actually been applied to a type. 7195 continue; 7196 } 7197 } 7198 7199 // If this is an attribute we can handle, do so now, 7200 // otherwise, add it to the FnAttrs list for rechaining. 7201 switch (attr.getKind()) { 7202 default: 7203 // A C++11 attribute on a declarator chunk must appertain to a type. 7204 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { 7205 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 7206 << attr.getName(); 7207 attr.setUsedAsTypeAttr(); 7208 } 7209 break; 7210 7211 case AttributeList::UnknownAttribute: 7212 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 7213 state.getSema().Diag(attr.getLoc(), 7214 diag::warn_unknown_attribute_ignored) 7215 << attr.getName(); 7216 break; 7217 7218 case AttributeList::IgnoredAttribute: 7219 break; 7220 7221 case AttributeList::AT_MayAlias: 7222 // FIXME: This attribute needs to actually be handled, but if we ignore 7223 // it it breaks large amounts of Linux software. 7224 attr.setUsedAsTypeAttr(); 7225 break; 7226 case AttributeList::AT_OpenCLPrivateAddressSpace: 7227 case AttributeList::AT_OpenCLGlobalAddressSpace: 7228 case AttributeList::AT_OpenCLLocalAddressSpace: 7229 case AttributeList::AT_OpenCLConstantAddressSpace: 7230 case AttributeList::AT_OpenCLGenericAddressSpace: 7231 case AttributeList::AT_AddressSpace: 7232 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 7233 attr.setUsedAsTypeAttr(); 7234 break; 7235 OBJC_POINTER_TYPE_ATTRS_CASELIST: 7236 if (!handleObjCPointerTypeAttr(state, attr, type)) 7237 distributeObjCPointerTypeAttr(state, attr, type); 7238 attr.setUsedAsTypeAttr(); 7239 break; 7240 case AttributeList::AT_VectorSize: 7241 HandleVectorSizeAttr(type, attr, state.getSema()); 7242 attr.setUsedAsTypeAttr(); 7243 break; 7244 case AttributeList::AT_ExtVectorType: 7245 HandleExtVectorTypeAttr(type, attr, state.getSema()); 7246 attr.setUsedAsTypeAttr(); 7247 break; 7248 case AttributeList::AT_NeonVectorType: 7249 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 7250 VectorType::NeonVector); 7251 attr.setUsedAsTypeAttr(); 7252 break; 7253 case AttributeList::AT_NeonPolyVectorType: 7254 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 7255 VectorType::NeonPolyVector); 7256 attr.setUsedAsTypeAttr(); 7257 break; 7258 case AttributeList::AT_OpenCLAccess: 7259 HandleOpenCLAccessAttr(type, attr, state.getSema()); 7260 attr.setUsedAsTypeAttr(); 7261 break; 7262 7263 MS_TYPE_ATTRS_CASELIST: 7264 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 7265 attr.setUsedAsTypeAttr(); 7266 break; 7267 7268 7269 NULLABILITY_TYPE_ATTRS_CASELIST: 7270 // Either add nullability here or try to distribute it. We 7271 // don't want to distribute the nullability specifier past any 7272 // dependent type, because that complicates the user model. 7273 if (type->canHaveNullability() || type->isDependentType() || 7274 type->isArrayType() || 7275 !distributeNullabilityTypeAttr(state, type, attr)) { 7276 unsigned endIndex; 7277 if (TAL == TAL_DeclChunk) 7278 endIndex = state.getCurrentChunkIndex(); 7279 else 7280 endIndex = state.getDeclarator().getNumTypeObjects(); 7281 bool allowOnArrayType = 7282 state.getDeclarator().isPrototypeContext() && 7283 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); 7284 if (state.getSema().checkNullabilityTypeSpecifier( 7285 type, 7286 mapNullabilityAttrKind(attr.getKind()), 7287 attr.getLoc(), 7288 attr.isContextSensitiveKeywordAttribute(), 7289 allowOnArrayType)) { 7290 attr.setInvalid(); 7291 } 7292 7293 attr.setUsedAsTypeAttr(); 7294 } 7295 break; 7296 7297 case AttributeList::AT_ObjCKindOf: 7298 // '__kindof' must be part of the decl-specifiers. 7299 switch (TAL) { 7300 case TAL_DeclSpec: 7301 break; 7302 7303 case TAL_DeclChunk: 7304 case TAL_DeclName: 7305 state.getSema().Diag(attr.getLoc(), 7306 diag::err_objc_kindof_wrong_position) 7307 << FixItHint::CreateRemoval(attr.getLoc()) 7308 << FixItHint::CreateInsertion( 7309 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof "); 7310 break; 7311 } 7312 7313 // Apply it regardless. 7314 if (state.getSema().checkObjCKindOfType(type, attr.getLoc())) 7315 attr.setInvalid(); 7316 attr.setUsedAsTypeAttr(); 7317 break; 7318 7319 FUNCTION_TYPE_ATTRS_CASELIST: 7320 attr.setUsedAsTypeAttr(); 7321 7322 // Never process function type attributes as part of the 7323 // declaration-specifiers. 7324 if (TAL == TAL_DeclSpec) 7325 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 7326 7327 // Otherwise, handle the possible delays. 7328 else if (!handleFunctionTypeAttr(state, attr, type)) 7329 distributeFunctionTypeAttr(state, attr, type); 7330 break; 7331 } 7332 } 7333 7334 if (!state.getSema().getLangOpts().OpenCL || 7335 type.getAddressSpace() != LangAS::Default) 7336 return; 7337 7338 deduceOpenCLImplicitAddrSpace(state, type, TAL); 7339 } 7340 7341 void Sema::completeExprArrayBound(Expr *E) { 7342 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 7343 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 7344 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { 7345 auto *Def = Var->getDefinition(); 7346 if (!Def) { 7347 SourceLocation PointOfInstantiation = E->getExprLoc(); 7348 InstantiateVariableDefinition(PointOfInstantiation, Var); 7349 Def = Var->getDefinition(); 7350 7351 // If we don't already have a point of instantiation, and we managed 7352 // to instantiate a definition, this is the point of instantiation. 7353 // Otherwise, we don't request an end-of-TU instantiation, so this is 7354 // not a point of instantiation. 7355 // FIXME: Is this really the right behavior? 7356 if (Var->getPointOfInstantiation().isInvalid() && Def) { 7357 assert(Var->getTemplateSpecializationKind() == 7358 TSK_ImplicitInstantiation && 7359 "explicit instantiation with no point of instantiation"); 7360 Var->setTemplateSpecializationKind( 7361 Var->getTemplateSpecializationKind(), PointOfInstantiation); 7362 } 7363 } 7364 7365 // Update the type to the definition's type both here and within the 7366 // expression. 7367 if (Def) { 7368 DRE->setDecl(Def); 7369 QualType T = Def->getType(); 7370 DRE->setType(T); 7371 // FIXME: Update the type on all intervening expressions. 7372 E->setType(T); 7373 } 7374 7375 // We still go on to try to complete the type independently, as it 7376 // may also require instantiations or diagnostics if it remains 7377 // incomplete. 7378 } 7379 } 7380 } 7381 } 7382 7383 /// \brief Ensure that the type of the given expression is complete. 7384 /// 7385 /// This routine checks whether the expression \p E has a complete type. If the 7386 /// expression refers to an instantiable construct, that instantiation is 7387 /// performed as needed to complete its type. Furthermore 7388 /// Sema::RequireCompleteType is called for the expression's type (or in the 7389 /// case of a reference type, the referred-to type). 7390 /// 7391 /// \param E The expression whose type is required to be complete. 7392 /// \param Diagnoser The object that will emit a diagnostic if the type is 7393 /// incomplete. 7394 /// 7395 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 7396 /// otherwise. 7397 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) { 7398 QualType T = E->getType(); 7399 7400 // Incomplete array types may be completed by the initializer attached to 7401 // their definitions. For static data members of class templates and for 7402 // variable templates, we need to instantiate the definition to get this 7403 // initializer and complete the type. 7404 if (T->isIncompleteArrayType()) { 7405 completeExprArrayBound(E); 7406 T = E->getType(); 7407 } 7408 7409 // FIXME: Are there other cases which require instantiating something other 7410 // than the type to complete the type of an expression? 7411 7412 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 7413 } 7414 7415 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 7416 BoundTypeDiagnoser<> Diagnoser(DiagID); 7417 return RequireCompleteExprType(E, Diagnoser); 7418 } 7419 7420 /// @brief Ensure that the type T is a complete type. 7421 /// 7422 /// This routine checks whether the type @p T is complete in any 7423 /// context where a complete type is required. If @p T is a complete 7424 /// type, returns false. If @p T is a class template specialization, 7425 /// this routine then attempts to perform class template 7426 /// instantiation. If instantiation fails, or if @p T is incomplete 7427 /// and cannot be completed, issues the diagnostic @p diag (giving it 7428 /// the type @p T) and returns true. 7429 /// 7430 /// @param Loc The location in the source that the incomplete type 7431 /// diagnostic should refer to. 7432 /// 7433 /// @param T The type that this routine is examining for completeness. 7434 /// 7435 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 7436 /// @c false otherwise. 7437 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 7438 TypeDiagnoser &Diagnoser) { 7439 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser)) 7440 return true; 7441 if (const TagType *Tag = T->getAs<TagType>()) { 7442 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 7443 Tag->getDecl()->setCompleteDefinitionRequired(); 7444 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 7445 } 7446 } 7447 return false; 7448 } 7449 7450 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { 7451 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; 7452 if (!Suggested) 7453 return false; 7454 7455 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext 7456 // and isolate from other C++ specific checks. 7457 StructuralEquivalenceContext Ctx( 7458 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, 7459 false /*StrictTypeSpelling*/, true /*Complain*/, 7460 true /*ErrorOnTagTypeMismatch*/); 7461 return Ctx.IsStructurallyEquivalent(D, Suggested); 7462 } 7463 7464 /// \brief Determine whether there is any declaration of \p D that was ever a 7465 /// definition (perhaps before module merging) and is currently visible. 7466 /// \param D The definition of the entity. 7467 /// \param Suggested Filled in with the declaration that should be made visible 7468 /// in order to provide a definition of this entity. 7469 /// \param OnlyNeedComplete If \c true, we only need the type to be complete, 7470 /// not defined. This only matters for enums with a fixed underlying 7471 /// type, since in all other cases, a type is complete if and only if it 7472 /// is defined. 7473 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 7474 bool OnlyNeedComplete) { 7475 // Easy case: if we don't have modules, all declarations are visible. 7476 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) 7477 return true; 7478 7479 // If this definition was instantiated from a template, map back to the 7480 // pattern from which it was instantiated. 7481 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { 7482 // We're in the middle of defining it; this definition should be treated 7483 // as visible. 7484 return true; 7485 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 7486 if (auto *Pattern = RD->getTemplateInstantiationPattern()) 7487 RD = Pattern; 7488 D = RD->getDefinition(); 7489 } else if (auto *ED = dyn_cast<EnumDecl>(D)) { 7490 if (auto *Pattern = ED->getTemplateInstantiationPattern()) 7491 ED = Pattern; 7492 if (OnlyNeedComplete && ED->isFixed()) { 7493 // If the enum has a fixed underlying type, and we're only looking for a 7494 // complete type (not a definition), any visible declaration of it will 7495 // do. 7496 *Suggested = nullptr; 7497 for (auto *Redecl : ED->redecls()) { 7498 if (isVisible(Redecl)) 7499 return true; 7500 if (Redecl->isThisDeclarationADefinition() || 7501 (Redecl->isCanonicalDecl() && !*Suggested)) 7502 *Suggested = Redecl; 7503 } 7504 return false; 7505 } 7506 D = ED->getDefinition(); 7507 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { 7508 if (auto *Pattern = FD->getTemplateInstantiationPattern()) 7509 FD = Pattern; 7510 D = FD->getDefinition(); 7511 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 7512 if (auto *Pattern = VD->getTemplateInstantiationPattern()) 7513 VD = Pattern; 7514 D = VD->getDefinition(); 7515 } 7516 assert(D && "missing definition for pattern of instantiated definition"); 7517 7518 *Suggested = D; 7519 if (isVisible(D)) 7520 return true; 7521 7522 // The external source may have additional definitions of this entity that are 7523 // visible, so complete the redeclaration chain now and ask again. 7524 if (auto *Source = Context.getExternalSource()) { 7525 Source->CompleteRedeclChain(D); 7526 return isVisible(D); 7527 } 7528 7529 return false; 7530 } 7531 7532 /// Locks in the inheritance model for the given class and all of its bases. 7533 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { 7534 RD = RD->getMostRecentDecl(); 7535 if (!RD->hasAttr<MSInheritanceAttr>()) { 7536 MSInheritanceAttr::Spelling IM; 7537 7538 switch (S.MSPointerToMemberRepresentationMethod) { 7539 case LangOptions::PPTMK_BestCase: 7540 IM = RD->calculateInheritanceModel(); 7541 break; 7542 case LangOptions::PPTMK_FullGeneralitySingleInheritance: 7543 IM = MSInheritanceAttr::Keyword_single_inheritance; 7544 break; 7545 case LangOptions::PPTMK_FullGeneralityMultipleInheritance: 7546 IM = MSInheritanceAttr::Keyword_multiple_inheritance; 7547 break; 7548 case LangOptions::PPTMK_FullGeneralityVirtualInheritance: 7549 IM = MSInheritanceAttr::Keyword_unspecified_inheritance; 7550 break; 7551 } 7552 7553 RD->addAttr(MSInheritanceAttr::CreateImplicit( 7554 S.getASTContext(), IM, 7555 /*BestCase=*/S.MSPointerToMemberRepresentationMethod == 7556 LangOptions::PPTMK_BestCase, 7557 S.ImplicitMSInheritanceAttrLoc.isValid() 7558 ? S.ImplicitMSInheritanceAttrLoc 7559 : RD->getSourceRange())); 7560 S.Consumer.AssignInheritanceModel(RD); 7561 } 7562 } 7563 7564 /// \brief The implementation of RequireCompleteType 7565 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 7566 TypeDiagnoser *Diagnoser) { 7567 // FIXME: Add this assertion to make sure we always get instantiation points. 7568 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 7569 // FIXME: Add this assertion to help us flush out problems with 7570 // checking for dependent types and type-dependent expressions. 7571 // 7572 // assert(!T->isDependentType() && 7573 // "Can't ask whether a dependent type is complete"); 7574 7575 // We lock in the inheritance model once somebody has asked us to ensure 7576 // that a pointer-to-member type is complete. 7577 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 7578 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { 7579 if (!MPTy->getClass()->isDependentType()) { 7580 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); 7581 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); 7582 } 7583 } 7584 } 7585 7586 NamedDecl *Def = nullptr; 7587 bool Incomplete = T->isIncompleteType(&Def); 7588 7589 // Check that any necessary explicit specializations are visible. For an 7590 // enum, we just need the declaration, so don't check this. 7591 if (Def && !isa<EnumDecl>(Def)) 7592 checkSpecializationVisibility(Loc, Def); 7593 7594 // If we have a complete type, we're done. 7595 if (!Incomplete) { 7596 // If we know about the definition but it is not visible, complain. 7597 NamedDecl *SuggestedDef = nullptr; 7598 if (Def && 7599 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { 7600 // If the user is going to see an error here, recover by making the 7601 // definition visible. 7602 bool TreatAsComplete = Diagnoser && !isSFINAEContext(); 7603 if (Diagnoser) 7604 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition, 7605 /*Recover*/TreatAsComplete); 7606 return !TreatAsComplete; 7607 } else if (Def && !TemplateInstCallbacks.empty()) { 7608 CodeSynthesisContext TempInst; 7609 TempInst.Kind = CodeSynthesisContext::Memoization; 7610 TempInst.Template = Def; 7611 TempInst.Entity = Def; 7612 TempInst.PointOfInstantiation = Loc; 7613 atTemplateBegin(TemplateInstCallbacks, *this, TempInst); 7614 atTemplateEnd(TemplateInstCallbacks, *this, TempInst); 7615 } 7616 7617 return false; 7618 } 7619 7620 const TagType *Tag = T->getAs<TagType>(); 7621 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>(); 7622 7623 // If there's an unimported definition of this type in a module (for 7624 // instance, because we forward declared it, then imported the definition), 7625 // import that definition now. 7626 // 7627 // FIXME: What about other cases where an import extends a redeclaration 7628 // chain for a declaration that can be accessed through a mechanism other 7629 // than name lookup (eg, referenced in a template, or a variable whose type 7630 // could be completed by the module)? 7631 // 7632 // FIXME: Should we map through to the base array element type before 7633 // checking for a tag type? 7634 if (Tag || IFace) { 7635 NamedDecl *D = 7636 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl(); 7637 7638 // Avoid diagnosing invalid decls as incomplete. 7639 if (D->isInvalidDecl()) 7640 return true; 7641 7642 // Give the external AST source a chance to complete the type. 7643 if (auto *Source = Context.getExternalSource()) { 7644 if (Tag) { 7645 TagDecl *TagD = Tag->getDecl(); 7646 if (TagD->hasExternalLexicalStorage()) 7647 Source->CompleteType(TagD); 7648 } else { 7649 ObjCInterfaceDecl *IFaceD = IFace->getDecl(); 7650 if (IFaceD->hasExternalLexicalStorage()) 7651 Source->CompleteType(IFace->getDecl()); 7652 } 7653 // If the external source completed the type, go through the motions 7654 // again to ensure we're allowed to use the completed type. 7655 if (!T->isIncompleteType()) 7656 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 7657 } 7658 } 7659 7660 // If we have a class template specialization or a class member of a 7661 // class template specialization, or an array with known size of such, 7662 // try to instantiate it. 7663 QualType MaybeTemplate = T; 7664 while (const ConstantArrayType *Array 7665 = Context.getAsConstantArrayType(MaybeTemplate)) 7666 MaybeTemplate = Array->getElementType(); 7667 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 7668 bool Instantiated = false; 7669 bool Diagnosed = false; 7670 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 7671 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 7672 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 7673 Diagnosed = InstantiateClassTemplateSpecialization( 7674 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, 7675 /*Complain=*/Diagnoser); 7676 Instantiated = true; 7677 } 7678 } else if (CXXRecordDecl *Rec 7679 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 7680 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); 7681 if (!Rec->isBeingDefined() && Pattern) { 7682 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); 7683 assert(MSI && "Missing member specialization information?"); 7684 // This record was instantiated from a class within a template. 7685 if (MSI->getTemplateSpecializationKind() != 7686 TSK_ExplicitSpecialization) { 7687 Diagnosed = InstantiateClass(Loc, Rec, Pattern, 7688 getTemplateInstantiationArgs(Rec), 7689 TSK_ImplicitInstantiation, 7690 /*Complain=*/Diagnoser); 7691 Instantiated = true; 7692 } 7693 } 7694 } 7695 7696 if (Instantiated) { 7697 // Instantiate* might have already complained that the template is not 7698 // defined, if we asked it to. 7699 if (Diagnoser && Diagnosed) 7700 return true; 7701 // If we instantiated a definition, check that it's usable, even if 7702 // instantiation produced an error, so that repeated calls to this 7703 // function give consistent answers. 7704 if (!T->isIncompleteType()) 7705 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 7706 } 7707 } 7708 7709 // FIXME: If we didn't instantiate a definition because of an explicit 7710 // specialization declaration, check that it's visible. 7711 7712 if (!Diagnoser) 7713 return true; 7714 7715 Diagnoser->diagnose(*this, Loc, T); 7716 7717 // If the type was a forward declaration of a class/struct/union 7718 // type, produce a note. 7719 if (Tag && !Tag->getDecl()->isInvalidDecl()) 7720 Diag(Tag->getDecl()->getLocation(), 7721 Tag->isBeingDefined() ? diag::note_type_being_defined 7722 : diag::note_forward_declaration) 7723 << QualType(Tag, 0); 7724 7725 // If the Objective-C class was a forward declaration, produce a note. 7726 if (IFace && !IFace->getDecl()->isInvalidDecl()) 7727 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); 7728 7729 // If we have external information that we can use to suggest a fix, 7730 // produce a note. 7731 if (ExternalSource) 7732 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); 7733 7734 return true; 7735 } 7736 7737 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 7738 unsigned DiagID) { 7739 BoundTypeDiagnoser<> Diagnoser(DiagID); 7740 return RequireCompleteType(Loc, T, Diagnoser); 7741 } 7742 7743 /// \brief Get diagnostic %select index for tag kind for 7744 /// literal type diagnostic message. 7745 /// WARNING: Indexes apply to particular diagnostics only! 7746 /// 7747 /// \returns diagnostic %select index. 7748 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 7749 switch (Tag) { 7750 case TTK_Struct: return 0; 7751 case TTK_Interface: return 1; 7752 case TTK_Class: return 2; 7753 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 7754 } 7755 } 7756 7757 /// @brief Ensure that the type T is a literal type. 7758 /// 7759 /// This routine checks whether the type @p T is a literal type. If @p T is an 7760 /// incomplete type, an attempt is made to complete it. If @p T is a literal 7761 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 7762 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 7763 /// it the type @p T), along with notes explaining why the type is not a 7764 /// literal type, and returns true. 7765 /// 7766 /// @param Loc The location in the source that the non-literal type 7767 /// diagnostic should refer to. 7768 /// 7769 /// @param T The type that this routine is examining for literalness. 7770 /// 7771 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 7772 /// 7773 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 7774 /// @c false otherwise. 7775 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 7776 TypeDiagnoser &Diagnoser) { 7777 assert(!T->isDependentType() && "type should not be dependent"); 7778 7779 QualType ElemType = Context.getBaseElementType(T); 7780 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && 7781 T->isLiteralType(Context)) 7782 return false; 7783 7784 Diagnoser.diagnose(*this, Loc, T); 7785 7786 if (T->isVariableArrayType()) 7787 return true; 7788 7789 const RecordType *RT = ElemType->getAs<RecordType>(); 7790 if (!RT) 7791 return true; 7792 7793 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 7794 7795 // A partially-defined class type can't be a literal type, because a literal 7796 // class type must have a trivial destructor (which can't be checked until 7797 // the class definition is complete). 7798 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) 7799 return true; 7800 7801 // If the class has virtual base classes, then it's not an aggregate, and 7802 // cannot have any constexpr constructors or a trivial default constructor, 7803 // so is non-literal. This is better to diagnose than the resulting absence 7804 // of constexpr constructors. 7805 if (RD->getNumVBases()) { 7806 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 7807 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 7808 for (const auto &I : RD->vbases()) 7809 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here) 7810 << I.getSourceRange(); 7811 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 7812 !RD->hasTrivialDefaultConstructor()) { 7813 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 7814 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 7815 for (const auto &I : RD->bases()) { 7816 if (!I.getType()->isLiteralType(Context)) { 7817 Diag(I.getLocStart(), 7818 diag::note_non_literal_base_class) 7819 << RD << I.getType() << I.getSourceRange(); 7820 return true; 7821 } 7822 } 7823 for (const auto *I : RD->fields()) { 7824 if (!I->getType()->isLiteralType(Context) || 7825 I->getType().isVolatileQualified()) { 7826 Diag(I->getLocation(), diag::note_non_literal_field) 7827 << RD << I << I->getType() 7828 << I->getType().isVolatileQualified(); 7829 return true; 7830 } 7831 } 7832 } else if (!RD->hasTrivialDestructor()) { 7833 // All fields and bases are of literal types, so have trivial destructors. 7834 // If this class's destructor is non-trivial it must be user-declared. 7835 CXXDestructorDecl *Dtor = RD->getDestructor(); 7836 assert(Dtor && "class has literal fields and bases but no dtor?"); 7837 if (!Dtor) 7838 return true; 7839 7840 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 7841 diag::note_non_literal_user_provided_dtor : 7842 diag::note_non_literal_nontrivial_dtor) << RD; 7843 if (!Dtor->isUserProvided()) 7844 SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI, 7845 /*Diagnose*/true); 7846 } 7847 7848 return true; 7849 } 7850 7851 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 7852 BoundTypeDiagnoser<> Diagnoser(DiagID); 7853 return RequireLiteralType(Loc, T, Diagnoser); 7854 } 7855 7856 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 7857 /// and qualified by the nested-name-specifier contained in SS. 7858 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 7859 const CXXScopeSpec &SS, QualType T) { 7860 if (T.isNull()) 7861 return T; 7862 NestedNameSpecifier *NNS; 7863 if (SS.isValid()) 7864 NNS = SS.getScopeRep(); 7865 else { 7866 if (Keyword == ETK_None) 7867 return T; 7868 NNS = nullptr; 7869 } 7870 return Context.getElaboratedType(Keyword, NNS, T); 7871 } 7872 7873 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 7874 ExprResult ER = CheckPlaceholderExpr(E); 7875 if (ER.isInvalid()) return QualType(); 7876 E = ER.get(); 7877 7878 if (!getLangOpts().CPlusPlus && E->refersToBitField()) 7879 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; 7880 7881 if (!E->isTypeDependent()) { 7882 QualType T = E->getType(); 7883 if (const TagType *TT = T->getAs<TagType>()) 7884 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 7885 } 7886 return Context.getTypeOfExprType(E); 7887 } 7888 7889 /// getDecltypeForExpr - Given an expr, will return the decltype for 7890 /// that expression, according to the rules in C++11 7891 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 7892 static QualType getDecltypeForExpr(Sema &S, Expr *E) { 7893 if (E->isTypeDependent()) 7894 return S.Context.DependentTy; 7895 7896 // C++11 [dcl.type.simple]p4: 7897 // The type denoted by decltype(e) is defined as follows: 7898 // 7899 // - if e is an unparenthesized id-expression or an unparenthesized class 7900 // member access (5.2.5), decltype(e) is the type of the entity named 7901 // by e. If there is no such entity, or if e names a set of overloaded 7902 // functions, the program is ill-formed; 7903 // 7904 // We apply the same rules for Objective-C ivar and property references. 7905 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 7906 const ValueDecl *VD = DRE->getDecl(); 7907 return VD->getType(); 7908 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 7909 if (const ValueDecl *VD = ME->getMemberDecl()) 7910 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD)) 7911 return VD->getType(); 7912 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { 7913 return IR->getDecl()->getType(); 7914 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { 7915 if (PR->isExplicitProperty()) 7916 return PR->getExplicitProperty()->getType(); 7917 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { 7918 return PE->getType(); 7919 } 7920 7921 // C++11 [expr.lambda.prim]p18: 7922 // Every occurrence of decltype((x)) where x is a possibly 7923 // parenthesized id-expression that names an entity of automatic 7924 // storage duration is treated as if x were transformed into an 7925 // access to a corresponding data member of the closure type that 7926 // would have been declared if x were an odr-use of the denoted 7927 // entity. 7928 using namespace sema; 7929 if (S.getCurLambda()) { 7930 if (isa<ParenExpr>(E)) { 7931 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 7932 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 7933 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 7934 if (!T.isNull()) 7935 return S.Context.getLValueReferenceType(T); 7936 } 7937 } 7938 } 7939 } 7940 7941 7942 // C++11 [dcl.type.simple]p4: 7943 // [...] 7944 QualType T = E->getType(); 7945 switch (E->getValueKind()) { 7946 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 7947 // type of e; 7948 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 7949 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 7950 // type of e; 7951 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 7952 // - otherwise, decltype(e) is the type of e. 7953 case VK_RValue: break; 7954 } 7955 7956 return T; 7957 } 7958 7959 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc, 7960 bool AsUnevaluated) { 7961 ExprResult ER = CheckPlaceholderExpr(E); 7962 if (ER.isInvalid()) return QualType(); 7963 E = ER.get(); 7964 7965 if (AsUnevaluated && CodeSynthesisContexts.empty() && 7966 E->HasSideEffects(Context, false)) { 7967 // The expression operand for decltype is in an unevaluated expression 7968 // context, so side effects could result in unintended consequences. 7969 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 7970 } 7971 7972 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 7973 } 7974 7975 QualType Sema::BuildUnaryTransformType(QualType BaseType, 7976 UnaryTransformType::UTTKind UKind, 7977 SourceLocation Loc) { 7978 switch (UKind) { 7979 case UnaryTransformType::EnumUnderlyingType: 7980 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 7981 Diag(Loc, diag::err_only_enums_have_underlying_types); 7982 return QualType(); 7983 } else { 7984 QualType Underlying = BaseType; 7985 if (!BaseType->isDependentType()) { 7986 // The enum could be incomplete if we're parsing its definition or 7987 // recovering from an error. 7988 NamedDecl *FwdDecl = nullptr; 7989 if (BaseType->isIncompleteType(&FwdDecl)) { 7990 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; 7991 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; 7992 return QualType(); 7993 } 7994 7995 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 7996 assert(ED && "EnumType has no EnumDecl"); 7997 7998 DiagnoseUseOfDecl(ED, Loc); 7999 8000 Underlying = ED->getIntegerType(); 8001 assert(!Underlying.isNull()); 8002 } 8003 return Context.getUnaryTransformType(BaseType, Underlying, 8004 UnaryTransformType::EnumUnderlyingType); 8005 } 8006 } 8007 llvm_unreachable("unknown unary transform type"); 8008 } 8009 8010 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 8011 if (!T->isDependentType()) { 8012 // FIXME: It isn't entirely clear whether incomplete atomic types 8013 // are allowed or not; for simplicity, ban them for the moment. 8014 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 8015 return QualType(); 8016 8017 int DisallowedKind = -1; 8018 if (T->isArrayType()) 8019 DisallowedKind = 1; 8020 else if (T->isFunctionType()) 8021 DisallowedKind = 2; 8022 else if (T->isReferenceType()) 8023 DisallowedKind = 3; 8024 else if (T->isAtomicType()) 8025 DisallowedKind = 4; 8026 else if (T.hasQualifiers()) 8027 DisallowedKind = 5; 8028 else if (!T.isTriviallyCopyableType(Context)) 8029 // Some other non-trivially-copyable type (probably a C++ class) 8030 DisallowedKind = 6; 8031 8032 if (DisallowedKind != -1) { 8033 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 8034 return QualType(); 8035 } 8036 8037 // FIXME: Do we need any handling for ARC here? 8038 } 8039 8040 // Build the pointer type. 8041 return Context.getAtomicType(T); 8042 } 8043