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 "clang/Sema/SemaInternal.h" 15 #include "TypeLocBuilder.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTMutationListener.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/Parse/ParseDiagnostic.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/Template.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include "llvm/Support/ErrorHandling.h" 36 37 using namespace clang; 38 39 enum TypeDiagSelector { 40 TDS_Function, 41 TDS_Pointer, 42 TDS_ObjCObjOrBlock 43 }; 44 45 /// isOmittedBlockReturnType - Return true if this declarator is missing a 46 /// return type because this is a omitted return type on a block literal. 47 static bool isOmittedBlockReturnType(const Declarator &D) { 48 if (D.getContext() != Declarator::BlockLiteralContext || 49 D.getDeclSpec().hasTypeSpecifier()) 50 return false; 51 52 if (D.getNumTypeObjects() == 0) 53 return true; // ^{ ... } 54 55 if (D.getNumTypeObjects() == 1 && 56 D.getTypeObject(0).Kind == DeclaratorChunk::Function) 57 return true; // ^(int X, float Y) { ... } 58 59 return false; 60 } 61 62 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which 63 /// doesn't apply to the given type. 64 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr, 65 QualType type) { 66 TypeDiagSelector WhichType; 67 bool useExpansionLoc = true; 68 switch (attr.getKind()) { 69 case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break; 70 case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break; 71 default: 72 // Assume everything else was a function attribute. 73 WhichType = TDS_Function; 74 useExpansionLoc = false; 75 break; 76 } 77 78 SourceLocation loc = attr.getLoc(); 79 StringRef name = attr.getName()->getName(); 80 81 // The GC attributes are usually written with macros; special-case them. 82 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident 83 : nullptr; 84 if (useExpansionLoc && loc.isMacroID() && II) { 85 if (II->isStr("strong")) { 86 if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; 87 } else if (II->isStr("weak")) { 88 if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; 89 } 90 } 91 92 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType 93 << type; 94 } 95 96 // objc_gc applies to Objective-C pointers or, otherwise, to the 97 // smallest available pointer type (i.e. 'void*' in 'void**'). 98 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \ 99 case AttributeList::AT_ObjCGC: \ 100 case AttributeList::AT_ObjCOwnership 101 102 // Function type attributes. 103 #define FUNCTION_TYPE_ATTRS_CASELIST \ 104 case AttributeList::AT_NoReturn: \ 105 case AttributeList::AT_CDecl: \ 106 case AttributeList::AT_FastCall: \ 107 case AttributeList::AT_StdCall: \ 108 case AttributeList::AT_ThisCall: \ 109 case AttributeList::AT_Pascal: \ 110 case AttributeList::AT_VectorCall: \ 111 case AttributeList::AT_MSABI: \ 112 case AttributeList::AT_SysVABI: \ 113 case AttributeList::AT_Regparm: \ 114 case AttributeList::AT_Pcs: \ 115 case AttributeList::AT_PnaclCall: \ 116 case AttributeList::AT_IntelOclBicc 117 118 // Microsoft-specific type qualifiers. 119 #define MS_TYPE_ATTRS_CASELIST \ 120 case AttributeList::AT_Ptr32: \ 121 case AttributeList::AT_Ptr64: \ 122 case AttributeList::AT_SPtr: \ 123 case AttributeList::AT_UPtr 124 125 namespace { 126 /// An object which stores processing state for the entire 127 /// GetTypeForDeclarator process. 128 class TypeProcessingState { 129 Sema &sema; 130 131 /// The declarator being processed. 132 Declarator &declarator; 133 134 /// The index of the declarator chunk we're currently processing. 135 /// May be the total number of valid chunks, indicating the 136 /// DeclSpec. 137 unsigned chunkIndex; 138 139 /// Whether there are non-trivial modifications to the decl spec. 140 bool trivial; 141 142 /// Whether we saved the attributes in the decl spec. 143 bool hasSavedAttrs; 144 145 /// The original set of attributes on the DeclSpec. 146 SmallVector<AttributeList*, 2> savedAttrs; 147 148 /// A list of attributes to diagnose the uselessness of when the 149 /// processing is complete. 150 SmallVector<AttributeList*, 2> ignoredTypeAttrs; 151 152 public: 153 TypeProcessingState(Sema &sema, Declarator &declarator) 154 : sema(sema), declarator(declarator), 155 chunkIndex(declarator.getNumTypeObjects()), 156 trivial(true), hasSavedAttrs(false) {} 157 158 Sema &getSema() const { 159 return sema; 160 } 161 162 Declarator &getDeclarator() const { 163 return declarator; 164 } 165 166 bool isProcessingDeclSpec() const { 167 return chunkIndex == declarator.getNumTypeObjects(); 168 } 169 170 unsigned getCurrentChunkIndex() const { 171 return chunkIndex; 172 } 173 174 void setCurrentChunkIndex(unsigned idx) { 175 assert(idx <= declarator.getNumTypeObjects()); 176 chunkIndex = idx; 177 } 178 179 AttributeList *&getCurrentAttrListRef() const { 180 if (isProcessingDeclSpec()) 181 return getMutableDeclSpec().getAttributes().getListRef(); 182 return declarator.getTypeObject(chunkIndex).getAttrListRef(); 183 } 184 185 /// Save the current set of attributes on the DeclSpec. 186 void saveDeclSpecAttrs() { 187 // Don't try to save them multiple times. 188 if (hasSavedAttrs) return; 189 190 DeclSpec &spec = getMutableDeclSpec(); 191 for (AttributeList *attr = spec.getAttributes().getList(); attr; 192 attr = attr->getNext()) 193 savedAttrs.push_back(attr); 194 trivial &= savedAttrs.empty(); 195 hasSavedAttrs = true; 196 } 197 198 /// Record that we had nowhere to put the given type attribute. 199 /// We will diagnose such attributes later. 200 void addIgnoredTypeAttr(AttributeList &attr) { 201 ignoredTypeAttrs.push_back(&attr); 202 } 203 204 /// Diagnose all the ignored type attributes, given that the 205 /// declarator worked out to the given type. 206 void diagnoseIgnoredTypeAttrs(QualType type) const { 207 for (SmallVectorImpl<AttributeList*>::const_iterator 208 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end(); 209 i != e; ++i) 210 diagnoseBadTypeAttribute(getSema(), **i, type); 211 } 212 213 ~TypeProcessingState() { 214 if (trivial) return; 215 216 restoreDeclSpecAttrs(); 217 } 218 219 private: 220 DeclSpec &getMutableDeclSpec() const { 221 return const_cast<DeclSpec&>(declarator.getDeclSpec()); 222 } 223 224 void restoreDeclSpecAttrs() { 225 assert(hasSavedAttrs); 226 227 if (savedAttrs.empty()) { 228 getMutableDeclSpec().getAttributes().set(nullptr); 229 return; 230 } 231 232 getMutableDeclSpec().getAttributes().set(savedAttrs[0]); 233 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i) 234 savedAttrs[i]->setNext(savedAttrs[i+1]); 235 savedAttrs.back()->setNext(nullptr); 236 } 237 }; 238 } 239 240 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) { 241 attr.setNext(head); 242 head = &attr; 243 } 244 245 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) { 246 if (head == &attr) { 247 head = attr.getNext(); 248 return; 249 } 250 251 AttributeList *cur = head; 252 while (true) { 253 assert(cur && cur->getNext() && "ran out of attrs?"); 254 if (cur->getNext() == &attr) { 255 cur->setNext(attr.getNext()); 256 return; 257 } 258 cur = cur->getNext(); 259 } 260 } 261 262 static void moveAttrFromListToList(AttributeList &attr, 263 AttributeList *&fromList, 264 AttributeList *&toList) { 265 spliceAttrOutOfList(attr, fromList); 266 spliceAttrIntoList(attr, toList); 267 } 268 269 /// The location of a type attribute. 270 enum TypeAttrLocation { 271 /// The attribute is in the decl-specifier-seq. 272 TAL_DeclSpec, 273 /// The attribute is part of a DeclaratorChunk. 274 TAL_DeclChunk, 275 /// The attribute is immediately after the declaration's name. 276 TAL_DeclName 277 }; 278 279 static void processTypeAttrs(TypeProcessingState &state, 280 QualType &type, TypeAttrLocation TAL, 281 AttributeList *attrs); 282 283 static bool handleFunctionTypeAttr(TypeProcessingState &state, 284 AttributeList &attr, 285 QualType &type); 286 287 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, 288 AttributeList &attr, 289 QualType &type); 290 291 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 292 AttributeList &attr, QualType &type); 293 294 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 295 AttributeList &attr, QualType &type); 296 297 static bool handleObjCPointerTypeAttr(TypeProcessingState &state, 298 AttributeList &attr, QualType &type) { 299 if (attr.getKind() == AttributeList::AT_ObjCGC) 300 return handleObjCGCTypeAttr(state, attr, type); 301 assert(attr.getKind() == AttributeList::AT_ObjCOwnership); 302 return handleObjCOwnershipTypeAttr(state, attr, type); 303 } 304 305 /// Given the index of a declarator chunk, check whether that chunk 306 /// directly specifies the return type of a function and, if so, find 307 /// an appropriate place for it. 308 /// 309 /// \param i - a notional index which the search will start 310 /// immediately inside 311 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, 312 unsigned i) { 313 assert(i <= declarator.getNumTypeObjects()); 314 315 DeclaratorChunk *result = nullptr; 316 317 // First, look inwards past parens for a function declarator. 318 for (; i != 0; --i) { 319 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); 320 switch (fnChunk.Kind) { 321 case DeclaratorChunk::Paren: 322 continue; 323 324 // If we find anything except a function, bail out. 325 case DeclaratorChunk::Pointer: 326 case DeclaratorChunk::BlockPointer: 327 case DeclaratorChunk::Array: 328 case DeclaratorChunk::Reference: 329 case DeclaratorChunk::MemberPointer: 330 return result; 331 332 // If we do find a function declarator, scan inwards from that, 333 // looking for a block-pointer declarator. 334 case DeclaratorChunk::Function: 335 for (--i; i != 0; --i) { 336 DeclaratorChunk &blockChunk = declarator.getTypeObject(i-1); 337 switch (blockChunk.Kind) { 338 case DeclaratorChunk::Paren: 339 case DeclaratorChunk::Pointer: 340 case DeclaratorChunk::Array: 341 case DeclaratorChunk::Function: 342 case DeclaratorChunk::Reference: 343 case DeclaratorChunk::MemberPointer: 344 continue; 345 case DeclaratorChunk::BlockPointer: 346 result = &blockChunk; 347 goto continue_outer; 348 } 349 llvm_unreachable("bad declarator chunk kind"); 350 } 351 352 // If we run out of declarators doing that, we're done. 353 return result; 354 } 355 llvm_unreachable("bad declarator chunk kind"); 356 357 // Okay, reconsider from our new point. 358 continue_outer: ; 359 } 360 361 // Ran out of chunks, bail out. 362 return result; 363 } 364 365 /// Given that an objc_gc attribute was written somewhere on a 366 /// declaration *other* than on the declarator itself (for which, use 367 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it 368 /// didn't apply in whatever position it was written in, try to move 369 /// it to a more appropriate position. 370 static void distributeObjCPointerTypeAttr(TypeProcessingState &state, 371 AttributeList &attr, 372 QualType type) { 373 Declarator &declarator = state.getDeclarator(); 374 375 // Move it to the outermost normal or block pointer declarator. 376 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 377 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 378 switch (chunk.Kind) { 379 case DeclaratorChunk::Pointer: 380 case DeclaratorChunk::BlockPointer: { 381 // But don't move an ARC ownership attribute to the return type 382 // of a block. 383 DeclaratorChunk *destChunk = nullptr; 384 if (state.isProcessingDeclSpec() && 385 attr.getKind() == AttributeList::AT_ObjCOwnership) 386 destChunk = maybeMovePastReturnType(declarator, i - 1); 387 if (!destChunk) destChunk = &chunk; 388 389 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 390 destChunk->getAttrListRef()); 391 return; 392 } 393 394 case DeclaratorChunk::Paren: 395 case DeclaratorChunk::Array: 396 continue; 397 398 // We may be starting at the return type of a block. 399 case DeclaratorChunk::Function: 400 if (state.isProcessingDeclSpec() && 401 attr.getKind() == AttributeList::AT_ObjCOwnership) { 402 if (DeclaratorChunk *dest = maybeMovePastReturnType(declarator, i)) { 403 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 404 dest->getAttrListRef()); 405 return; 406 } 407 } 408 goto error; 409 410 // Don't walk through these. 411 case DeclaratorChunk::Reference: 412 case DeclaratorChunk::MemberPointer: 413 goto error; 414 } 415 } 416 error: 417 418 diagnoseBadTypeAttribute(state.getSema(), attr, type); 419 } 420 421 /// Distribute an objc_gc type attribute that was written on the 422 /// declarator. 423 static void 424 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, 425 AttributeList &attr, 426 QualType &declSpecType) { 427 Declarator &declarator = state.getDeclarator(); 428 429 // objc_gc goes on the innermost pointer to something that's not a 430 // pointer. 431 unsigned innermost = -1U; 432 bool considerDeclSpec = true; 433 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 434 DeclaratorChunk &chunk = declarator.getTypeObject(i); 435 switch (chunk.Kind) { 436 case DeclaratorChunk::Pointer: 437 case DeclaratorChunk::BlockPointer: 438 innermost = i; 439 continue; 440 441 case DeclaratorChunk::Reference: 442 case DeclaratorChunk::MemberPointer: 443 case DeclaratorChunk::Paren: 444 case DeclaratorChunk::Array: 445 continue; 446 447 case DeclaratorChunk::Function: 448 considerDeclSpec = false; 449 goto done; 450 } 451 } 452 done: 453 454 // That might actually be the decl spec if we weren't blocked by 455 // anything in the declarator. 456 if (considerDeclSpec) { 457 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { 458 // Splice the attribute into the decl spec. Prevents the 459 // attribute from being applied multiple times and gives 460 // the source-location-filler something to work with. 461 state.saveDeclSpecAttrs(); 462 moveAttrFromListToList(attr, declarator.getAttrListRef(), 463 declarator.getMutableDeclSpec().getAttributes().getListRef()); 464 return; 465 } 466 } 467 468 // Otherwise, if we found an appropriate chunk, splice the attribute 469 // into it. 470 if (innermost != -1U) { 471 moveAttrFromListToList(attr, declarator.getAttrListRef(), 472 declarator.getTypeObject(innermost).getAttrListRef()); 473 return; 474 } 475 476 // Otherwise, diagnose when we're done building the type. 477 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 478 state.addIgnoredTypeAttr(attr); 479 } 480 481 /// A function type attribute was written somewhere in a declaration 482 /// *other* than on the declarator itself or in the decl spec. Given 483 /// that it didn't apply in whatever position it was written in, try 484 /// to move it to a more appropriate position. 485 static void distributeFunctionTypeAttr(TypeProcessingState &state, 486 AttributeList &attr, 487 QualType type) { 488 Declarator &declarator = state.getDeclarator(); 489 490 // Try to push the attribute from the return type of a function to 491 // the function itself. 492 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 493 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 494 switch (chunk.Kind) { 495 case DeclaratorChunk::Function: 496 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 497 chunk.getAttrListRef()); 498 return; 499 500 case DeclaratorChunk::Paren: 501 case DeclaratorChunk::Pointer: 502 case DeclaratorChunk::BlockPointer: 503 case DeclaratorChunk::Array: 504 case DeclaratorChunk::Reference: 505 case DeclaratorChunk::MemberPointer: 506 continue; 507 } 508 } 509 510 diagnoseBadTypeAttribute(state.getSema(), attr, type); 511 } 512 513 /// Try to distribute a function type attribute to the innermost 514 /// function chunk or type. Returns true if the attribute was 515 /// distributed, false if no location was found. 516 static bool 517 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, 518 AttributeList &attr, 519 AttributeList *&attrList, 520 QualType &declSpecType) { 521 Declarator &declarator = state.getDeclarator(); 522 523 // Put it on the innermost function chunk, if there is one. 524 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 525 DeclaratorChunk &chunk = declarator.getTypeObject(i); 526 if (chunk.Kind != DeclaratorChunk::Function) continue; 527 528 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef()); 529 return true; 530 } 531 532 return handleFunctionTypeAttr(state, attr, declSpecType); 533 } 534 535 /// A function type attribute was written in the decl spec. Try to 536 /// apply it somewhere. 537 static void 538 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, 539 AttributeList &attr, 540 QualType &declSpecType) { 541 state.saveDeclSpecAttrs(); 542 543 // C++11 attributes before the decl specifiers actually appertain to 544 // the declarators. Move them straight there. We don't support the 545 // 'put them wherever you like' semantics we allow for GNU attributes. 546 if (attr.isCXX11Attribute()) { 547 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 548 state.getDeclarator().getAttrListRef()); 549 return; 550 } 551 552 // Try to distribute to the innermost. 553 if (distributeFunctionTypeAttrToInnermost(state, attr, 554 state.getCurrentAttrListRef(), 555 declSpecType)) 556 return; 557 558 // If that failed, diagnose the bad attribute when the declarator is 559 // fully built. 560 state.addIgnoredTypeAttr(attr); 561 } 562 563 /// A function type attribute was written on the declarator. Try to 564 /// apply it somewhere. 565 static void 566 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, 567 AttributeList &attr, 568 QualType &declSpecType) { 569 Declarator &declarator = state.getDeclarator(); 570 571 // Try to distribute to the innermost. 572 if (distributeFunctionTypeAttrToInnermost(state, attr, 573 declarator.getAttrListRef(), 574 declSpecType)) 575 return; 576 577 // If that failed, diagnose the bad attribute when the declarator is 578 // fully built. 579 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 580 state.addIgnoredTypeAttr(attr); 581 } 582 583 /// \brief Given that there are attributes written on the declarator 584 /// itself, try to distribute any type attributes to the appropriate 585 /// declarator chunk. 586 /// 587 /// These are attributes like the following: 588 /// int f ATTR; 589 /// int (f ATTR)(); 590 /// but not necessarily this: 591 /// int f() ATTR; 592 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, 593 QualType &declSpecType) { 594 // Collect all the type attributes from the declarator itself. 595 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!"); 596 AttributeList *attr = state.getDeclarator().getAttributes(); 597 AttributeList *next; 598 do { 599 next = attr->getNext(); 600 601 // Do not distribute C++11 attributes. They have strict rules for what 602 // they appertain to. 603 if (attr->isCXX11Attribute()) 604 continue; 605 606 switch (attr->getKind()) { 607 OBJC_POINTER_TYPE_ATTRS_CASELIST: 608 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType); 609 break; 610 611 case AttributeList::AT_NSReturnsRetained: 612 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 613 break; 614 // fallthrough 615 616 FUNCTION_TYPE_ATTRS_CASELIST: 617 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType); 618 break; 619 620 MS_TYPE_ATTRS_CASELIST: 621 // Microsoft type attributes cannot go after the declarator-id. 622 continue; 623 624 default: 625 break; 626 } 627 } while ((attr = next)); 628 } 629 630 /// Add a synthetic '()' to a block-literal declarator if it is 631 /// required, given the return type. 632 static void maybeSynthesizeBlockSignature(TypeProcessingState &state, 633 QualType declSpecType) { 634 Declarator &declarator = state.getDeclarator(); 635 636 // First, check whether the declarator would produce a function, 637 // i.e. whether the innermost semantic chunk is a function. 638 if (declarator.isFunctionDeclarator()) { 639 // If so, make that declarator a prototyped declarator. 640 declarator.getFunctionTypeInfo().hasPrototype = true; 641 return; 642 } 643 644 // If there are any type objects, the type as written won't name a 645 // function, regardless of the decl spec type. This is because a 646 // block signature declarator is always an abstract-declarator, and 647 // abstract-declarators can't just be parentheses chunks. Therefore 648 // we need to build a function chunk unless there are no type 649 // objects and the decl spec type is a function. 650 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) 651 return; 652 653 // Note that there *are* cases with invalid declarators where 654 // declarators consist solely of parentheses. In general, these 655 // occur only in failed efforts to make function declarators, so 656 // faking up the function chunk is still the right thing to do. 657 658 // Otherwise, we need to fake up a function declarator. 659 SourceLocation loc = declarator.getLocStart(); 660 661 // ...and *prepend* it to the declarator. 662 SourceLocation NoLoc; 663 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( 664 /*HasProto=*/true, 665 /*IsAmbiguous=*/false, 666 /*LParenLoc=*/NoLoc, 667 /*ArgInfo=*/nullptr, 668 /*NumArgs=*/0, 669 /*EllipsisLoc=*/NoLoc, 670 /*RParenLoc=*/NoLoc, 671 /*TypeQuals=*/0, 672 /*RefQualifierIsLvalueRef=*/true, 673 /*RefQualifierLoc=*/NoLoc, 674 /*ConstQualifierLoc=*/NoLoc, 675 /*VolatileQualifierLoc=*/NoLoc, 676 /*RestrictQualifierLoc=*/NoLoc, 677 /*MutableLoc=*/NoLoc, 678 EST_None, 679 /*ESpecLoc=*/NoLoc, 680 /*Exceptions=*/nullptr, 681 /*ExceptionRanges=*/nullptr, 682 /*NumExceptions=*/0, 683 /*NoexceptExpr=*/nullptr, 684 loc, loc, declarator)); 685 686 // For consistency, make sure the state still has us as processing 687 // the decl spec. 688 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); 689 state.setCurrentChunkIndex(declarator.getNumTypeObjects()); 690 } 691 692 /// \brief Convert the specified declspec to the appropriate type 693 /// object. 694 /// \param state Specifies the declarator containing the declaration specifier 695 /// to be converted, along with other associated processing state. 696 /// \returns The type described by the declaration specifiers. This function 697 /// never returns null. 698 static QualType ConvertDeclSpecToType(TypeProcessingState &state) { 699 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 700 // checking. 701 702 Sema &S = state.getSema(); 703 Declarator &declarator = state.getDeclarator(); 704 const DeclSpec &DS = declarator.getDeclSpec(); 705 SourceLocation DeclLoc = declarator.getIdentifierLoc(); 706 if (DeclLoc.isInvalid()) 707 DeclLoc = DS.getLocStart(); 708 709 ASTContext &Context = S.Context; 710 711 QualType Result; 712 switch (DS.getTypeSpecType()) { 713 case DeclSpec::TST_void: 714 Result = Context.VoidTy; 715 break; 716 case DeclSpec::TST_char: 717 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 718 Result = Context.CharTy; 719 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 720 Result = Context.SignedCharTy; 721 else { 722 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 723 "Unknown TSS value"); 724 Result = Context.UnsignedCharTy; 725 } 726 break; 727 case DeclSpec::TST_wchar: 728 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 729 Result = Context.WCharTy; 730 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 731 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 732 << DS.getSpecifierName(DS.getTypeSpecType(), 733 Context.getPrintingPolicy()); 734 Result = Context.getSignedWCharType(); 735 } else { 736 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 737 "Unknown TSS value"); 738 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 739 << DS.getSpecifierName(DS.getTypeSpecType(), 740 Context.getPrintingPolicy()); 741 Result = Context.getUnsignedWCharType(); 742 } 743 break; 744 case DeclSpec::TST_char16: 745 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 746 "Unknown TSS value"); 747 Result = Context.Char16Ty; 748 break; 749 case DeclSpec::TST_char32: 750 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 751 "Unknown TSS value"); 752 Result = Context.Char32Ty; 753 break; 754 case DeclSpec::TST_unspecified: 755 // "<proto1,proto2>" is an objc qualified ID with a missing id. 756 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 757 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 758 (ObjCProtocolDecl*const*)PQ, 759 DS.getNumProtocolQualifiers()); 760 Result = Context.getObjCObjectPointerType(Result); 761 break; 762 } 763 764 // If this is a missing declspec in a block literal return context, then it 765 // is inferred from the return statements inside the block. 766 // The declspec is always missing in a lambda expr context; it is either 767 // specified with a trailing return type or inferred. 768 if (S.getLangOpts().CPlusPlus14 && 769 declarator.getContext() == Declarator::LambdaExprContext) { 770 // In C++1y, a lambda's implicit return type is 'auto'. 771 Result = Context.getAutoDeductType(); 772 break; 773 } else if (declarator.getContext() == Declarator::LambdaExprContext || 774 isOmittedBlockReturnType(declarator)) { 775 Result = Context.DependentTy; 776 break; 777 } 778 779 // Unspecified typespec defaults to int in C90. However, the C90 grammar 780 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 781 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 782 // Note that the one exception to this is function definitions, which are 783 // allowed to be completely missing a declspec. This is handled in the 784 // parser already though by it pretending to have seen an 'int' in this 785 // case. 786 if (S.getLangOpts().ImplicitInt) { 787 // In C89 mode, we only warn if there is a completely missing declspec 788 // when one is not allowed. 789 if (DS.isEmpty()) { 790 S.Diag(DeclLoc, diag::ext_missing_declspec) 791 << DS.getSourceRange() 792 << FixItHint::CreateInsertion(DS.getLocStart(), "int"); 793 } 794 } else if (!DS.hasTypeSpecifier()) { 795 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 796 // "At least one type specifier shall be given in the declaration 797 // specifiers in each declaration, and in the specifier-qualifier list in 798 // each struct declaration and type name." 799 if (S.getLangOpts().CPlusPlus) { 800 S.Diag(DeclLoc, diag::err_missing_type_specifier) 801 << DS.getSourceRange(); 802 803 // When this occurs in C++ code, often something is very broken with the 804 // value being declared, poison it as invalid so we don't get chains of 805 // errors. 806 declarator.setInvalidType(true); 807 } else { 808 S.Diag(DeclLoc, diag::ext_missing_type_specifier) 809 << DS.getSourceRange(); 810 } 811 } 812 813 // FALL THROUGH. 814 case DeclSpec::TST_int: { 815 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 816 switch (DS.getTypeSpecWidth()) { 817 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 818 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 819 case DeclSpec::TSW_long: Result = Context.LongTy; break; 820 case DeclSpec::TSW_longlong: 821 Result = Context.LongLongTy; 822 823 // 'long long' is a C99 or C++11 feature. 824 if (!S.getLangOpts().C99) { 825 if (S.getLangOpts().CPlusPlus) 826 S.Diag(DS.getTypeSpecWidthLoc(), 827 S.getLangOpts().CPlusPlus11 ? 828 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 829 else 830 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 831 } 832 break; 833 } 834 } else { 835 switch (DS.getTypeSpecWidth()) { 836 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 837 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 838 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 839 case DeclSpec::TSW_longlong: 840 Result = Context.UnsignedLongLongTy; 841 842 // 'long long' is a C99 or C++11 feature. 843 if (!S.getLangOpts().C99) { 844 if (S.getLangOpts().CPlusPlus) 845 S.Diag(DS.getTypeSpecWidthLoc(), 846 S.getLangOpts().CPlusPlus11 ? 847 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 848 else 849 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 850 } 851 break; 852 } 853 } 854 break; 855 } 856 case DeclSpec::TST_int128: 857 if (!S.Context.getTargetInfo().hasInt128Type()) 858 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported); 859 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) 860 Result = Context.UnsignedInt128Ty; 861 else 862 Result = Context.Int128Ty; 863 break; 864 case DeclSpec::TST_half: Result = Context.HalfTy; break; 865 case DeclSpec::TST_float: Result = Context.FloatTy; break; 866 case DeclSpec::TST_double: 867 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 868 Result = Context.LongDoubleTy; 869 else 870 Result = Context.DoubleTy; 871 872 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) { 873 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64); 874 declarator.setInvalidType(true); 875 } 876 break; 877 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 878 case DeclSpec::TST_decimal32: // _Decimal32 879 case DeclSpec::TST_decimal64: // _Decimal64 880 case DeclSpec::TST_decimal128: // _Decimal128 881 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 882 Result = Context.IntTy; 883 declarator.setInvalidType(true); 884 break; 885 case DeclSpec::TST_class: 886 case DeclSpec::TST_enum: 887 case DeclSpec::TST_union: 888 case DeclSpec::TST_struct: 889 case DeclSpec::TST_interface: { 890 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl()); 891 if (!D) { 892 // This can happen in C++ with ambiguous lookups. 893 Result = Context.IntTy; 894 declarator.setInvalidType(true); 895 break; 896 } 897 898 // If the type is deprecated or unavailable, diagnose it. 899 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); 900 901 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 902 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!"); 903 904 // TypeQuals handled by caller. 905 Result = Context.getTypeDeclType(D); 906 907 // In both C and C++, make an ElaboratedType. 908 ElaboratedTypeKeyword Keyword 909 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); 910 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result); 911 break; 912 } 913 case DeclSpec::TST_typename: { 914 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 915 DS.getTypeSpecSign() == 0 && 916 "Can't handle qualifiers on typedef names yet!"); 917 Result = S.GetTypeFromParser(DS.getRepAsType()); 918 if (Result.isNull()) 919 declarator.setInvalidType(true); 920 else if (DeclSpec::ProtocolQualifierListTy PQ 921 = DS.getProtocolQualifiers()) { 922 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) { 923 // Silently drop any existing protocol qualifiers. 924 // TODO: determine whether that's the right thing to do. 925 if (ObjT->getNumProtocols()) 926 Result = ObjT->getBaseType(); 927 928 if (DS.getNumProtocolQualifiers()) 929 Result = Context.getObjCObjectType(Result, 930 (ObjCProtocolDecl*const*) PQ, 931 DS.getNumProtocolQualifiers()); 932 } else if (Result->isObjCIdType()) { 933 // id<protocol-list> 934 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 935 (ObjCProtocolDecl*const*) PQ, 936 DS.getNumProtocolQualifiers()); 937 Result = Context.getObjCObjectPointerType(Result); 938 } else if (Result->isObjCClassType()) { 939 // Class<protocol-list> 940 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 941 (ObjCProtocolDecl*const*) PQ, 942 DS.getNumProtocolQualifiers()); 943 Result = Context.getObjCObjectPointerType(Result); 944 } else { 945 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers) 946 << DS.getSourceRange(); 947 declarator.setInvalidType(true); 948 } 949 } 950 951 // TypeQuals handled by caller. 952 break; 953 } 954 case DeclSpec::TST_typeofType: 955 // FIXME: Preserve type source info. 956 Result = S.GetTypeFromParser(DS.getRepAsType()); 957 assert(!Result.isNull() && "Didn't get a type for typeof?"); 958 if (!Result->isDependentType()) 959 if (const TagType *TT = Result->getAs<TagType>()) 960 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); 961 // TypeQuals handled by caller. 962 Result = Context.getTypeOfType(Result); 963 break; 964 case DeclSpec::TST_typeofExpr: { 965 Expr *E = DS.getRepAsExpr(); 966 assert(E && "Didn't get an expression for typeof?"); 967 // TypeQuals handled by caller. 968 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); 969 if (Result.isNull()) { 970 Result = Context.IntTy; 971 declarator.setInvalidType(true); 972 } 973 break; 974 } 975 case DeclSpec::TST_decltype: { 976 Expr *E = DS.getRepAsExpr(); 977 assert(E && "Didn't get an expression for decltype?"); 978 // TypeQuals handled by caller. 979 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); 980 if (Result.isNull()) { 981 Result = Context.IntTy; 982 declarator.setInvalidType(true); 983 } 984 break; 985 } 986 case DeclSpec::TST_underlyingType: 987 Result = S.GetTypeFromParser(DS.getRepAsType()); 988 assert(!Result.isNull() && "Didn't get a type for __underlying_type?"); 989 Result = S.BuildUnaryTransformType(Result, 990 UnaryTransformType::EnumUnderlyingType, 991 DS.getTypeSpecTypeLoc()); 992 if (Result.isNull()) { 993 Result = Context.IntTy; 994 declarator.setInvalidType(true); 995 } 996 break; 997 998 case DeclSpec::TST_auto: 999 // TypeQuals handled by caller. 1000 // If auto is mentioned in a lambda parameter context, convert it to a 1001 // template parameter type immediately, with the appropriate depth and 1002 // index, and update sema's state (LambdaScopeInfo) for the current lambda 1003 // being analyzed (which tracks the invented type template parameter). 1004 if (declarator.getContext() == Declarator::LambdaExprParameterContext) { 1005 sema::LambdaScopeInfo *LSI = S.getCurLambda(); 1006 assert(LSI && "No LambdaScopeInfo on the stack!"); 1007 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth; 1008 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size(); 1009 const bool IsParameterPack = declarator.hasEllipsis(); 1010 1011 // Create a name for the invented template parameter type. 1012 std::string InventedTemplateParamName = "$auto-"; 1013 llvm::raw_string_ostream ss(InventedTemplateParamName); 1014 ss << TemplateParameterDepth; 1015 ss << "-" << AutoParameterPosition; 1016 ss.flush(); 1017 1018 IdentifierInfo& TemplateParamII = Context.Idents.get( 1019 InventedTemplateParamName.c_str()); 1020 // Turns out we must create the TemplateTypeParmDecl here to 1021 // retrieve the corresponding template parameter type. 1022 TemplateTypeParmDecl *CorrespondingTemplateParam = 1023 TemplateTypeParmDecl::Create(Context, 1024 // Temporarily add to the TranslationUnit DeclContext. When the 1025 // associated TemplateParameterList is attached to a template 1026 // declaration (such as FunctionTemplateDecl), the DeclContext 1027 // for each template parameter gets updated appropriately via 1028 // a call to AdoptTemplateParameterList. 1029 Context.getTranslationUnitDecl(), 1030 /*KeyLoc*/ SourceLocation(), 1031 /*NameLoc*/ declarator.getLocStart(), 1032 TemplateParameterDepth, 1033 AutoParameterPosition, // our template param index 1034 /* Identifier*/ &TemplateParamII, false, IsParameterPack); 1035 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam); 1036 // Replace the 'auto' in the function parameter with this invented 1037 // template type parameter. 1038 Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0); 1039 } else { 1040 Result = Context.getAutoType(QualType(), /*decltype(auto)*/false, false); 1041 } 1042 break; 1043 1044 case DeclSpec::TST_decltype_auto: 1045 Result = Context.getAutoType(QualType(), 1046 /*decltype(auto)*/true, 1047 /*IsDependent*/ false); 1048 break; 1049 1050 case DeclSpec::TST_unknown_anytype: 1051 Result = Context.UnknownAnyTy; 1052 break; 1053 1054 case DeclSpec::TST_atomic: 1055 Result = S.GetTypeFromParser(DS.getRepAsType()); 1056 assert(!Result.isNull() && "Didn't get a type for _Atomic?"); 1057 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); 1058 if (Result.isNull()) { 1059 Result = Context.IntTy; 1060 declarator.setInvalidType(true); 1061 } 1062 break; 1063 1064 case DeclSpec::TST_error: 1065 Result = Context.IntTy; 1066 declarator.setInvalidType(true); 1067 break; 1068 } 1069 1070 // Handle complex types. 1071 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 1072 if (S.getLangOpts().Freestanding) 1073 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 1074 Result = Context.getComplexType(Result); 1075 } else if (DS.isTypeAltiVecVector()) { 1076 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); 1077 assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); 1078 VectorType::VectorKind VecKind = VectorType::AltiVecVector; 1079 if (DS.isTypeAltiVecPixel()) 1080 VecKind = VectorType::AltiVecPixel; 1081 else if (DS.isTypeAltiVecBool()) 1082 VecKind = VectorType::AltiVecBool; 1083 Result = Context.getVectorType(Result, 128/typeSize, VecKind); 1084 } 1085 1086 // FIXME: Imaginary. 1087 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) 1088 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); 1089 1090 // Before we process any type attributes, synthesize a block literal 1091 // function declarator if necessary. 1092 if (declarator.getContext() == Declarator::BlockLiteralContext) 1093 maybeSynthesizeBlockSignature(state, Result); 1094 1095 // Apply any type attributes from the decl spec. This may cause the 1096 // list of type attributes to be temporarily saved while the type 1097 // attributes are pushed around. 1098 if (AttributeList *attrs = DS.getAttributes().getList()) 1099 processTypeAttrs(state, Result, TAL_DeclSpec, attrs); 1100 1101 // Apply const/volatile/restrict qualifiers to T. 1102 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 1103 1104 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 1105 // of a function type includes any type qualifiers, the behavior is 1106 // undefined." 1107 if (Result->isFunctionType() && TypeQuals) { 1108 if (TypeQuals & DeclSpec::TQ_const) 1109 S.Diag(DS.getConstSpecLoc(), diag::warn_typecheck_function_qualifiers) 1110 << Result << DS.getSourceRange(); 1111 else if (TypeQuals & DeclSpec::TQ_volatile) 1112 S.Diag(DS.getVolatileSpecLoc(), diag::warn_typecheck_function_qualifiers) 1113 << Result << DS.getSourceRange(); 1114 else { 1115 assert((TypeQuals & (DeclSpec::TQ_restrict | DeclSpec::TQ_atomic)) && 1116 "Has CVRA quals but not C, V, R, or A?"); 1117 // No diagnostic; we'll diagnose 'restrict' or '_Atomic' applied to a 1118 // function type later, in BuildQualifiedType. 1119 } 1120 } 1121 1122 // C++11 [dcl.ref]p1: 1123 // Cv-qualified references are ill-formed except when the 1124 // cv-qualifiers are introduced through the use of a typedef-name 1125 // or decltype-specifier, in which case the cv-qualifiers are ignored. 1126 // 1127 // There don't appear to be any other contexts in which a cv-qualified 1128 // reference type could be formed, so the 'ill-formed' clause here appears 1129 // to never happen. 1130 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 1131 TypeQuals && Result->isReferenceType()) { 1132 // If this occurs outside a template instantiation, warn the user about 1133 // it; they probably didn't mean to specify a redundant qualifier. 1134 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; 1135 QualLoc Quals[] = { 1136 QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), 1137 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), 1138 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc()) 1139 }; 1140 for (unsigned I = 0, N = llvm::array_lengthof(Quals); I != N; ++I) { 1141 if (S.ActiveTemplateInstantiations.empty()) { 1142 if (TypeQuals & Quals[I].first) 1143 S.Diag(Quals[I].second, diag::warn_typecheck_reference_qualifiers) 1144 << DeclSpec::getSpecifierName(Quals[I].first) << Result 1145 << FixItHint::CreateRemoval(Quals[I].second); 1146 } 1147 TypeQuals &= ~Quals[I].first; 1148 } 1149 } 1150 1151 // C90 6.5.3 constraints: "The same type qualifier shall not appear more 1152 // than once in the same specifier-list or qualifier-list, either directly 1153 // or via one or more typedefs." 1154 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus 1155 && TypeQuals & Result.getCVRQualifiers()) { 1156 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { 1157 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) 1158 << "const"; 1159 } 1160 1161 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { 1162 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) 1163 << "volatile"; 1164 } 1165 1166 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to 1167 // produce a warning in this case. 1168 } 1169 1170 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); 1171 1172 // If adding qualifiers fails, just use the unqualified type. 1173 if (Qualified.isNull()) 1174 declarator.setInvalidType(true); 1175 else 1176 Result = Qualified; 1177 } 1178 1179 return Result; 1180 } 1181 1182 static std::string getPrintableNameForEntity(DeclarationName Entity) { 1183 if (Entity) 1184 return Entity.getAsString(); 1185 1186 return "type name"; 1187 } 1188 1189 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 1190 Qualifiers Qs, const DeclSpec *DS) { 1191 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 1192 // object or incomplete types shall not be restrict-qualified." 1193 if (Qs.hasRestrict()) { 1194 unsigned DiagID = 0; 1195 QualType ProblemTy; 1196 1197 if (T->isAnyPointerType() || T->isReferenceType() || 1198 T->isMemberPointerType()) { 1199 QualType EltTy; 1200 if (T->isObjCObjectPointerType()) 1201 EltTy = T; 1202 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) 1203 EltTy = PTy->getPointeeType(); 1204 else 1205 EltTy = T->getPointeeType(); 1206 1207 // If we have a pointer or reference, the pointee must have an object 1208 // incomplete type. 1209 if (!EltTy->isIncompleteOrObjectType()) { 1210 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 1211 ProblemTy = EltTy; 1212 } 1213 } else if (!T->isDependentType()) { 1214 DiagID = diag::err_typecheck_invalid_restrict_not_pointer; 1215 ProblemTy = T; 1216 } 1217 1218 if (DiagID) { 1219 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; 1220 Qs.removeRestrict(); 1221 } 1222 } 1223 1224 return Context.getQualifiedType(T, Qs); 1225 } 1226 1227 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 1228 unsigned CVRA, const DeclSpec *DS) { 1229 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic. 1230 unsigned CVR = CVRA & ~DeclSpec::TQ_atomic; 1231 1232 // C11 6.7.3/5: 1233 // If the same qualifier appears more than once in the same 1234 // specifier-qualifier-list, either directly or via one or more typedefs, 1235 // the behavior is the same as if it appeared only once. 1236 // 1237 // It's not specified what happens when the _Atomic qualifier is applied to 1238 // a type specified with the _Atomic specifier, but we assume that this 1239 // should be treated as if the _Atomic qualifier appeared multiple times. 1240 if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) { 1241 // C11 6.7.3/5: 1242 // If other qualifiers appear along with the _Atomic qualifier in a 1243 // specifier-qualifier-list, the resulting type is the so-qualified 1244 // atomic type. 1245 // 1246 // Don't need to worry about array types here, since _Atomic can't be 1247 // applied to such types. 1248 SplitQualType Split = T.getSplitUnqualifiedType(); 1249 T = BuildAtomicType(QualType(Split.Ty, 0), 1250 DS ? DS->getAtomicSpecLoc() : Loc); 1251 if (T.isNull()) 1252 return T; 1253 Split.Quals.addCVRQualifiers(CVR); 1254 return BuildQualifiedType(T, Loc, Split.Quals); 1255 } 1256 1257 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS); 1258 } 1259 1260 /// \brief Build a paren type including \p T. 1261 QualType Sema::BuildParenType(QualType T) { 1262 return Context.getParenType(T); 1263 } 1264 1265 /// Given that we're building a pointer or reference to the given 1266 static QualType inferARCLifetimeForPointee(Sema &S, QualType type, 1267 SourceLocation loc, 1268 bool isReference) { 1269 // Bail out if retention is unrequired or already specified. 1270 if (!type->isObjCLifetimeType() || 1271 type.getObjCLifetime() != Qualifiers::OCL_None) 1272 return type; 1273 1274 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; 1275 1276 // If the object type is const-qualified, we can safely use 1277 // __unsafe_unretained. This is safe (because there are no read 1278 // barriers), and it'll be safe to coerce anything but __weak* to 1279 // the resulting type. 1280 if (type.isConstQualified()) { 1281 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1282 1283 // Otherwise, check whether the static type does not require 1284 // retaining. This currently only triggers for Class (possibly 1285 // protocol-qualifed, and arrays thereof). 1286 } else if (type->isObjCARCImplicitlyUnretainedType()) { 1287 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1288 1289 // If we are in an unevaluated context, like sizeof, skip adding a 1290 // qualification. 1291 } else if (S.isUnevaluatedContext()) { 1292 return type; 1293 1294 // If that failed, give an error and recover using __strong. __strong 1295 // is the option most likely to prevent spurious second-order diagnostics, 1296 // like when binding a reference to a field. 1297 } else { 1298 // These types can show up in private ivars in system headers, so 1299 // we need this to not be an error in those cases. Instead we 1300 // want to delay. 1301 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 1302 S.DelayedDiagnostics.add( 1303 sema::DelayedDiagnostic::makeForbiddenType(loc, 1304 diag::err_arc_indirect_no_ownership, type, isReference)); 1305 } else { 1306 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; 1307 } 1308 implicitLifetime = Qualifiers::OCL_Strong; 1309 } 1310 assert(implicitLifetime && "didn't infer any lifetime!"); 1311 1312 Qualifiers qs; 1313 qs.addObjCLifetime(implicitLifetime); 1314 return S.Context.getQualifiedType(type, qs); 1315 } 1316 1317 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ 1318 std::string Quals = 1319 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString(); 1320 1321 switch (FnTy->getRefQualifier()) { 1322 case RQ_None: 1323 break; 1324 1325 case RQ_LValue: 1326 if (!Quals.empty()) 1327 Quals += ' '; 1328 Quals += '&'; 1329 break; 1330 1331 case RQ_RValue: 1332 if (!Quals.empty()) 1333 Quals += ' '; 1334 Quals += "&&"; 1335 break; 1336 } 1337 1338 return Quals; 1339 } 1340 1341 namespace { 1342 /// Kinds of declarator that cannot contain a qualified function type. 1343 /// 1344 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: 1345 /// a function type with a cv-qualifier or a ref-qualifier can only appear 1346 /// at the topmost level of a type. 1347 /// 1348 /// Parens and member pointers are permitted. We don't diagnose array and 1349 /// function declarators, because they don't allow function types at all. 1350 /// 1351 /// The values of this enum are used in diagnostics. 1352 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference }; 1353 } 1354 1355 /// Check whether the type T is a qualified function type, and if it is, 1356 /// diagnose that it cannot be contained within the given kind of declarator. 1357 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, 1358 QualifiedFunctionKind QFK) { 1359 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 1360 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); 1361 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None)) 1362 return false; 1363 1364 S.Diag(Loc, diag::err_compound_qualified_function_type) 1365 << QFK << isa<FunctionType>(T.IgnoreParens()) << T 1366 << getFunctionQualifiersAsString(FPT); 1367 return true; 1368 } 1369 1370 /// \brief Build a pointer type. 1371 /// 1372 /// \param T The type to which we'll be building a pointer. 1373 /// 1374 /// \param Loc The location of the entity whose type involves this 1375 /// pointer type or, if there is no such entity, the location of the 1376 /// type that will have pointer type. 1377 /// 1378 /// \param Entity The name of the entity that involves the pointer 1379 /// type, if known. 1380 /// 1381 /// \returns A suitable pointer type, if there are no 1382 /// errors. Otherwise, returns a NULL type. 1383 QualType Sema::BuildPointerType(QualType T, 1384 SourceLocation Loc, DeclarationName Entity) { 1385 if (T->isReferenceType()) { 1386 // C++ 8.3.2p4: There shall be no ... pointers to references ... 1387 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 1388 << getPrintableNameForEntity(Entity) << T; 1389 return QualType(); 1390 } 1391 1392 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer)) 1393 return QualType(); 1394 1395 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); 1396 1397 // In ARC, it is forbidden to build pointers to unqualified pointers. 1398 if (getLangOpts().ObjCAutoRefCount) 1399 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); 1400 1401 // Build the pointer type. 1402 return Context.getPointerType(T); 1403 } 1404 1405 /// \brief Build a reference type. 1406 /// 1407 /// \param T The type to which we'll be building a reference. 1408 /// 1409 /// \param Loc The location of the entity whose type involves this 1410 /// reference type or, if there is no such entity, the location of the 1411 /// type that will have reference type. 1412 /// 1413 /// \param Entity The name of the entity that involves the reference 1414 /// type, if known. 1415 /// 1416 /// \returns A suitable reference type, if there are no 1417 /// errors. Otherwise, returns a NULL type. 1418 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, 1419 SourceLocation Loc, 1420 DeclarationName Entity) { 1421 assert(Context.getCanonicalType(T) != Context.OverloadTy && 1422 "Unresolved overloaded function type"); 1423 1424 // C++0x [dcl.ref]p6: 1425 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a 1426 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a 1427 // type T, an attempt to create the type "lvalue reference to cv TR" creates 1428 // the type "lvalue reference to T", while an attempt to create the type 1429 // "rvalue reference to cv TR" creates the type TR. 1430 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); 1431 1432 // C++ [dcl.ref]p4: There shall be no references to references. 1433 // 1434 // According to C++ DR 106, references to references are only 1435 // diagnosed when they are written directly (e.g., "int & &"), 1436 // but not when they happen via a typedef: 1437 // 1438 // typedef int& intref; 1439 // typedef intref& intref2; 1440 // 1441 // Parser::ParseDeclaratorInternal diagnoses the case where 1442 // references are written directly; here, we handle the 1443 // collapsing of references-to-references as described in C++0x. 1444 // DR 106 and 540 introduce reference-collapsing into C++98/03. 1445 1446 // C++ [dcl.ref]p1: 1447 // A declarator that specifies the type "reference to cv void" 1448 // is ill-formed. 1449 if (T->isVoidType()) { 1450 Diag(Loc, diag::err_reference_to_void); 1451 return QualType(); 1452 } 1453 1454 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference)) 1455 return QualType(); 1456 1457 // In ARC, it is forbidden to build references to unqualified pointers. 1458 if (getLangOpts().ObjCAutoRefCount) 1459 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); 1460 1461 // Handle restrict on references. 1462 if (LValueRef) 1463 return Context.getLValueReferenceType(T, SpelledAsLValue); 1464 return Context.getRValueReferenceType(T); 1465 } 1466 1467 /// Check whether the specified array size makes the array type a VLA. If so, 1468 /// return true, if not, return the size of the array in SizeVal. 1469 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) { 1470 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode 1471 // (like gnu99, but not c99) accept any evaluatable value as an extension. 1472 class VLADiagnoser : public Sema::VerifyICEDiagnoser { 1473 public: 1474 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {} 1475 1476 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 1477 } 1478 1479 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override { 1480 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR; 1481 } 1482 } Diagnoser; 1483 1484 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser, 1485 S.LangOpts.GNUMode).isInvalid(); 1486 } 1487 1488 1489 /// \brief Build an array type. 1490 /// 1491 /// \param T The type of each element in the array. 1492 /// 1493 /// \param ASM C99 array size modifier (e.g., '*', 'static'). 1494 /// 1495 /// \param ArraySize Expression describing the size of the array. 1496 /// 1497 /// \param Brackets The range from the opening '[' to the closing ']'. 1498 /// 1499 /// \param Entity The name of the entity that involves the array 1500 /// type, if known. 1501 /// 1502 /// \returns A suitable array type, if there are no errors. Otherwise, 1503 /// returns a NULL type. 1504 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 1505 Expr *ArraySize, unsigned Quals, 1506 SourceRange Brackets, DeclarationName Entity) { 1507 1508 SourceLocation Loc = Brackets.getBegin(); 1509 if (getLangOpts().CPlusPlus) { 1510 // C++ [dcl.array]p1: 1511 // T is called the array element type; this type shall not be a reference 1512 // type, the (possibly cv-qualified) type void, a function type or an 1513 // abstract class type. 1514 // 1515 // C++ [dcl.array]p3: 1516 // When several "array of" specifications are adjacent, [...] only the 1517 // first of the constant expressions that specify the bounds of the arrays 1518 // may be omitted. 1519 // 1520 // Note: function types are handled in the common path with C. 1521 if (T->isReferenceType()) { 1522 Diag(Loc, diag::err_illegal_decl_array_of_references) 1523 << getPrintableNameForEntity(Entity) << T; 1524 return QualType(); 1525 } 1526 1527 if (T->isVoidType() || T->isIncompleteArrayType()) { 1528 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; 1529 return QualType(); 1530 } 1531 1532 if (RequireNonAbstractType(Brackets.getBegin(), T, 1533 diag::err_array_of_abstract_type)) 1534 return QualType(); 1535 1536 // Mentioning a member pointer type for an array type causes us to lock in 1537 // an inheritance model, even if it's inside an unused typedef. 1538 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 1539 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) 1540 if (!MPTy->getClass()->isDependentType()) 1541 RequireCompleteType(Loc, T, 0); 1542 1543 } else { 1544 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 1545 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 1546 if (RequireCompleteType(Loc, T, 1547 diag::err_illegal_decl_array_incomplete_type)) 1548 return QualType(); 1549 } 1550 1551 if (T->isFunctionType()) { 1552 Diag(Loc, diag::err_illegal_decl_array_of_functions) 1553 << getPrintableNameForEntity(Entity) << T; 1554 return QualType(); 1555 } 1556 1557 if (const RecordType *EltTy = T->getAs<RecordType>()) { 1558 // If the element type is a struct or union that contains a variadic 1559 // array, accept it as a GNU extension: C99 6.7.2.1p2. 1560 if (EltTy->getDecl()->hasFlexibleArrayMember()) 1561 Diag(Loc, diag::ext_flexible_array_in_array) << T; 1562 } else if (T->isObjCObjectType()) { 1563 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 1564 return QualType(); 1565 } 1566 1567 // Do placeholder conversions on the array size expression. 1568 if (ArraySize && ArraySize->hasPlaceholderType()) { 1569 ExprResult Result = CheckPlaceholderExpr(ArraySize); 1570 if (Result.isInvalid()) return QualType(); 1571 ArraySize = Result.get(); 1572 } 1573 1574 // Do lvalue-to-rvalue conversions on the array size expression. 1575 if (ArraySize && !ArraySize->isRValue()) { 1576 ExprResult Result = DefaultLvalueConversion(ArraySize); 1577 if (Result.isInvalid()) 1578 return QualType(); 1579 1580 ArraySize = Result.get(); 1581 } 1582 1583 // C99 6.7.5.2p1: The size expression shall have integer type. 1584 // C++11 allows contextual conversions to such types. 1585 if (!getLangOpts().CPlusPlus11 && 1586 ArraySize && !ArraySize->isTypeDependent() && 1587 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 1588 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 1589 << ArraySize->getType() << ArraySize->getSourceRange(); 1590 return QualType(); 1591 } 1592 1593 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); 1594 if (!ArraySize) { 1595 if (ASM == ArrayType::Star) 1596 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets); 1597 else 1598 T = Context.getIncompleteArrayType(T, ASM, Quals); 1599 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { 1600 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 1601 } else if ((!T->isDependentType() && !T->isIncompleteType() && 1602 !T->isConstantSizeType()) || 1603 isArraySizeVLA(*this, ArraySize, ConstVal)) { 1604 // Even in C++11, don't allow contextual conversions in the array bound 1605 // of a VLA. 1606 if (getLangOpts().CPlusPlus11 && 1607 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 1608 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 1609 << ArraySize->getType() << ArraySize->getSourceRange(); 1610 return QualType(); 1611 } 1612 1613 // C99: an array with an element type that has a non-constant-size is a VLA. 1614 // C99: an array with a non-ICE size is a VLA. We accept any expression 1615 // that we can fold to a non-zero positive value as an extension. 1616 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 1617 } else { 1618 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 1619 // have a value greater than zero. 1620 if (ConstVal.isSigned() && ConstVal.isNegative()) { 1621 if (Entity) 1622 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size) 1623 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); 1624 else 1625 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size) 1626 << ArraySize->getSourceRange(); 1627 return QualType(); 1628 } 1629 if (ConstVal == 0) { 1630 // GCC accepts zero sized static arrays. We allow them when 1631 // we're not in a SFINAE context. 1632 Diag(ArraySize->getLocStart(), 1633 isSFINAEContext()? diag::err_typecheck_zero_array_size 1634 : diag::ext_typecheck_zero_array_size) 1635 << ArraySize->getSourceRange(); 1636 1637 if (ASM == ArrayType::Static) { 1638 Diag(ArraySize->getLocStart(), 1639 diag::warn_typecheck_zero_static_array_size) 1640 << ArraySize->getSourceRange(); 1641 ASM = ArrayType::Normal; 1642 } 1643 } else if (!T->isDependentType() && !T->isVariablyModifiedType() && 1644 !T->isIncompleteType() && !T->isUndeducedType()) { 1645 // Is the array too large? 1646 unsigned ActiveSizeBits 1647 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); 1648 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 1649 Diag(ArraySize->getLocStart(), diag::err_array_too_large) 1650 << ConstVal.toString(10) 1651 << ArraySize->getSourceRange(); 1652 return QualType(); 1653 } 1654 } 1655 1656 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); 1657 } 1658 1659 // OpenCL v1.2 s6.9.d: variable length arrays are not supported. 1660 if (getLangOpts().OpenCL && T->isVariableArrayType()) { 1661 Diag(Loc, diag::err_opencl_vla); 1662 return QualType(); 1663 } 1664 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 1665 if (!getLangOpts().C99) { 1666 if (T->isVariableArrayType()) { 1667 // Prohibit the use of non-POD types in VLAs. 1668 QualType BaseT = Context.getBaseElementType(T); 1669 if (!T->isDependentType() && 1670 !RequireCompleteType(Loc, BaseT, 0) && 1671 !BaseT.isPODType(Context) && 1672 !BaseT->isObjCLifetimeType()) { 1673 Diag(Loc, diag::err_vla_non_pod) 1674 << BaseT; 1675 return QualType(); 1676 } 1677 // Prohibit the use of VLAs during template argument deduction. 1678 else if (isSFINAEContext()) { 1679 Diag(Loc, diag::err_vla_in_sfinae); 1680 return QualType(); 1681 } 1682 // Just extwarn about VLAs. 1683 else 1684 Diag(Loc, diag::ext_vla); 1685 } else if (ASM != ArrayType::Normal || Quals != 0) 1686 Diag(Loc, 1687 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx 1688 : diag::ext_c99_array_usage) << ASM; 1689 } 1690 1691 if (T->isVariableArrayType()) { 1692 // Warn about VLAs for -Wvla. 1693 Diag(Loc, diag::warn_vla_used); 1694 } 1695 1696 return T; 1697 } 1698 1699 /// \brief Build an ext-vector type. 1700 /// 1701 /// Run the required checks for the extended vector type. 1702 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, 1703 SourceLocation AttrLoc) { 1704 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 1705 // in conjunction with complex types (pointers, arrays, functions, etc.). 1706 if (!T->isDependentType() && 1707 !T->isIntegerType() && !T->isRealFloatingType()) { 1708 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 1709 return QualType(); 1710 } 1711 1712 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { 1713 llvm::APSInt vecSize(32); 1714 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { 1715 Diag(AttrLoc, diag::err_attribute_argument_type) 1716 << "ext_vector_type" << AANT_ArgumentIntegerConstant 1717 << ArraySize->getSourceRange(); 1718 return QualType(); 1719 } 1720 1721 // unlike gcc's vector_size attribute, the size is specified as the 1722 // number of elements, not the number of bytes. 1723 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 1724 1725 if (vectorSize == 0) { 1726 Diag(AttrLoc, diag::err_attribute_zero_size) 1727 << ArraySize->getSourceRange(); 1728 return QualType(); 1729 } 1730 1731 if (VectorType::isVectorSizeTooLarge(vectorSize)) { 1732 Diag(AttrLoc, diag::err_attribute_size_too_large) 1733 << ArraySize->getSourceRange(); 1734 return QualType(); 1735 } 1736 1737 return Context.getExtVectorType(T, vectorSize); 1738 } 1739 1740 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); 1741 } 1742 1743 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { 1744 if (T->isArrayType() || T->isFunctionType()) { 1745 Diag(Loc, diag::err_func_returning_array_function) 1746 << T->isFunctionType() << T; 1747 return true; 1748 } 1749 1750 // Functions cannot return half FP. 1751 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) { 1752 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << 1753 FixItHint::CreateInsertion(Loc, "*"); 1754 return true; 1755 } 1756 1757 // Methods cannot return interface types. All ObjC objects are 1758 // passed by reference. 1759 if (T->isObjCObjectType()) { 1760 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T; 1761 return 0; 1762 } 1763 1764 return false; 1765 } 1766 1767 QualType Sema::BuildFunctionType(QualType T, 1768 MutableArrayRef<QualType> ParamTypes, 1769 SourceLocation Loc, DeclarationName Entity, 1770 const FunctionProtoType::ExtProtoInfo &EPI) { 1771 bool Invalid = false; 1772 1773 Invalid |= CheckFunctionReturnType(T, Loc); 1774 1775 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { 1776 // FIXME: Loc is too inprecise here, should use proper locations for args. 1777 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); 1778 if (ParamType->isVoidType()) { 1779 Diag(Loc, diag::err_param_with_void_type); 1780 Invalid = true; 1781 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) { 1782 // Disallow half FP arguments. 1783 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << 1784 FixItHint::CreateInsertion(Loc, "*"); 1785 Invalid = true; 1786 } 1787 1788 ParamTypes[Idx] = ParamType; 1789 } 1790 1791 if (Invalid) 1792 return QualType(); 1793 1794 return Context.getFunctionType(T, ParamTypes, EPI); 1795 } 1796 1797 /// \brief Build a member pointer type \c T Class::*. 1798 /// 1799 /// \param T the type to which the member pointer refers. 1800 /// \param Class the class type into which the member pointer points. 1801 /// \param Loc the location where this type begins 1802 /// \param Entity the name of the entity that will have this member pointer type 1803 /// 1804 /// \returns a member pointer type, if successful, or a NULL type if there was 1805 /// an error. 1806 QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 1807 SourceLocation Loc, 1808 DeclarationName Entity) { 1809 // Verify that we're not building a pointer to pointer to function with 1810 // exception specification. 1811 if (CheckDistantExceptionSpec(T)) { 1812 Diag(Loc, diag::err_distant_exception_spec); 1813 1814 // FIXME: If we're doing this as part of template instantiation, 1815 // we should return immediately. 1816 1817 // Build the type anyway, but use the canonical type so that the 1818 // exception specifiers are stripped off. 1819 T = Context.getCanonicalType(T); 1820 } 1821 1822 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 1823 // with reference type, or "cv void." 1824 if (T->isReferenceType()) { 1825 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 1826 << getPrintableNameForEntity(Entity) << T; 1827 return QualType(); 1828 } 1829 1830 if (T->isVoidType()) { 1831 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 1832 << getPrintableNameForEntity(Entity); 1833 return QualType(); 1834 } 1835 1836 if (!Class->isDependentType() && !Class->isRecordType()) { 1837 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 1838 return QualType(); 1839 } 1840 1841 // Adjust the default free function calling convention to the default method 1842 // calling convention. 1843 if (T->isFunctionType()) 1844 adjustMemberFunctionCC(T, /*IsStatic=*/false); 1845 1846 return Context.getMemberPointerType(T, Class.getTypePtr()); 1847 } 1848 1849 /// \brief Build a block pointer type. 1850 /// 1851 /// \param T The type to which we'll be building a block pointer. 1852 /// 1853 /// \param Loc The source location, used for diagnostics. 1854 /// 1855 /// \param Entity The name of the entity that involves the block pointer 1856 /// type, if known. 1857 /// 1858 /// \returns A suitable block pointer type, if there are no 1859 /// errors. Otherwise, returns a NULL type. 1860 QualType Sema::BuildBlockPointerType(QualType T, 1861 SourceLocation Loc, 1862 DeclarationName Entity) { 1863 if (!T->isFunctionType()) { 1864 Diag(Loc, diag::err_nonfunction_block_type); 1865 return QualType(); 1866 } 1867 1868 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) 1869 return QualType(); 1870 1871 return Context.getBlockPointerType(T); 1872 } 1873 1874 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 1875 QualType QT = Ty.get(); 1876 if (QT.isNull()) { 1877 if (TInfo) *TInfo = nullptr; 1878 return QualType(); 1879 } 1880 1881 TypeSourceInfo *DI = nullptr; 1882 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 1883 QT = LIT->getType(); 1884 DI = LIT->getTypeSourceInfo(); 1885 } 1886 1887 if (TInfo) *TInfo = DI; 1888 return QT; 1889 } 1890 1891 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 1892 Qualifiers::ObjCLifetime ownership, 1893 unsigned chunkIndex); 1894 1895 /// Given that this is the declaration of a parameter under ARC, 1896 /// attempt to infer attributes and such for pointer-to-whatever 1897 /// types. 1898 static void inferARCWriteback(TypeProcessingState &state, 1899 QualType &declSpecType) { 1900 Sema &S = state.getSema(); 1901 Declarator &declarator = state.getDeclarator(); 1902 1903 // TODO: should we care about decl qualifiers? 1904 1905 // Check whether the declarator has the expected form. We walk 1906 // from the inside out in order to make the block logic work. 1907 unsigned outermostPointerIndex = 0; 1908 bool isBlockPointer = false; 1909 unsigned numPointers = 0; 1910 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 1911 unsigned chunkIndex = i; 1912 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); 1913 switch (chunk.Kind) { 1914 case DeclaratorChunk::Paren: 1915 // Ignore parens. 1916 break; 1917 1918 case DeclaratorChunk::Reference: 1919 case DeclaratorChunk::Pointer: 1920 // Count the number of pointers. Treat references 1921 // interchangeably as pointers; if they're mis-ordered, normal 1922 // type building will discover that. 1923 outermostPointerIndex = chunkIndex; 1924 numPointers++; 1925 break; 1926 1927 case DeclaratorChunk::BlockPointer: 1928 // If we have a pointer to block pointer, that's an acceptable 1929 // indirect reference; anything else is not an application of 1930 // the rules. 1931 if (numPointers != 1) return; 1932 numPointers++; 1933 outermostPointerIndex = chunkIndex; 1934 isBlockPointer = true; 1935 1936 // We don't care about pointer structure in return values here. 1937 goto done; 1938 1939 case DeclaratorChunk::Array: // suppress if written (id[])? 1940 case DeclaratorChunk::Function: 1941 case DeclaratorChunk::MemberPointer: 1942 return; 1943 } 1944 } 1945 done: 1946 1947 // If we have *one* pointer, then we want to throw the qualifier on 1948 // the declaration-specifiers, which means that it needs to be a 1949 // retainable object type. 1950 if (numPointers == 1) { 1951 // If it's not a retainable object type, the rule doesn't apply. 1952 if (!declSpecType->isObjCRetainableType()) return; 1953 1954 // If it already has lifetime, don't do anything. 1955 if (declSpecType.getObjCLifetime()) return; 1956 1957 // Otherwise, modify the type in-place. 1958 Qualifiers qs; 1959 1960 if (declSpecType->isObjCARCImplicitlyUnretainedType()) 1961 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); 1962 else 1963 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); 1964 declSpecType = S.Context.getQualifiedType(declSpecType, qs); 1965 1966 // If we have *two* pointers, then we want to throw the qualifier on 1967 // the outermost pointer. 1968 } else if (numPointers == 2) { 1969 // If we don't have a block pointer, we need to check whether the 1970 // declaration-specifiers gave us something that will turn into a 1971 // retainable object pointer after we slap the first pointer on it. 1972 if (!isBlockPointer && !declSpecType->isObjCObjectType()) 1973 return; 1974 1975 // Look for an explicit lifetime attribute there. 1976 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); 1977 if (chunk.Kind != DeclaratorChunk::Pointer && 1978 chunk.Kind != DeclaratorChunk::BlockPointer) 1979 return; 1980 for (const AttributeList *attr = chunk.getAttrs(); attr; 1981 attr = attr->getNext()) 1982 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 1983 return; 1984 1985 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, 1986 outermostPointerIndex); 1987 1988 // Any other number of pointers/references does not trigger the rule. 1989 } else return; 1990 1991 // TODO: mark whether we did this inference? 1992 } 1993 1994 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 1995 SourceLocation FallbackLoc, 1996 SourceLocation ConstQualLoc, 1997 SourceLocation VolatileQualLoc, 1998 SourceLocation RestrictQualLoc, 1999 SourceLocation AtomicQualLoc) { 2000 if (!Quals) 2001 return; 2002 2003 struct Qual { 2004 unsigned Mask; 2005 const char *Name; 2006 SourceLocation Loc; 2007 } const QualKinds[4] = { 2008 { DeclSpec::TQ_const, "const", ConstQualLoc }, 2009 { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc }, 2010 { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc }, 2011 { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc } 2012 }; 2013 2014 SmallString<32> QualStr; 2015 unsigned NumQuals = 0; 2016 SourceLocation Loc; 2017 FixItHint FixIts[4]; 2018 2019 // Build a string naming the redundant qualifiers. 2020 for (unsigned I = 0; I != 4; ++I) { 2021 if (Quals & QualKinds[I].Mask) { 2022 if (!QualStr.empty()) QualStr += ' '; 2023 QualStr += QualKinds[I].Name; 2024 2025 // If we have a location for the qualifier, offer a fixit. 2026 SourceLocation QualLoc = QualKinds[I].Loc; 2027 if (!QualLoc.isInvalid()) { 2028 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); 2029 if (Loc.isInvalid() || 2030 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) 2031 Loc = QualLoc; 2032 } 2033 2034 ++NumQuals; 2035 } 2036 } 2037 2038 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) 2039 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; 2040 } 2041 2042 // Diagnose pointless type qualifiers on the return type of a function. 2043 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, 2044 Declarator &D, 2045 unsigned FunctionChunkIndex) { 2046 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) { 2047 // FIXME: TypeSourceInfo doesn't preserve location information for 2048 // qualifiers. 2049 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2050 RetTy.getLocalCVRQualifiers(), 2051 D.getIdentifierLoc()); 2052 return; 2053 } 2054 2055 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, 2056 End = D.getNumTypeObjects(); 2057 OuterChunkIndex != End; ++OuterChunkIndex) { 2058 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); 2059 switch (OuterChunk.Kind) { 2060 case DeclaratorChunk::Paren: 2061 continue; 2062 2063 case DeclaratorChunk::Pointer: { 2064 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; 2065 S.diagnoseIgnoredQualifiers( 2066 diag::warn_qual_return_type, 2067 PTI.TypeQuals, 2068 SourceLocation(), 2069 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), 2070 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), 2071 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), 2072 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc)); 2073 return; 2074 } 2075 2076 case DeclaratorChunk::Function: 2077 case DeclaratorChunk::BlockPointer: 2078 case DeclaratorChunk::Reference: 2079 case DeclaratorChunk::Array: 2080 case DeclaratorChunk::MemberPointer: 2081 // FIXME: We can't currently provide an accurate source location and a 2082 // fix-it hint for these. 2083 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; 2084 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2085 RetTy.getCVRQualifiers() | AtomicQual, 2086 D.getIdentifierLoc()); 2087 return; 2088 } 2089 2090 llvm_unreachable("unknown declarator chunk kind"); 2091 } 2092 2093 // If the qualifiers come from a conversion function type, don't diagnose 2094 // them -- they're not necessarily redundant, since such a conversion 2095 // operator can be explicitly called as "x.operator const int()". 2096 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 2097 return; 2098 2099 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers 2100 // which are present there. 2101 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2102 D.getDeclSpec().getTypeQualifiers(), 2103 D.getIdentifierLoc(), 2104 D.getDeclSpec().getConstSpecLoc(), 2105 D.getDeclSpec().getVolatileSpecLoc(), 2106 D.getDeclSpec().getRestrictSpecLoc(), 2107 D.getDeclSpec().getAtomicSpecLoc()); 2108 } 2109 2110 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, 2111 TypeSourceInfo *&ReturnTypeInfo) { 2112 Sema &SemaRef = state.getSema(); 2113 Declarator &D = state.getDeclarator(); 2114 QualType T; 2115 ReturnTypeInfo = nullptr; 2116 2117 // The TagDecl owned by the DeclSpec. 2118 TagDecl *OwnedTagDecl = nullptr; 2119 2120 bool ContainsPlaceholderType = false; 2121 2122 switch (D.getName().getKind()) { 2123 case UnqualifiedId::IK_ImplicitSelfParam: 2124 case UnqualifiedId::IK_OperatorFunctionId: 2125 case UnqualifiedId::IK_Identifier: 2126 case UnqualifiedId::IK_LiteralOperatorId: 2127 case UnqualifiedId::IK_TemplateId: 2128 T = ConvertDeclSpecToType(state); 2129 ContainsPlaceholderType = D.getDeclSpec().containsPlaceholderType(); 2130 2131 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 2132 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2133 // Owned declaration is embedded in declarator. 2134 OwnedTagDecl->setEmbeddedInDeclarator(true); 2135 } 2136 break; 2137 2138 case UnqualifiedId::IK_ConstructorName: 2139 case UnqualifiedId::IK_ConstructorTemplateId: 2140 case UnqualifiedId::IK_DestructorName: 2141 // Constructors and destructors don't have return types. Use 2142 // "void" instead. 2143 T = SemaRef.Context.VoidTy; 2144 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList()) 2145 processTypeAttrs(state, T, TAL_DeclSpec, attrs); 2146 break; 2147 2148 case UnqualifiedId::IK_ConversionFunctionId: 2149 // The result type of a conversion function is the type that it 2150 // converts to. 2151 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, 2152 &ReturnTypeInfo); 2153 ContainsPlaceholderType = T->getContainedAutoType(); 2154 break; 2155 } 2156 2157 if (D.getAttributes()) 2158 distributeTypeAttrsFromDeclarator(state, T); 2159 2160 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 2161 // In C++11, a function declarator using 'auto' must have a trailing return 2162 // type (this is checked later) and we can skip this. In other languages 2163 // using auto, we need to check regardless. 2164 // C++14 In generic lambdas allow 'auto' in their parameters. 2165 if (ContainsPlaceholderType && 2166 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) { 2167 int Error = -1; 2168 2169 switch (D.getContext()) { 2170 case Declarator::KNRTypeListContext: 2171 llvm_unreachable("K&R type lists aren't allowed in C++"); 2172 case Declarator::LambdaExprContext: 2173 llvm_unreachable("Can't specify a type specifier in lambda grammar"); 2174 case Declarator::ObjCParameterContext: 2175 case Declarator::ObjCResultContext: 2176 case Declarator::PrototypeContext: 2177 Error = 0; 2178 break; 2179 case Declarator::LambdaExprParameterContext: 2180 if (!(SemaRef.getLangOpts().CPlusPlus14 2181 && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto)) 2182 Error = 14; 2183 break; 2184 case Declarator::MemberContext: 2185 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) 2186 break; 2187 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { 2188 case TTK_Enum: llvm_unreachable("unhandled tag kind"); 2189 case TTK_Struct: Error = 1; /* Struct member */ break; 2190 case TTK_Union: Error = 2; /* Union member */ break; 2191 case TTK_Class: Error = 3; /* Class member */ break; 2192 case TTK_Interface: Error = 4; /* Interface member */ break; 2193 } 2194 break; 2195 case Declarator::CXXCatchContext: 2196 case Declarator::ObjCCatchContext: 2197 Error = 5; // Exception declaration 2198 break; 2199 case Declarator::TemplateParamContext: 2200 Error = 6; // Template parameter 2201 break; 2202 case Declarator::BlockLiteralContext: 2203 Error = 7; // Block literal 2204 break; 2205 case Declarator::TemplateTypeArgContext: 2206 Error = 8; // Template type argument 2207 break; 2208 case Declarator::AliasDeclContext: 2209 case Declarator::AliasTemplateContext: 2210 Error = 10; // Type alias 2211 break; 2212 case Declarator::TrailingReturnContext: 2213 if (!SemaRef.getLangOpts().CPlusPlus14) 2214 Error = 11; // Function return type 2215 break; 2216 case Declarator::ConversionIdContext: 2217 if (!SemaRef.getLangOpts().CPlusPlus14) 2218 Error = 12; // conversion-type-id 2219 break; 2220 case Declarator::TypeNameContext: 2221 Error = 13; // Generic 2222 break; 2223 case Declarator::FileContext: 2224 case Declarator::BlockContext: 2225 case Declarator::ForContext: 2226 case Declarator::ConditionContext: 2227 case Declarator::CXXNewContext: 2228 break; 2229 } 2230 2231 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 2232 Error = 9; 2233 2234 // In Objective-C it is an error to use 'auto' on a function declarator. 2235 if (D.isFunctionDeclarator()) 2236 Error = 11; 2237 2238 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator 2239 // contains a trailing return type. That is only legal at the outermost 2240 // level. Check all declarator chunks (outermost first) anyway, to give 2241 // better diagnostics. 2242 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) { 2243 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2244 unsigned chunkIndex = e - i - 1; 2245 state.setCurrentChunkIndex(chunkIndex); 2246 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 2247 if (DeclType.Kind == DeclaratorChunk::Function) { 2248 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2249 if (FTI.hasTrailingReturnType()) { 2250 Error = -1; 2251 break; 2252 } 2253 } 2254 } 2255 } 2256 2257 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); 2258 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 2259 AutoRange = D.getName().getSourceRange(); 2260 2261 if (Error != -1) { 2262 const bool IsDeclTypeAuto = 2263 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_decltype_auto; 2264 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) 2265 << IsDeclTypeAuto << Error << AutoRange; 2266 T = SemaRef.Context.IntTy; 2267 D.setInvalidType(true); 2268 } else 2269 SemaRef.Diag(AutoRange.getBegin(), 2270 diag::warn_cxx98_compat_auto_type_specifier) 2271 << AutoRange; 2272 } 2273 2274 if (SemaRef.getLangOpts().CPlusPlus && 2275 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 2276 // Check the contexts where C++ forbids the declaration of a new class 2277 // or enumeration in a type-specifier-seq. 2278 switch (D.getContext()) { 2279 case Declarator::TrailingReturnContext: 2280 // Class and enumeration definitions are syntactically not allowed in 2281 // trailing return types. 2282 llvm_unreachable("parser should not have allowed this"); 2283 break; 2284 case Declarator::FileContext: 2285 case Declarator::MemberContext: 2286 case Declarator::BlockContext: 2287 case Declarator::ForContext: 2288 case Declarator::BlockLiteralContext: 2289 case Declarator::LambdaExprContext: 2290 // C++11 [dcl.type]p3: 2291 // A type-specifier-seq shall not define a class or enumeration unless 2292 // it appears in the type-id of an alias-declaration (7.1.3) that is not 2293 // the declaration of a template-declaration. 2294 case Declarator::AliasDeclContext: 2295 break; 2296 case Declarator::AliasTemplateContext: 2297 SemaRef.Diag(OwnedTagDecl->getLocation(), 2298 diag::err_type_defined_in_alias_template) 2299 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2300 D.setInvalidType(true); 2301 break; 2302 case Declarator::TypeNameContext: 2303 case Declarator::ConversionIdContext: 2304 case Declarator::TemplateParamContext: 2305 case Declarator::CXXNewContext: 2306 case Declarator::CXXCatchContext: 2307 case Declarator::ObjCCatchContext: 2308 case Declarator::TemplateTypeArgContext: 2309 SemaRef.Diag(OwnedTagDecl->getLocation(), 2310 diag::err_type_defined_in_type_specifier) 2311 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2312 D.setInvalidType(true); 2313 break; 2314 case Declarator::PrototypeContext: 2315 case Declarator::LambdaExprParameterContext: 2316 case Declarator::ObjCParameterContext: 2317 case Declarator::ObjCResultContext: 2318 case Declarator::KNRTypeListContext: 2319 // C++ [dcl.fct]p6: 2320 // Types shall not be defined in return or parameter types. 2321 SemaRef.Diag(OwnedTagDecl->getLocation(), 2322 diag::err_type_defined_in_param_type) 2323 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2324 D.setInvalidType(true); 2325 break; 2326 case Declarator::ConditionContext: 2327 // C++ 6.4p2: 2328 // The type-specifier-seq shall not contain typedef and shall not declare 2329 // a new class or enumeration. 2330 SemaRef.Diag(OwnedTagDecl->getLocation(), 2331 diag::err_type_defined_in_condition); 2332 D.setInvalidType(true); 2333 break; 2334 } 2335 } 2336 2337 return T; 2338 } 2339 2340 /// Produce an appropriate diagnostic for an ambiguity between a function 2341 /// declarator and a C++ direct-initializer. 2342 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, 2343 DeclaratorChunk &DeclType, QualType RT) { 2344 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2345 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity"); 2346 2347 // If the return type is void there is no ambiguity. 2348 if (RT->isVoidType()) 2349 return; 2350 2351 // An initializer for a non-class type can have at most one argument. 2352 if (!RT->isRecordType() && FTI.NumParams > 1) 2353 return; 2354 2355 // An initializer for a reference must have exactly one argument. 2356 if (RT->isReferenceType() && FTI.NumParams != 1) 2357 return; 2358 2359 // Only warn if this declarator is declaring a function at block scope, and 2360 // doesn't have a storage class (such as 'extern') specified. 2361 if (!D.isFunctionDeclarator() || 2362 D.getFunctionDefinitionKind() != FDK_Declaration || 2363 !S.CurContext->isFunctionOrMethod() || 2364 D.getDeclSpec().getStorageClassSpec() 2365 != DeclSpec::SCS_unspecified) 2366 return; 2367 2368 // Inside a condition, a direct initializer is not permitted. We allow one to 2369 // be parsed in order to give better diagnostics in condition parsing. 2370 if (D.getContext() == Declarator::ConditionContext) 2371 return; 2372 2373 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); 2374 2375 S.Diag(DeclType.Loc, 2376 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration 2377 : diag::warn_empty_parens_are_function_decl) 2378 << ParenRange; 2379 2380 // If the declaration looks like: 2381 // T var1, 2382 // f(); 2383 // and name lookup finds a function named 'f', then the ',' was 2384 // probably intended to be a ';'. 2385 if (!D.isFirstDeclarator() && D.getIdentifier()) { 2386 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); 2387 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); 2388 if (Comma.getFileID() != Name.getFileID() || 2389 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { 2390 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 2391 Sema::LookupOrdinaryName); 2392 if (S.LookupName(Result, S.getCurScope())) 2393 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) 2394 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") 2395 << D.getIdentifier(); 2396 } 2397 } 2398 2399 if (FTI.NumParams > 0) { 2400 // For a declaration with parameters, eg. "T var(T());", suggest adding 2401 // parens around the first parameter to turn the declaration into a 2402 // variable declaration. 2403 SourceRange Range = FTI.Params[0].Param->getSourceRange(); 2404 SourceLocation B = Range.getBegin(); 2405 SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); 2406 // FIXME: Maybe we should suggest adding braces instead of parens 2407 // in C++11 for classes that don't have an initializer_list constructor. 2408 S.Diag(B, diag::note_additional_parens_for_variable_declaration) 2409 << FixItHint::CreateInsertion(B, "(") 2410 << FixItHint::CreateInsertion(E, ")"); 2411 } else { 2412 // For a declaration without parameters, eg. "T var();", suggest replacing 2413 // the parens with an initializer to turn the declaration into a variable 2414 // declaration. 2415 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 2416 2417 // Empty parens mean value-initialization, and no parens mean 2418 // default initialization. These are equivalent if the default 2419 // constructor is user-provided or if zero-initialization is a 2420 // no-op. 2421 if (RD && RD->hasDefinition() && 2422 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) 2423 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) 2424 << FixItHint::CreateRemoval(ParenRange); 2425 else { 2426 std::string Init = 2427 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); 2428 if (Init.empty() && S.LangOpts.CPlusPlus11) 2429 Init = "{}"; 2430 if (!Init.empty()) 2431 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) 2432 << FixItHint::CreateReplacement(ParenRange, Init); 2433 } 2434 } 2435 } 2436 2437 /// Helper for figuring out the default CC for a function declarator type. If 2438 /// this is the outermost chunk, then we can determine the CC from the 2439 /// declarator context. If not, then this could be either a member function 2440 /// type or normal function type. 2441 static CallingConv 2442 getCCForDeclaratorChunk(Sema &S, Declarator &D, 2443 const DeclaratorChunk::FunctionTypeInfo &FTI, 2444 unsigned ChunkIndex) { 2445 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function); 2446 2447 bool IsCXXInstanceMethod = false; 2448 2449 if (S.getLangOpts().CPlusPlus) { 2450 // Look inwards through parentheses to see if this chunk will form a 2451 // member pointer type or if we're the declarator. Any type attributes 2452 // between here and there will override the CC we choose here. 2453 unsigned I = ChunkIndex; 2454 bool FoundNonParen = false; 2455 while (I && !FoundNonParen) { 2456 --I; 2457 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) 2458 FoundNonParen = true; 2459 } 2460 2461 if (FoundNonParen) { 2462 // If we're not the declarator, we're a regular function type unless we're 2463 // in a member pointer. 2464 IsCXXInstanceMethod = 2465 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; 2466 } else { 2467 // We're the innermost decl chunk, so must be a function declarator. 2468 assert(D.isFunctionDeclarator()); 2469 2470 // If we're inside a record, we're declaring a method, but it could be 2471 // explicitly or implicitly static. 2472 IsCXXInstanceMethod = 2473 D.isFirstDeclarationOfMember() && 2474 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 2475 !D.isStaticMember(); 2476 } 2477 } 2478 2479 return S.Context.getDefaultCallingConvention(FTI.isVariadic, 2480 IsCXXInstanceMethod); 2481 } 2482 2483 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 2484 QualType declSpecType, 2485 TypeSourceInfo *TInfo) { 2486 2487 QualType T = declSpecType; 2488 Declarator &D = state.getDeclarator(); 2489 Sema &S = state.getSema(); 2490 ASTContext &Context = S.Context; 2491 const LangOptions &LangOpts = S.getLangOpts(); 2492 2493 // The name we're declaring, if any. 2494 DeclarationName Name; 2495 if (D.getIdentifier()) 2496 Name = D.getIdentifier(); 2497 2498 // Does this declaration declare a typedef-name? 2499 bool IsTypedefName = 2500 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 2501 D.getContext() == Declarator::AliasDeclContext || 2502 D.getContext() == Declarator::AliasTemplateContext; 2503 2504 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 2505 bool IsQualifiedFunction = T->isFunctionProtoType() && 2506 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 || 2507 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 2508 2509 // If T is 'decltype(auto)', the only declarators we can have are parens 2510 // and at most one function declarator if this is a function declaration. 2511 if (const AutoType *AT = T->getAs<AutoType>()) { 2512 if (AT->isDecltypeAuto()) { 2513 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 2514 unsigned Index = E - I - 1; 2515 DeclaratorChunk &DeclChunk = D.getTypeObject(Index); 2516 unsigned DiagId = diag::err_decltype_auto_compound_type; 2517 unsigned DiagKind = 0; 2518 switch (DeclChunk.Kind) { 2519 case DeclaratorChunk::Paren: 2520 continue; 2521 case DeclaratorChunk::Function: { 2522 unsigned FnIndex; 2523 if (D.isFunctionDeclarationContext() && 2524 D.isFunctionDeclarator(FnIndex) && FnIndex == Index) 2525 continue; 2526 DiagId = diag::err_decltype_auto_function_declarator_not_declaration; 2527 break; 2528 } 2529 case DeclaratorChunk::Pointer: 2530 case DeclaratorChunk::BlockPointer: 2531 case DeclaratorChunk::MemberPointer: 2532 DiagKind = 0; 2533 break; 2534 case DeclaratorChunk::Reference: 2535 DiagKind = 1; 2536 break; 2537 case DeclaratorChunk::Array: 2538 DiagKind = 2; 2539 break; 2540 } 2541 2542 S.Diag(DeclChunk.Loc, DiagId) << DiagKind; 2543 D.setInvalidType(true); 2544 break; 2545 } 2546 } 2547 } 2548 2549 // Walk the DeclTypeInfo, building the recursive type as we go. 2550 // DeclTypeInfos are ordered from the identifier out, which is 2551 // opposite of what we want :). 2552 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2553 unsigned chunkIndex = e - i - 1; 2554 state.setCurrentChunkIndex(chunkIndex); 2555 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 2556 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; 2557 switch (DeclType.Kind) { 2558 case DeclaratorChunk::Paren: 2559 T = S.BuildParenType(T); 2560 break; 2561 case DeclaratorChunk::BlockPointer: 2562 // If blocks are disabled, emit an error. 2563 if (!LangOpts.Blocks) 2564 S.Diag(DeclType.Loc, diag::err_blocks_disable); 2565 2566 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 2567 if (DeclType.Cls.TypeQuals) 2568 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 2569 break; 2570 case DeclaratorChunk::Pointer: 2571 // Verify that we're not building a pointer to pointer to function with 2572 // exception specification. 2573 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2574 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2575 D.setInvalidType(true); 2576 // Build the type anyway. 2577 } 2578 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) { 2579 T = Context.getObjCObjectPointerType(T); 2580 if (DeclType.Ptr.TypeQuals) 2581 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 2582 break; 2583 } 2584 T = S.BuildPointerType(T, DeclType.Loc, Name); 2585 if (DeclType.Ptr.TypeQuals) 2586 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 2587 2588 break; 2589 case DeclaratorChunk::Reference: { 2590 // Verify that we're not building a reference to pointer to function with 2591 // exception specification. 2592 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2593 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2594 D.setInvalidType(true); 2595 // Build the type anyway. 2596 } 2597 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 2598 2599 if (DeclType.Ref.HasRestrict) 2600 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 2601 break; 2602 } 2603 case DeclaratorChunk::Array: { 2604 // Verify that we're not building an array of pointers to function with 2605 // exception specification. 2606 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2607 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2608 D.setInvalidType(true); 2609 // Build the type anyway. 2610 } 2611 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 2612 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 2613 ArrayType::ArraySizeModifier ASM; 2614 if (ATI.isStar) 2615 ASM = ArrayType::Star; 2616 else if (ATI.hasStatic) 2617 ASM = ArrayType::Static; 2618 else 2619 ASM = ArrayType::Normal; 2620 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 2621 // FIXME: This check isn't quite right: it allows star in prototypes 2622 // for function definitions, and disallows some edge cases detailed 2623 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 2624 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 2625 ASM = ArrayType::Normal; 2626 D.setInvalidType(true); 2627 } 2628 2629 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static 2630 // shall appear only in a declaration of a function parameter with an 2631 // array type, ... 2632 if (ASM == ArrayType::Static || ATI.TypeQuals) { 2633 if (!(D.isPrototypeContext() || 2634 D.getContext() == Declarator::KNRTypeListContext)) { 2635 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << 2636 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 2637 // Remove the 'static' and the type qualifiers. 2638 if (ASM == ArrayType::Static) 2639 ASM = ArrayType::Normal; 2640 ATI.TypeQuals = 0; 2641 D.setInvalidType(true); 2642 } 2643 2644 // C99 6.7.5.2p1: ... and then only in the outermost array type 2645 // derivation. 2646 unsigned x = chunkIndex; 2647 while (x != 0) { 2648 // Walk outwards along the declarator chunks. 2649 x--; 2650 const DeclaratorChunk &DC = D.getTypeObject(x); 2651 switch (DC.Kind) { 2652 case DeclaratorChunk::Paren: 2653 continue; 2654 case DeclaratorChunk::Array: 2655 case DeclaratorChunk::Pointer: 2656 case DeclaratorChunk::Reference: 2657 case DeclaratorChunk::MemberPointer: 2658 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << 2659 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 2660 if (ASM == ArrayType::Static) 2661 ASM = ArrayType::Normal; 2662 ATI.TypeQuals = 0; 2663 D.setInvalidType(true); 2664 break; 2665 case DeclaratorChunk::Function: 2666 case DeclaratorChunk::BlockPointer: 2667 // These are invalid anyway, so just ignore. 2668 break; 2669 } 2670 } 2671 } 2672 const AutoType *AT = T->getContainedAutoType(); 2673 // Allow arrays of auto if we are a generic lambda parameter. 2674 // i.e. [](auto (&array)[5]) { return array[0]; }; OK 2675 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) { 2676 // We've already diagnosed this for decltype(auto). 2677 if (!AT->isDecltypeAuto()) 2678 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) 2679 << getPrintableNameForEntity(Name) << T; 2680 T = QualType(); 2681 break; 2682 } 2683 2684 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 2685 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 2686 break; 2687 } 2688 case DeclaratorChunk::Function: { 2689 // If the function declarator has a prototype (i.e. it is not () and 2690 // does not have a K&R-style identifier list), then the arguments are part 2691 // of the type, otherwise the argument list is (). 2692 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2693 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier(); 2694 2695 // Check for auto functions and trailing return type and adjust the 2696 // return type accordingly. 2697 if (!D.isInvalidType()) { 2698 // trailing-return-type is only required if we're declaring a function, 2699 // and not, for instance, a pointer to a function. 2700 if (D.getDeclSpec().containsPlaceholderType() && 2701 !FTI.hasTrailingReturnType() && chunkIndex == 0 && 2702 !S.getLangOpts().CPlusPlus14) { 2703 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2704 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto 2705 ? diag::err_auto_missing_trailing_return 2706 : diag::err_deduced_return_type); 2707 T = Context.IntTy; 2708 D.setInvalidType(true); 2709 } else if (FTI.hasTrailingReturnType()) { 2710 // T must be exactly 'auto' at this point. See CWG issue 681. 2711 if (isa<ParenType>(T)) { 2712 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2713 diag::err_trailing_return_in_parens) 2714 << T << D.getDeclSpec().getSourceRange(); 2715 D.setInvalidType(true); 2716 } else if (D.getContext() != Declarator::LambdaExprContext && 2717 (T.hasQualifiers() || !isa<AutoType>(T) || 2718 cast<AutoType>(T)->isDecltypeAuto())) { 2719 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2720 diag::err_trailing_return_without_auto) 2721 << T << D.getDeclSpec().getSourceRange(); 2722 D.setInvalidType(true); 2723 } 2724 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); 2725 if (T.isNull()) { 2726 // An error occurred parsing the trailing return type. 2727 T = Context.IntTy; 2728 D.setInvalidType(true); 2729 } 2730 } 2731 } 2732 2733 // C99 6.7.5.3p1: The return type may not be a function or array type. 2734 // For conversion functions, we'll diagnose this particular error later. 2735 if ((T->isArrayType() || T->isFunctionType()) && 2736 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 2737 unsigned diagID = diag::err_func_returning_array_function; 2738 // Last processing chunk in block context means this function chunk 2739 // represents the block. 2740 if (chunkIndex == 0 && 2741 D.getContext() == Declarator::BlockLiteralContext) 2742 diagID = diag::err_block_returning_array_function; 2743 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 2744 T = Context.IntTy; 2745 D.setInvalidType(true); 2746 } 2747 2748 // Do not allow returning half FP value. 2749 // FIXME: This really should be in BuildFunctionType. 2750 if (T->isHalfType()) { 2751 if (S.getLangOpts().OpenCL) { 2752 if (!S.getOpenCLOptions().cl_khr_fp16) { 2753 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T; 2754 D.setInvalidType(true); 2755 } 2756 } else if (!S.getLangOpts().HalfArgsAndReturns) { 2757 S.Diag(D.getIdentifierLoc(), 2758 diag::err_parameters_retval_cannot_have_fp16_type) << 1; 2759 D.setInvalidType(true); 2760 } 2761 } 2762 2763 // Methods cannot return interface types. All ObjC objects are 2764 // passed by reference. 2765 if (T->isObjCObjectType()) { 2766 SourceLocation DiagLoc, FixitLoc; 2767 if (TInfo) { 2768 DiagLoc = TInfo->getTypeLoc().getLocStart(); 2769 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd()); 2770 } else { 2771 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 2772 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd()); 2773 } 2774 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) 2775 << 0 << T 2776 << FixItHint::CreateInsertion(FixitLoc, "*"); 2777 2778 T = Context.getObjCObjectPointerType(T); 2779 if (TInfo) { 2780 TypeLocBuilder TLB; 2781 TLB.pushFullCopy(TInfo->getTypeLoc()); 2782 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); 2783 TLoc.setStarLoc(FixitLoc); 2784 TInfo = TLB.getTypeSourceInfo(Context, T); 2785 } 2786 2787 D.setInvalidType(true); 2788 } 2789 2790 // cv-qualifiers on return types are pointless except when the type is a 2791 // class type in C++. 2792 if ((T.getCVRQualifiers() || T->isAtomicType()) && 2793 !(S.getLangOpts().CPlusPlus && 2794 (T->isDependentType() || T->isRecordType()))) 2795 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); 2796 2797 // Objective-C ARC ownership qualifiers are ignored on the function 2798 // return type (by type canonicalization). Complain if this attribute 2799 // was written here. 2800 if (T.getQualifiers().hasObjCLifetime()) { 2801 SourceLocation AttrLoc; 2802 if (chunkIndex + 1 < D.getNumTypeObjects()) { 2803 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 2804 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs(); 2805 Attr; Attr = Attr->getNext()) { 2806 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 2807 AttrLoc = Attr->getLoc(); 2808 break; 2809 } 2810 } 2811 } 2812 if (AttrLoc.isInvalid()) { 2813 for (const AttributeList *Attr 2814 = D.getDeclSpec().getAttributes().getList(); 2815 Attr; Attr = Attr->getNext()) { 2816 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 2817 AttrLoc = Attr->getLoc(); 2818 break; 2819 } 2820 } 2821 } 2822 2823 if (AttrLoc.isValid()) { 2824 // The ownership attributes are almost always written via 2825 // the predefined 2826 // __strong/__weak/__autoreleasing/__unsafe_unretained. 2827 if (AttrLoc.isMacroID()) 2828 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first; 2829 2830 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 2831 << T.getQualifiers().getObjCLifetime(); 2832 } 2833 } 2834 2835 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { 2836 // C++ [dcl.fct]p6: 2837 // Types shall not be defined in return or parameter types. 2838 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2839 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 2840 << Context.getTypeDeclType(Tag); 2841 } 2842 2843 // Exception specs are not allowed in typedefs. Complain, but add it 2844 // anyway. 2845 if (IsTypedefName && FTI.getExceptionSpecType()) 2846 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef) 2847 << (D.getContext() == Declarator::AliasDeclContext || 2848 D.getContext() == Declarator::AliasTemplateContext); 2849 2850 // If we see "T var();" or "T var(T());" at block scope, it is probably 2851 // an attempt to initialize a variable, not a function declaration. 2852 if (FTI.isAmbiguous) 2853 warnAboutAmbiguousFunction(S, D, DeclType, T); 2854 2855 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex)); 2856 2857 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) { 2858 // Simple void foo(), where the incoming T is the result type. 2859 T = Context.getFunctionNoProtoType(T, EI); 2860 } else { 2861 // We allow a zero-parameter variadic function in C if the 2862 // function is marked with the "overloadable" attribute. Scan 2863 // for this attribute now. 2864 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) { 2865 bool Overloadable = false; 2866 for (const AttributeList *Attrs = D.getAttributes(); 2867 Attrs; Attrs = Attrs->getNext()) { 2868 if (Attrs->getKind() == AttributeList::AT_Overloadable) { 2869 Overloadable = true; 2870 break; 2871 } 2872 } 2873 2874 if (!Overloadable) 2875 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); 2876 } 2877 2878 if (FTI.NumParams && FTI.Params[0].Param == nullptr) { 2879 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 2880 // definition. 2881 S.Diag(FTI.Params[0].IdentLoc, 2882 diag::err_ident_list_in_fn_declaration); 2883 D.setInvalidType(true); 2884 // Recover by creating a K&R-style function type. 2885 T = Context.getFunctionNoProtoType(T, EI); 2886 break; 2887 } 2888 2889 FunctionProtoType::ExtProtoInfo EPI; 2890 EPI.ExtInfo = EI; 2891 EPI.Variadic = FTI.isVariadic; 2892 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 2893 EPI.TypeQuals = FTI.TypeQuals; 2894 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 2895 : FTI.RefQualifierIsLValueRef? RQ_LValue 2896 : RQ_RValue; 2897 2898 // Otherwise, we have a function with a parameter list that is 2899 // potentially variadic. 2900 SmallVector<QualType, 16> ParamTys; 2901 ParamTys.reserve(FTI.NumParams); 2902 2903 SmallVector<bool, 16> ConsumedParameters; 2904 ConsumedParameters.reserve(FTI.NumParams); 2905 bool HasAnyConsumedParameters = false; 2906 2907 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 2908 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 2909 QualType ParamTy = Param->getType(); 2910 assert(!ParamTy.isNull() && "Couldn't parse type?"); 2911 2912 // Look for 'void'. void is allowed only as a single parameter to a 2913 // function with no other parameters (C99 6.7.5.3p10). We record 2914 // int(void) as a FunctionProtoType with an empty parameter list. 2915 if (ParamTy->isVoidType()) { 2916 // If this is something like 'float(int, void)', reject it. 'void' 2917 // is an incomplete type (C99 6.2.5p19) and function decls cannot 2918 // have parameters of incomplete type. 2919 if (FTI.NumParams != 1 || FTI.isVariadic) { 2920 S.Diag(DeclType.Loc, diag::err_void_only_param); 2921 ParamTy = Context.IntTy; 2922 Param->setType(ParamTy); 2923 } else if (FTI.Params[i].Ident) { 2924 // Reject, but continue to parse 'int(void abc)'. 2925 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); 2926 ParamTy = Context.IntTy; 2927 Param->setType(ParamTy); 2928 } else { 2929 // Reject, but continue to parse 'float(const void)'. 2930 if (ParamTy.hasQualifiers()) 2931 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 2932 2933 // Do not add 'void' to the list. 2934 break; 2935 } 2936 } else if (ParamTy->isHalfType()) { 2937 // Disallow half FP parameters. 2938 // FIXME: This really should be in BuildFunctionType. 2939 if (S.getLangOpts().OpenCL) { 2940 if (!S.getOpenCLOptions().cl_khr_fp16) { 2941 S.Diag(Param->getLocation(), 2942 diag::err_opencl_half_param) << ParamTy; 2943 D.setInvalidType(); 2944 Param->setInvalidDecl(); 2945 } 2946 } else if (!S.getLangOpts().HalfArgsAndReturns) { 2947 S.Diag(Param->getLocation(), 2948 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 2949 D.setInvalidType(); 2950 } 2951 } else if (!FTI.hasPrototype) { 2952 if (ParamTy->isPromotableIntegerType()) { 2953 ParamTy = Context.getPromotedIntegerType(ParamTy); 2954 Param->setKNRPromoted(true); 2955 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { 2956 if (BTy->getKind() == BuiltinType::Float) { 2957 ParamTy = Context.DoubleTy; 2958 Param->setKNRPromoted(true); 2959 } 2960 } 2961 } 2962 2963 if (LangOpts.ObjCAutoRefCount) { 2964 bool Consumed = Param->hasAttr<NSConsumedAttr>(); 2965 ConsumedParameters.push_back(Consumed); 2966 HasAnyConsumedParameters |= Consumed; 2967 } 2968 2969 ParamTys.push_back(ParamTy); 2970 } 2971 2972 if (HasAnyConsumedParameters) 2973 EPI.ConsumedParameters = ConsumedParameters.data(); 2974 2975 SmallVector<QualType, 4> Exceptions; 2976 SmallVector<ParsedType, 2> DynamicExceptions; 2977 SmallVector<SourceRange, 2> DynamicExceptionRanges; 2978 Expr *NoexceptExpr = nullptr; 2979 2980 if (FTI.getExceptionSpecType() == EST_Dynamic) { 2981 // FIXME: It's rather inefficient to have to split into two vectors 2982 // here. 2983 unsigned N = FTI.NumExceptions; 2984 DynamicExceptions.reserve(N); 2985 DynamicExceptionRanges.reserve(N); 2986 for (unsigned I = 0; I != N; ++I) { 2987 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 2988 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 2989 } 2990 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 2991 NoexceptExpr = FTI.NoexceptExpr; 2992 } 2993 2994 S.checkExceptionSpecification(FTI.getExceptionSpecType(), 2995 DynamicExceptions, 2996 DynamicExceptionRanges, 2997 NoexceptExpr, 2998 Exceptions, 2999 EPI.ExceptionSpec); 3000 3001 T = Context.getFunctionType(T, ParamTys, EPI); 3002 } 3003 3004 break; 3005 } 3006 case DeclaratorChunk::MemberPointer: 3007 // The scope spec must refer to a class, or be dependent. 3008 CXXScopeSpec &SS = DeclType.Mem.Scope(); 3009 QualType ClsType; 3010 if (SS.isInvalid()) { 3011 // Avoid emitting extra errors if we already errored on the scope. 3012 D.setInvalidType(true); 3013 } else if (S.isDependentScopeSpecifier(SS) || 3014 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 3015 NestedNameSpecifier *NNS = SS.getScopeRep(); 3016 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 3017 switch (NNS->getKind()) { 3018 case NestedNameSpecifier::Identifier: 3019 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 3020 NNS->getAsIdentifier()); 3021 break; 3022 3023 case NestedNameSpecifier::Namespace: 3024 case NestedNameSpecifier::NamespaceAlias: 3025 case NestedNameSpecifier::Global: 3026 case NestedNameSpecifier::Super: 3027 llvm_unreachable("Nested-name-specifier must name a type"); 3028 3029 case NestedNameSpecifier::TypeSpec: 3030 case NestedNameSpecifier::TypeSpecWithTemplate: 3031 ClsType = QualType(NNS->getAsType(), 0); 3032 // Note: if the NNS has a prefix and ClsType is a nondependent 3033 // TemplateSpecializationType, then the NNS prefix is NOT included 3034 // in ClsType; hence we wrap ClsType into an ElaboratedType. 3035 // NOTE: in particular, no wrap occurs if ClsType already is an 3036 // Elaborated, DependentName, or DependentTemplateSpecialization. 3037 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 3038 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 3039 break; 3040 } 3041 } else { 3042 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 3043 diag::err_illegal_decl_mempointer_in_nonclass) 3044 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 3045 << DeclType.Mem.Scope().getRange(); 3046 D.setInvalidType(true); 3047 } 3048 3049 if (!ClsType.isNull()) 3050 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier()); 3051 if (T.isNull()) { 3052 T = Context.IntTy; 3053 D.setInvalidType(true); 3054 } else if (DeclType.Mem.TypeQuals) { 3055 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 3056 } 3057 break; 3058 } 3059 3060 if (T.isNull()) { 3061 D.setInvalidType(true); 3062 T = Context.IntTy; 3063 } 3064 3065 // See if there are any attributes on this declarator chunk. 3066 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs())) 3067 processTypeAttrs(state, T, TAL_DeclChunk, attrs); 3068 } 3069 3070 if (LangOpts.CPlusPlus && T->isFunctionType()) { 3071 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 3072 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 3073 3074 // C++ 8.3.5p4: 3075 // A cv-qualifier-seq shall only be part of the function type 3076 // for a nonstatic member function, the function type to which a pointer 3077 // to member refers, or the top-level function type of a function typedef 3078 // declaration. 3079 // 3080 // Core issue 547 also allows cv-qualifiers on function types that are 3081 // top-level template type arguments. 3082 bool FreeFunction; 3083 if (!D.getCXXScopeSpec().isSet()) { 3084 FreeFunction = ((D.getContext() != Declarator::MemberContext && 3085 D.getContext() != Declarator::LambdaExprContext) || 3086 D.getDeclSpec().isFriendSpecified()); 3087 } else { 3088 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 3089 FreeFunction = (DC && !DC->isRecord()); 3090 } 3091 3092 // C++11 [dcl.fct]p6 (w/DR1417): 3093 // An attempt to specify a function type with a cv-qualifier-seq or a 3094 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 3095 // - the function type for a non-static member function, 3096 // - the function type to which a pointer to member refers, 3097 // - the top-level function type of a function typedef declaration or 3098 // alias-declaration, 3099 // - the type-id in the default argument of a type-parameter, or 3100 // - the type-id of a template-argument for a type-parameter 3101 // 3102 // FIXME: Checking this here is insufficient. We accept-invalid on: 3103 // 3104 // template<typename T> struct S { void f(T); }; 3105 // S<int() const> s; 3106 // 3107 // ... for instance. 3108 if (IsQualifiedFunction && 3109 !(!FreeFunction && 3110 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 3111 !IsTypedefName && 3112 D.getContext() != Declarator::TemplateTypeArgContext) { 3113 SourceLocation Loc = D.getLocStart(); 3114 SourceRange RemovalRange; 3115 unsigned I; 3116 if (D.isFunctionDeclarator(I)) { 3117 SmallVector<SourceLocation, 4> RemovalLocs; 3118 const DeclaratorChunk &Chunk = D.getTypeObject(I); 3119 assert(Chunk.Kind == DeclaratorChunk::Function); 3120 if (Chunk.Fun.hasRefQualifier()) 3121 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 3122 if (Chunk.Fun.TypeQuals & Qualifiers::Const) 3123 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); 3124 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) 3125 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); 3126 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) 3127 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); 3128 if (!RemovalLocs.empty()) { 3129 std::sort(RemovalLocs.begin(), RemovalLocs.end(), 3130 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 3131 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 3132 Loc = RemovalLocs.front(); 3133 } 3134 } 3135 3136 S.Diag(Loc, diag::err_invalid_qualified_function_type) 3137 << FreeFunction << D.isFunctionDeclarator() << T 3138 << getFunctionQualifiersAsString(FnTy) 3139 << FixItHint::CreateRemoval(RemovalRange); 3140 3141 // Strip the cv-qualifiers and ref-qualifiers from the type. 3142 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 3143 EPI.TypeQuals = 0; 3144 EPI.RefQualifier = RQ_None; 3145 3146 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), 3147 EPI); 3148 // Rebuild any parens around the identifier in the function type. 3149 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3150 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 3151 break; 3152 T = S.BuildParenType(T); 3153 } 3154 } 3155 } 3156 3157 // Apply any undistributed attributes from the declarator. 3158 if (!T.isNull()) 3159 if (AttributeList *attrs = D.getAttributes()) 3160 processTypeAttrs(state, T, TAL_DeclName, attrs); 3161 3162 // Diagnose any ignored type attributes. 3163 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T); 3164 3165 // C++0x [dcl.constexpr]p9: 3166 // A constexpr specifier used in an object declaration declares the object 3167 // as const. 3168 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 3169 T.addConst(); 3170 } 3171 3172 // If there was an ellipsis in the declarator, the declaration declares a 3173 // parameter pack whose type may be a pack expansion type. 3174 if (D.hasEllipsis() && !T.isNull()) { 3175 // C++0x [dcl.fct]p13: 3176 // A declarator-id or abstract-declarator containing an ellipsis shall 3177 // only be used in a parameter-declaration. Such a parameter-declaration 3178 // is a parameter pack (14.5.3). [...] 3179 switch (D.getContext()) { 3180 case Declarator::PrototypeContext: 3181 case Declarator::LambdaExprParameterContext: 3182 // C++0x [dcl.fct]p13: 3183 // [...] When it is part of a parameter-declaration-clause, the 3184 // parameter pack is a function parameter pack (14.5.3). The type T 3185 // of the declarator-id of the function parameter pack shall contain 3186 // a template parameter pack; each template parameter pack in T is 3187 // expanded by the function parameter pack. 3188 // 3189 // We represent function parameter packs as function parameters whose 3190 // type is a pack expansion. 3191 if (!T->containsUnexpandedParameterPack()) { 3192 S.Diag(D.getEllipsisLoc(), 3193 diag::err_function_parameter_pack_without_parameter_packs) 3194 << T << D.getSourceRange(); 3195 D.setEllipsisLoc(SourceLocation()); 3196 } else { 3197 T = Context.getPackExpansionType(T, None); 3198 } 3199 break; 3200 case Declarator::TemplateParamContext: 3201 // C++0x [temp.param]p15: 3202 // If a template-parameter is a [...] is a parameter-declaration that 3203 // declares a parameter pack (8.3.5), then the template-parameter is a 3204 // template parameter pack (14.5.3). 3205 // 3206 // Note: core issue 778 clarifies that, if there are any unexpanded 3207 // parameter packs in the type of the non-type template parameter, then 3208 // it expands those parameter packs. 3209 if (T->containsUnexpandedParameterPack()) 3210 T = Context.getPackExpansionType(T, None); 3211 else 3212 S.Diag(D.getEllipsisLoc(), 3213 LangOpts.CPlusPlus11 3214 ? diag::warn_cxx98_compat_variadic_templates 3215 : diag::ext_variadic_templates); 3216 break; 3217 3218 case Declarator::FileContext: 3219 case Declarator::KNRTypeListContext: 3220 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here? 3221 case Declarator::ObjCResultContext: // FIXME: special diagnostic here? 3222 case Declarator::TypeNameContext: 3223 case Declarator::CXXNewContext: 3224 case Declarator::AliasDeclContext: 3225 case Declarator::AliasTemplateContext: 3226 case Declarator::MemberContext: 3227 case Declarator::BlockContext: 3228 case Declarator::ForContext: 3229 case Declarator::ConditionContext: 3230 case Declarator::CXXCatchContext: 3231 case Declarator::ObjCCatchContext: 3232 case Declarator::BlockLiteralContext: 3233 case Declarator::LambdaExprContext: 3234 case Declarator::ConversionIdContext: 3235 case Declarator::TrailingReturnContext: 3236 case Declarator::TemplateTypeArgContext: 3237 // FIXME: We may want to allow parameter packs in block-literal contexts 3238 // in the future. 3239 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter); 3240 D.setEllipsisLoc(SourceLocation()); 3241 break; 3242 } 3243 } 3244 3245 if (T.isNull()) 3246 return Context.getNullTypeSourceInfo(); 3247 else if (D.isInvalidType()) 3248 return Context.getTrivialTypeSourceInfo(T); 3249 3250 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 3251 } 3252 3253 /// GetTypeForDeclarator - Convert the type for the specified 3254 /// declarator to Type instances. 3255 /// 3256 /// The result of this call will never be null, but the associated 3257 /// type may be a null type if there's an unrecoverable error. 3258 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 3259 // Determine the type of the declarator. Not all forms of declarator 3260 // have a type. 3261 3262 TypeProcessingState state(*this, D); 3263 3264 TypeSourceInfo *ReturnTypeInfo = nullptr; 3265 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 3266 if (T.isNull()) 3267 return Context.getNullTypeSourceInfo(); 3268 3269 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 3270 inferARCWriteback(state, T); 3271 3272 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 3273 } 3274 3275 static void transferARCOwnershipToDeclSpec(Sema &S, 3276 QualType &declSpecTy, 3277 Qualifiers::ObjCLifetime ownership) { 3278 if (declSpecTy->isObjCRetainableType() && 3279 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 3280 Qualifiers qs; 3281 qs.addObjCLifetime(ownership); 3282 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 3283 } 3284 } 3285 3286 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 3287 Qualifiers::ObjCLifetime ownership, 3288 unsigned chunkIndex) { 3289 Sema &S = state.getSema(); 3290 Declarator &D = state.getDeclarator(); 3291 3292 // Look for an explicit lifetime attribute. 3293 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 3294 for (const AttributeList *attr = chunk.getAttrs(); attr; 3295 attr = attr->getNext()) 3296 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 3297 return; 3298 3299 const char *attrStr = nullptr; 3300 switch (ownership) { 3301 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 3302 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 3303 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 3304 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 3305 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 3306 } 3307 3308 IdentifierLoc *Arg = new (S.Context) IdentifierLoc; 3309 Arg->Ident = &S.Context.Idents.get(attrStr); 3310 Arg->Loc = SourceLocation(); 3311 3312 ArgsUnion Args(Arg); 3313 3314 // If there wasn't one, add one (with an invalid source location 3315 // so that we don't make an AttributedType for it). 3316 AttributeList *attr = D.getAttributePool() 3317 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 3318 /*scope*/ nullptr, SourceLocation(), 3319 /*args*/ &Args, 1, AttributeList::AS_GNU); 3320 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 3321 3322 // TODO: mark whether we did this inference? 3323 } 3324 3325 /// \brief Used for transferring ownership in casts resulting in l-values. 3326 static void transferARCOwnership(TypeProcessingState &state, 3327 QualType &declSpecTy, 3328 Qualifiers::ObjCLifetime ownership) { 3329 Sema &S = state.getSema(); 3330 Declarator &D = state.getDeclarator(); 3331 3332 int inner = -1; 3333 bool hasIndirection = false; 3334 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3335 DeclaratorChunk &chunk = D.getTypeObject(i); 3336 switch (chunk.Kind) { 3337 case DeclaratorChunk::Paren: 3338 // Ignore parens. 3339 break; 3340 3341 case DeclaratorChunk::Array: 3342 case DeclaratorChunk::Reference: 3343 case DeclaratorChunk::Pointer: 3344 if (inner != -1) 3345 hasIndirection = true; 3346 inner = i; 3347 break; 3348 3349 case DeclaratorChunk::BlockPointer: 3350 if (inner != -1) 3351 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 3352 return; 3353 3354 case DeclaratorChunk::Function: 3355 case DeclaratorChunk::MemberPointer: 3356 return; 3357 } 3358 } 3359 3360 if (inner == -1) 3361 return; 3362 3363 DeclaratorChunk &chunk = D.getTypeObject(inner); 3364 if (chunk.Kind == DeclaratorChunk::Pointer) { 3365 if (declSpecTy->isObjCRetainableType()) 3366 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 3367 if (declSpecTy->isObjCObjectType() && hasIndirection) 3368 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 3369 } else { 3370 assert(chunk.Kind == DeclaratorChunk::Array || 3371 chunk.Kind == DeclaratorChunk::Reference); 3372 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 3373 } 3374 } 3375 3376 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 3377 TypeProcessingState state(*this, D); 3378 3379 TypeSourceInfo *ReturnTypeInfo = nullptr; 3380 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 3381 if (declSpecTy.isNull()) 3382 return Context.getNullTypeSourceInfo(); 3383 3384 if (getLangOpts().ObjCAutoRefCount) { 3385 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 3386 if (ownership != Qualifiers::OCL_None) 3387 transferARCOwnership(state, declSpecTy, ownership); 3388 } 3389 3390 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 3391 } 3392 3393 /// Map an AttributedType::Kind to an AttributeList::Kind. 3394 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 3395 switch (kind) { 3396 case AttributedType::attr_address_space: 3397 return AttributeList::AT_AddressSpace; 3398 case AttributedType::attr_regparm: 3399 return AttributeList::AT_Regparm; 3400 case AttributedType::attr_vector_size: 3401 return AttributeList::AT_VectorSize; 3402 case AttributedType::attr_neon_vector_type: 3403 return AttributeList::AT_NeonVectorType; 3404 case AttributedType::attr_neon_polyvector_type: 3405 return AttributeList::AT_NeonPolyVectorType; 3406 case AttributedType::attr_objc_gc: 3407 return AttributeList::AT_ObjCGC; 3408 case AttributedType::attr_objc_ownership: 3409 return AttributeList::AT_ObjCOwnership; 3410 case AttributedType::attr_noreturn: 3411 return AttributeList::AT_NoReturn; 3412 case AttributedType::attr_cdecl: 3413 return AttributeList::AT_CDecl; 3414 case AttributedType::attr_fastcall: 3415 return AttributeList::AT_FastCall; 3416 case AttributedType::attr_stdcall: 3417 return AttributeList::AT_StdCall; 3418 case AttributedType::attr_thiscall: 3419 return AttributeList::AT_ThisCall; 3420 case AttributedType::attr_pascal: 3421 return AttributeList::AT_Pascal; 3422 case AttributedType::attr_vectorcall: 3423 return AttributeList::AT_VectorCall; 3424 case AttributedType::attr_pcs: 3425 case AttributedType::attr_pcs_vfp: 3426 return AttributeList::AT_Pcs; 3427 case AttributedType::attr_pnaclcall: 3428 return AttributeList::AT_PnaclCall; 3429 case AttributedType::attr_inteloclbicc: 3430 return AttributeList::AT_IntelOclBicc; 3431 case AttributedType::attr_ms_abi: 3432 return AttributeList::AT_MSABI; 3433 case AttributedType::attr_sysv_abi: 3434 return AttributeList::AT_SysVABI; 3435 case AttributedType::attr_ptr32: 3436 return AttributeList::AT_Ptr32; 3437 case AttributedType::attr_ptr64: 3438 return AttributeList::AT_Ptr64; 3439 case AttributedType::attr_sptr: 3440 return AttributeList::AT_SPtr; 3441 case AttributedType::attr_uptr: 3442 return AttributeList::AT_UPtr; 3443 } 3444 llvm_unreachable("unexpected attribute kind!"); 3445 } 3446 3447 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 3448 const AttributeList *attrs) { 3449 AttributedType::Kind kind = TL.getAttrKind(); 3450 3451 assert(attrs && "no type attributes in the expected location!"); 3452 AttributeList::Kind parsedKind = getAttrListKind(kind); 3453 while (attrs->getKind() != parsedKind) { 3454 attrs = attrs->getNext(); 3455 assert(attrs && "no matching attribute in expected location!"); 3456 } 3457 3458 TL.setAttrNameLoc(attrs->getLoc()); 3459 if (TL.hasAttrExprOperand()) { 3460 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind"); 3461 TL.setAttrExprOperand(attrs->getArgAsExpr(0)); 3462 } else if (TL.hasAttrEnumOperand()) { 3463 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) && 3464 "unexpected attribute operand kind"); 3465 if (attrs->isArgIdent(0)) 3466 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc); 3467 else 3468 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc()); 3469 } 3470 3471 // FIXME: preserve this information to here. 3472 if (TL.hasAttrOperand()) 3473 TL.setAttrOperandParensRange(SourceRange()); 3474 } 3475 3476 namespace { 3477 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 3478 ASTContext &Context; 3479 const DeclSpec &DS; 3480 3481 public: 3482 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 3483 : Context(Context), DS(DS) {} 3484 3485 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 3486 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 3487 Visit(TL.getModifiedLoc()); 3488 } 3489 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 3490 Visit(TL.getUnqualifiedLoc()); 3491 } 3492 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 3493 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 3494 } 3495 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 3496 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 3497 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 3498 // addition field. What we have is good enough for dispay of location 3499 // of 'fixit' on interface name. 3500 TL.setNameEndLoc(DS.getLocEnd()); 3501 } 3502 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 3503 // Handle the base type, which might not have been written explicitly. 3504 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 3505 TL.setHasBaseTypeAsWritten(false); 3506 TL.getBaseLoc().initialize(Context, SourceLocation()); 3507 } else { 3508 TL.setHasBaseTypeAsWritten(true); 3509 Visit(TL.getBaseLoc()); 3510 } 3511 3512 // Protocol qualifiers. 3513 if (DS.getProtocolQualifiers()) { 3514 assert(TL.getNumProtocols() > 0); 3515 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 3516 TL.setLAngleLoc(DS.getProtocolLAngleLoc()); 3517 TL.setRAngleLoc(DS.getSourceRange().getEnd()); 3518 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i) 3519 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]); 3520 } else { 3521 assert(TL.getNumProtocols() == 0); 3522 TL.setLAngleLoc(SourceLocation()); 3523 TL.setRAngleLoc(SourceLocation()); 3524 } 3525 } 3526 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 3527 TL.setStarLoc(SourceLocation()); 3528 Visit(TL.getPointeeLoc()); 3529 } 3530 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 3531 TypeSourceInfo *TInfo = nullptr; 3532 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3533 3534 // If we got no declarator info from previous Sema routines, 3535 // just fill with the typespec loc. 3536 if (!TInfo) { 3537 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 3538 return; 3539 } 3540 3541 TypeLoc OldTL = TInfo->getTypeLoc(); 3542 if (TInfo->getType()->getAs<ElaboratedType>()) { 3543 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 3544 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 3545 .castAs<TemplateSpecializationTypeLoc>(); 3546 TL.copy(NamedTL); 3547 } else { 3548 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 3549 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 3550 } 3551 3552 } 3553 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 3554 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 3555 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 3556 TL.setParensRange(DS.getTypeofParensRange()); 3557 } 3558 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 3559 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 3560 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 3561 TL.setParensRange(DS.getTypeofParensRange()); 3562 assert(DS.getRepAsType()); 3563 TypeSourceInfo *TInfo = nullptr; 3564 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3565 TL.setUnderlyingTInfo(TInfo); 3566 } 3567 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 3568 // FIXME: This holds only because we only have one unary transform. 3569 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 3570 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 3571 TL.setParensRange(DS.getTypeofParensRange()); 3572 assert(DS.getRepAsType()); 3573 TypeSourceInfo *TInfo = nullptr; 3574 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3575 TL.setUnderlyingTInfo(TInfo); 3576 } 3577 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 3578 // By default, use the source location of the type specifier. 3579 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 3580 if (TL.needsExtraLocalData()) { 3581 // Set info for the written builtin specifiers. 3582 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 3583 // Try to have a meaningful source location. 3584 if (TL.getWrittenSignSpec() != TSS_unspecified) 3585 // Sign spec loc overrides the others (e.g., 'unsigned long'). 3586 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 3587 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 3588 // Width spec loc overrides type spec loc (e.g., 'short int'). 3589 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 3590 } 3591 } 3592 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 3593 ElaboratedTypeKeyword Keyword 3594 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 3595 if (DS.getTypeSpecType() == TST_typename) { 3596 TypeSourceInfo *TInfo = nullptr; 3597 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3598 if (TInfo) { 3599 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 3600 return; 3601 } 3602 } 3603 TL.setElaboratedKeywordLoc(Keyword != ETK_None 3604 ? DS.getTypeSpecTypeLoc() 3605 : SourceLocation()); 3606 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 3607 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3608 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 3609 } 3610 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 3611 assert(DS.getTypeSpecType() == TST_typename); 3612 TypeSourceInfo *TInfo = nullptr; 3613 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3614 assert(TInfo); 3615 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 3616 } 3617 void VisitDependentTemplateSpecializationTypeLoc( 3618 DependentTemplateSpecializationTypeLoc TL) { 3619 assert(DS.getTypeSpecType() == TST_typename); 3620 TypeSourceInfo *TInfo = nullptr; 3621 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3622 assert(TInfo); 3623 TL.copy( 3624 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 3625 } 3626 void VisitTagTypeLoc(TagTypeLoc TL) { 3627 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 3628 } 3629 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 3630 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 3631 // or an _Atomic qualifier. 3632 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 3633 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 3634 TL.setParensRange(DS.getTypeofParensRange()); 3635 3636 TypeSourceInfo *TInfo = nullptr; 3637 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3638 assert(TInfo); 3639 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 3640 } else { 3641 TL.setKWLoc(DS.getAtomicSpecLoc()); 3642 // No parens, to indicate this was spelled as an _Atomic qualifier. 3643 TL.setParensRange(SourceRange()); 3644 Visit(TL.getValueLoc()); 3645 } 3646 } 3647 3648 void VisitTypeLoc(TypeLoc TL) { 3649 // FIXME: add other typespec types and change this to an assert. 3650 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 3651 } 3652 }; 3653 3654 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 3655 ASTContext &Context; 3656 const DeclaratorChunk &Chunk; 3657 3658 public: 3659 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 3660 : Context(Context), Chunk(Chunk) {} 3661 3662 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 3663 llvm_unreachable("qualified type locs not expected here!"); 3664 } 3665 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 3666 llvm_unreachable("decayed type locs not expected here!"); 3667 } 3668 3669 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 3670 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 3671 } 3672 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 3673 // nothing 3674 } 3675 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 3676 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 3677 TL.setCaretLoc(Chunk.Loc); 3678 } 3679 void VisitPointerTypeLoc(PointerTypeLoc TL) { 3680 assert(Chunk.Kind == DeclaratorChunk::Pointer); 3681 TL.setStarLoc(Chunk.Loc); 3682 } 3683 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 3684 assert(Chunk.Kind == DeclaratorChunk::Pointer); 3685 TL.setStarLoc(Chunk.Loc); 3686 } 3687 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 3688 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 3689 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 3690 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 3691 3692 const Type* ClsTy = TL.getClass(); 3693 QualType ClsQT = QualType(ClsTy, 0); 3694 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 3695 // Now copy source location info into the type loc component. 3696 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 3697 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 3698 case NestedNameSpecifier::Identifier: 3699 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 3700 { 3701 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 3702 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 3703 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 3704 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 3705 } 3706 break; 3707 3708 case NestedNameSpecifier::TypeSpec: 3709 case NestedNameSpecifier::TypeSpecWithTemplate: 3710 if (isa<ElaboratedType>(ClsTy)) { 3711 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 3712 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 3713 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 3714 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 3715 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 3716 } else { 3717 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 3718 } 3719 break; 3720 3721 case NestedNameSpecifier::Namespace: 3722 case NestedNameSpecifier::NamespaceAlias: 3723 case NestedNameSpecifier::Global: 3724 case NestedNameSpecifier::Super: 3725 llvm_unreachable("Nested-name-specifier must name a type"); 3726 } 3727 3728 // Finally fill in MemberPointerLocInfo fields. 3729 TL.setStarLoc(Chunk.Loc); 3730 TL.setClassTInfo(ClsTInfo); 3731 } 3732 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 3733 assert(Chunk.Kind == DeclaratorChunk::Reference); 3734 // 'Amp' is misleading: this might have been originally 3735 /// spelled with AmpAmp. 3736 TL.setAmpLoc(Chunk.Loc); 3737 } 3738 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 3739 assert(Chunk.Kind == DeclaratorChunk::Reference); 3740 assert(!Chunk.Ref.LValueRef); 3741 TL.setAmpAmpLoc(Chunk.Loc); 3742 } 3743 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 3744 assert(Chunk.Kind == DeclaratorChunk::Array); 3745 TL.setLBracketLoc(Chunk.Loc); 3746 TL.setRBracketLoc(Chunk.EndLoc); 3747 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 3748 } 3749 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 3750 assert(Chunk.Kind == DeclaratorChunk::Function); 3751 TL.setLocalRangeBegin(Chunk.Loc); 3752 TL.setLocalRangeEnd(Chunk.EndLoc); 3753 3754 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 3755 TL.setLParenLoc(FTI.getLParenLoc()); 3756 TL.setRParenLoc(FTI.getRParenLoc()); 3757 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { 3758 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 3759 TL.setParam(tpi++, Param); 3760 } 3761 // FIXME: exception specs 3762 } 3763 void VisitParenTypeLoc(ParenTypeLoc TL) { 3764 assert(Chunk.Kind == DeclaratorChunk::Paren); 3765 TL.setLParenLoc(Chunk.Loc); 3766 TL.setRParenLoc(Chunk.EndLoc); 3767 } 3768 3769 void VisitTypeLoc(TypeLoc TL) { 3770 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 3771 } 3772 }; 3773 } 3774 3775 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 3776 SourceLocation Loc; 3777 switch (Chunk.Kind) { 3778 case DeclaratorChunk::Function: 3779 case DeclaratorChunk::Array: 3780 case DeclaratorChunk::Paren: 3781 llvm_unreachable("cannot be _Atomic qualified"); 3782 3783 case DeclaratorChunk::Pointer: 3784 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); 3785 break; 3786 3787 case DeclaratorChunk::BlockPointer: 3788 case DeclaratorChunk::Reference: 3789 case DeclaratorChunk::MemberPointer: 3790 // FIXME: Provide a source location for the _Atomic keyword. 3791 break; 3792 } 3793 3794 ATL.setKWLoc(Loc); 3795 ATL.setParensRange(SourceRange()); 3796 } 3797 3798 /// \brief Create and instantiate a TypeSourceInfo with type source information. 3799 /// 3800 /// \param T QualType referring to the type as written in source code. 3801 /// 3802 /// \param ReturnTypeInfo For declarators whose return type does not show 3803 /// up in the normal place in the declaration specifiers (such as a C++ 3804 /// conversion function), this pointer will refer to a type source information 3805 /// for that return type. 3806 TypeSourceInfo * 3807 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 3808 TypeSourceInfo *ReturnTypeInfo) { 3809 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 3810 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 3811 3812 // Handle parameter packs whose type is a pack expansion. 3813 if (isa<PackExpansionType>(T)) { 3814 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 3815 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 3816 } 3817 3818 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3819 // An AtomicTypeLoc might be produced by an atomic qualifier in this 3820 // declarator chunk. 3821 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 3822 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 3823 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 3824 } 3825 3826 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 3827 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs()); 3828 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 3829 } 3830 3831 // FIXME: Ordering here? 3832 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) 3833 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 3834 3835 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 3836 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 3837 } 3838 3839 // If we have different source information for the return type, use 3840 // that. This really only applies to C++ conversion functions. 3841 if (ReturnTypeInfo) { 3842 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 3843 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 3844 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 3845 } else { 3846 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 3847 } 3848 3849 return TInfo; 3850 } 3851 3852 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 3853 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 3854 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 3855 // and Sema during declaration parsing. Try deallocating/caching them when 3856 // it's appropriate, instead of allocating them and keeping them around. 3857 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 3858 TypeAlignment); 3859 new (LocT) LocInfoType(T, TInfo); 3860 assert(LocT->getTypeClass() != T->getTypeClass() && 3861 "LocInfoType's TypeClass conflicts with an existing Type class"); 3862 return ParsedType::make(QualType(LocT, 0)); 3863 } 3864 3865 void LocInfoType::getAsStringInternal(std::string &Str, 3866 const PrintingPolicy &Policy) const { 3867 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 3868 " was used directly instead of getting the QualType through" 3869 " GetTypeFromParser"); 3870 } 3871 3872 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 3873 // C99 6.7.6: Type names have no identifier. This is already validated by 3874 // the parser. 3875 assert(D.getIdentifier() == nullptr && 3876 "Type name should have no identifier!"); 3877 3878 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3879 QualType T = TInfo->getType(); 3880 if (D.isInvalidType()) 3881 return true; 3882 3883 // Make sure there are no unused decl attributes on the declarator. 3884 // We don't want to do this for ObjC parameters because we're going 3885 // to apply them to the actual parameter declaration. 3886 // Likewise, we don't want to do this for alias declarations, because 3887 // we are actually going to build a declaration from this eventually. 3888 if (D.getContext() != Declarator::ObjCParameterContext && 3889 D.getContext() != Declarator::AliasDeclContext && 3890 D.getContext() != Declarator::AliasTemplateContext) 3891 checkUnusedDeclAttributes(D); 3892 3893 if (getLangOpts().CPlusPlus) { 3894 // Check that there are no default arguments (C++ only). 3895 CheckExtraCXXDefaultArguments(D); 3896 } 3897 3898 return CreateParsedType(T, TInfo); 3899 } 3900 3901 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 3902 QualType T = Context.getObjCInstanceType(); 3903 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 3904 return CreateParsedType(T, TInfo); 3905 } 3906 3907 3908 //===----------------------------------------------------------------------===// 3909 // Type Attribute Processing 3910 //===----------------------------------------------------------------------===// 3911 3912 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 3913 /// specified type. The attribute contains 1 argument, the id of the address 3914 /// space for the type. 3915 static void HandleAddressSpaceTypeAttribute(QualType &Type, 3916 const AttributeList &Attr, Sema &S){ 3917 3918 // If this type is already address space qualified, reject it. 3919 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 3920 // qualifiers for two or more different address spaces." 3921 if (Type.getAddressSpace()) { 3922 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 3923 Attr.setInvalid(); 3924 return; 3925 } 3926 3927 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 3928 // qualified by an address-space qualifier." 3929 if (Type->isFunctionType()) { 3930 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 3931 Attr.setInvalid(); 3932 return; 3933 } 3934 3935 unsigned ASIdx; 3936 if (Attr.getKind() == AttributeList::AT_AddressSpace) { 3937 // Check the attribute arguments. 3938 if (Attr.getNumArgs() != 1) { 3939 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 3940 << Attr.getName() << 1; 3941 Attr.setInvalid(); 3942 return; 3943 } 3944 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 3945 llvm::APSInt addrSpace(32); 3946 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 3947 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 3948 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 3949 << Attr.getName() << AANT_ArgumentIntegerConstant 3950 << ASArgExpr->getSourceRange(); 3951 Attr.setInvalid(); 3952 return; 3953 } 3954 3955 // Bounds checking. 3956 if (addrSpace.isSigned()) { 3957 if (addrSpace.isNegative()) { 3958 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 3959 << ASArgExpr->getSourceRange(); 3960 Attr.setInvalid(); 3961 return; 3962 } 3963 addrSpace.setIsSigned(false); 3964 } 3965 llvm::APSInt max(addrSpace.getBitWidth()); 3966 max = Qualifiers::MaxAddressSpace; 3967 if (addrSpace > max) { 3968 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 3969 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange(); 3970 Attr.setInvalid(); 3971 return; 3972 } 3973 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 3974 } else { 3975 // The keyword-based type attributes imply which address space to use. 3976 switch (Attr.getKind()) { 3977 case AttributeList::AT_OpenCLGlobalAddressSpace: 3978 ASIdx = LangAS::opencl_global; break; 3979 case AttributeList::AT_OpenCLLocalAddressSpace: 3980 ASIdx = LangAS::opencl_local; break; 3981 case AttributeList::AT_OpenCLConstantAddressSpace: 3982 ASIdx = LangAS::opencl_constant; break; 3983 default: 3984 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace); 3985 ASIdx = 0; break; 3986 } 3987 } 3988 3989 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 3990 } 3991 3992 /// Does this type have a "direct" ownership qualifier? That is, 3993 /// is it written like "__strong id", as opposed to something like 3994 /// "typeof(foo)", where that happens to be strong? 3995 static bool hasDirectOwnershipQualifier(QualType type) { 3996 // Fast path: no qualifier at all. 3997 assert(type.getQualifiers().hasObjCLifetime()); 3998 3999 while (true) { 4000 // __strong id 4001 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 4002 if (attr->getAttrKind() == AttributedType::attr_objc_ownership) 4003 return true; 4004 4005 type = attr->getModifiedType(); 4006 4007 // X *__strong (...) 4008 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 4009 type = paren->getInnerType(); 4010 4011 // That's it for things we want to complain about. In particular, 4012 // we do not want to look through typedefs, typeof(expr), 4013 // typeof(type), or any other way that the type is somehow 4014 // abstracted. 4015 } else { 4016 4017 return false; 4018 } 4019 } 4020 } 4021 4022 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 4023 /// attribute on the specified type. 4024 /// 4025 /// Returns 'true' if the attribute was handled. 4026 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 4027 AttributeList &attr, 4028 QualType &type) { 4029 bool NonObjCPointer = false; 4030 4031 if (!type->isDependentType() && !type->isUndeducedType()) { 4032 if (const PointerType *ptr = type->getAs<PointerType>()) { 4033 QualType pointee = ptr->getPointeeType(); 4034 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 4035 return false; 4036 // It is important not to lose the source info that there was an attribute 4037 // applied to non-objc pointer. We will create an attributed type but 4038 // its type will be the same as the original type. 4039 NonObjCPointer = true; 4040 } else if (!type->isObjCRetainableType()) { 4041 return false; 4042 } 4043 4044 // Don't accept an ownership attribute in the declspec if it would 4045 // just be the return type of a block pointer. 4046 if (state.isProcessingDeclSpec()) { 4047 Declarator &D = state.getDeclarator(); 4048 if (maybeMovePastReturnType(D, D.getNumTypeObjects())) 4049 return false; 4050 } 4051 } 4052 4053 Sema &S = state.getSema(); 4054 SourceLocation AttrLoc = attr.getLoc(); 4055 if (AttrLoc.isMacroID()) 4056 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; 4057 4058 if (!attr.isArgIdent(0)) { 4059 S.Diag(AttrLoc, diag::err_attribute_argument_type) 4060 << attr.getName() << AANT_ArgumentString; 4061 attr.setInvalid(); 4062 return true; 4063 } 4064 4065 // Consume lifetime attributes without further comment outside of 4066 // ARC mode. 4067 if (!S.getLangOpts().ObjCAutoRefCount) 4068 return true; 4069 4070 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 4071 Qualifiers::ObjCLifetime lifetime; 4072 if (II->isStr("none")) 4073 lifetime = Qualifiers::OCL_ExplicitNone; 4074 else if (II->isStr("strong")) 4075 lifetime = Qualifiers::OCL_Strong; 4076 else if (II->isStr("weak")) 4077 lifetime = Qualifiers::OCL_Weak; 4078 else if (II->isStr("autoreleasing")) 4079 lifetime = Qualifiers::OCL_Autoreleasing; 4080 else { 4081 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 4082 << attr.getName() << II; 4083 attr.setInvalid(); 4084 return true; 4085 } 4086 4087 SplitQualType underlyingType = type.split(); 4088 4089 // Check for redundant/conflicting ownership qualifiers. 4090 if (Qualifiers::ObjCLifetime previousLifetime 4091 = type.getQualifiers().getObjCLifetime()) { 4092 // If it's written directly, that's an error. 4093 if (hasDirectOwnershipQualifier(type)) { 4094 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 4095 << type; 4096 return true; 4097 } 4098 4099 // Otherwise, if the qualifiers actually conflict, pull sugar off 4100 // until we reach a type that is directly qualified. 4101 if (previousLifetime != lifetime) { 4102 // This should always terminate: the canonical type is 4103 // qualified, so some bit of sugar must be hiding it. 4104 while (!underlyingType.Quals.hasObjCLifetime()) { 4105 underlyingType = underlyingType.getSingleStepDesugaredType(); 4106 } 4107 underlyingType.Quals.removeObjCLifetime(); 4108 } 4109 } 4110 4111 underlyingType.Quals.addObjCLifetime(lifetime); 4112 4113 if (NonObjCPointer) { 4114 StringRef name = attr.getName()->getName(); 4115 switch (lifetime) { 4116 case Qualifiers::OCL_None: 4117 case Qualifiers::OCL_ExplicitNone: 4118 break; 4119 case Qualifiers::OCL_Strong: name = "__strong"; break; 4120 case Qualifiers::OCL_Weak: name = "__weak"; break; 4121 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 4122 } 4123 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 4124 << TDS_ObjCObjOrBlock << type; 4125 } 4126 4127 QualType origType = type; 4128 if (!NonObjCPointer) 4129 type = S.Context.getQualifiedType(underlyingType); 4130 4131 // If we have a valid source location for the attribute, use an 4132 // AttributedType instead. 4133 if (AttrLoc.isValid()) 4134 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 4135 origType, type); 4136 4137 // Forbid __weak if the runtime doesn't support it. 4138 if (lifetime == Qualifiers::OCL_Weak && 4139 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) { 4140 4141 // Actually, delay this until we know what we're parsing. 4142 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 4143 S.DelayedDiagnostics.add( 4144 sema::DelayedDiagnostic::makeForbiddenType( 4145 S.getSourceManager().getExpansionLoc(AttrLoc), 4146 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0)); 4147 } else { 4148 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime); 4149 } 4150 4151 attr.setInvalid(); 4152 return true; 4153 } 4154 4155 // Forbid __weak for class objects marked as 4156 // objc_arc_weak_reference_unavailable 4157 if (lifetime == Qualifiers::OCL_Weak) { 4158 if (const ObjCObjectPointerType *ObjT = 4159 type->getAs<ObjCObjectPointerType>()) { 4160 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 4161 if (Class->isArcWeakrefUnavailable()) { 4162 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 4163 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 4164 diag::note_class_declared); 4165 } 4166 } 4167 } 4168 } 4169 4170 return true; 4171 } 4172 4173 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 4174 /// attribute on the specified type. Returns true to indicate that 4175 /// the attribute was handled, false to indicate that the type does 4176 /// not permit the attribute. 4177 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 4178 AttributeList &attr, 4179 QualType &type) { 4180 Sema &S = state.getSema(); 4181 4182 // Delay if this isn't some kind of pointer. 4183 if (!type->isPointerType() && 4184 !type->isObjCObjectPointerType() && 4185 !type->isBlockPointerType()) 4186 return false; 4187 4188 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 4189 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 4190 attr.setInvalid(); 4191 return true; 4192 } 4193 4194 // Check the attribute arguments. 4195 if (!attr.isArgIdent(0)) { 4196 S.Diag(attr.getLoc(), diag::err_attribute_argument_type) 4197 << attr.getName() << AANT_ArgumentString; 4198 attr.setInvalid(); 4199 return true; 4200 } 4201 Qualifiers::GC GCAttr; 4202 if (attr.getNumArgs() > 1) { 4203 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) 4204 << attr.getName() << 1; 4205 attr.setInvalid(); 4206 return true; 4207 } 4208 4209 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 4210 if (II->isStr("weak")) 4211 GCAttr = Qualifiers::Weak; 4212 else if (II->isStr("strong")) 4213 GCAttr = Qualifiers::Strong; 4214 else { 4215 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 4216 << attr.getName() << II; 4217 attr.setInvalid(); 4218 return true; 4219 } 4220 4221 QualType origType = type; 4222 type = S.Context.getObjCGCQualType(origType, GCAttr); 4223 4224 // Make an attributed type to preserve the source information. 4225 if (attr.getLoc().isValid()) 4226 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 4227 origType, type); 4228 4229 return true; 4230 } 4231 4232 namespace { 4233 /// A helper class to unwrap a type down to a function for the 4234 /// purposes of applying attributes there. 4235 /// 4236 /// Use: 4237 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 4238 /// if (unwrapped.isFunctionType()) { 4239 /// const FunctionType *fn = unwrapped.get(); 4240 /// // change fn somehow 4241 /// T = unwrapped.wrap(fn); 4242 /// } 4243 struct FunctionTypeUnwrapper { 4244 enum WrapKind { 4245 Desugar, 4246 Parens, 4247 Pointer, 4248 BlockPointer, 4249 Reference, 4250 MemberPointer 4251 }; 4252 4253 QualType Original; 4254 const FunctionType *Fn; 4255 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 4256 4257 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 4258 while (true) { 4259 const Type *Ty = T.getTypePtr(); 4260 if (isa<FunctionType>(Ty)) { 4261 Fn = cast<FunctionType>(Ty); 4262 return; 4263 } else if (isa<ParenType>(Ty)) { 4264 T = cast<ParenType>(Ty)->getInnerType(); 4265 Stack.push_back(Parens); 4266 } else if (isa<PointerType>(Ty)) { 4267 T = cast<PointerType>(Ty)->getPointeeType(); 4268 Stack.push_back(Pointer); 4269 } else if (isa<BlockPointerType>(Ty)) { 4270 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4271 Stack.push_back(BlockPointer); 4272 } else if (isa<MemberPointerType>(Ty)) { 4273 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4274 Stack.push_back(MemberPointer); 4275 } else if (isa<ReferenceType>(Ty)) { 4276 T = cast<ReferenceType>(Ty)->getPointeeType(); 4277 Stack.push_back(Reference); 4278 } else { 4279 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 4280 if (Ty == DTy) { 4281 Fn = nullptr; 4282 return; 4283 } 4284 4285 T = QualType(DTy, 0); 4286 Stack.push_back(Desugar); 4287 } 4288 } 4289 } 4290 4291 bool isFunctionType() const { return (Fn != nullptr); } 4292 const FunctionType *get() const { return Fn; } 4293 4294 QualType wrap(Sema &S, const FunctionType *New) { 4295 // If T wasn't modified from the unwrapped type, do nothing. 4296 if (New == get()) return Original; 4297 4298 Fn = New; 4299 return wrap(S.Context, Original, 0); 4300 } 4301 4302 private: 4303 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 4304 if (I == Stack.size()) 4305 return C.getQualifiedType(Fn, Old.getQualifiers()); 4306 4307 // Build up the inner type, applying the qualifiers from the old 4308 // type to the new type. 4309 SplitQualType SplitOld = Old.split(); 4310 4311 // As a special case, tail-recurse if there are no qualifiers. 4312 if (SplitOld.Quals.empty()) 4313 return wrap(C, SplitOld.Ty, I); 4314 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 4315 } 4316 4317 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 4318 if (I == Stack.size()) return QualType(Fn, 0); 4319 4320 switch (static_cast<WrapKind>(Stack[I++])) { 4321 case Desugar: 4322 // This is the point at which we potentially lose source 4323 // information. 4324 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 4325 4326 case Parens: { 4327 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 4328 return C.getParenType(New); 4329 } 4330 4331 case Pointer: { 4332 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 4333 return C.getPointerType(New); 4334 } 4335 4336 case BlockPointer: { 4337 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 4338 return C.getBlockPointerType(New); 4339 } 4340 4341 case MemberPointer: { 4342 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 4343 QualType New = wrap(C, OldMPT->getPointeeType(), I); 4344 return C.getMemberPointerType(New, OldMPT->getClass()); 4345 } 4346 4347 case Reference: { 4348 const ReferenceType *OldRef = cast<ReferenceType>(Old); 4349 QualType New = wrap(C, OldRef->getPointeeType(), I); 4350 if (isa<LValueReferenceType>(OldRef)) 4351 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 4352 else 4353 return C.getRValueReferenceType(New); 4354 } 4355 } 4356 4357 llvm_unreachable("unknown wrapping kind"); 4358 } 4359 }; 4360 } 4361 4362 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 4363 AttributeList &Attr, 4364 QualType &Type) { 4365 Sema &S = State.getSema(); 4366 4367 AttributeList::Kind Kind = Attr.getKind(); 4368 QualType Desugared = Type; 4369 const AttributedType *AT = dyn_cast<AttributedType>(Type); 4370 while (AT) { 4371 AttributedType::Kind CurAttrKind = AT->getAttrKind(); 4372 4373 // You cannot specify duplicate type attributes, so if the attribute has 4374 // already been applied, flag it. 4375 if (getAttrListKind(CurAttrKind) == Kind) { 4376 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact) 4377 << Attr.getName(); 4378 return true; 4379 } 4380 4381 // You cannot have both __sptr and __uptr on the same type, nor can you 4382 // have __ptr32 and __ptr64. 4383 if ((CurAttrKind == AttributedType::attr_ptr32 && 4384 Kind == AttributeList::AT_Ptr64) || 4385 (CurAttrKind == AttributedType::attr_ptr64 && 4386 Kind == AttributeList::AT_Ptr32)) { 4387 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 4388 << "'__ptr32'" << "'__ptr64'"; 4389 return true; 4390 } else if ((CurAttrKind == AttributedType::attr_sptr && 4391 Kind == AttributeList::AT_UPtr) || 4392 (CurAttrKind == AttributedType::attr_uptr && 4393 Kind == AttributeList::AT_SPtr)) { 4394 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 4395 << "'__sptr'" << "'__uptr'"; 4396 return true; 4397 } 4398 4399 Desugared = AT->getEquivalentType(); 4400 AT = dyn_cast<AttributedType>(Desugared); 4401 } 4402 4403 // Pointer type qualifiers can only operate on pointer types, but not 4404 // pointer-to-member types. 4405 if (!isa<PointerType>(Desugared)) { 4406 S.Diag(Attr.getLoc(), Type->isMemberPointerType() ? 4407 diag::err_attribute_no_member_pointers : 4408 diag::err_attribute_pointers_only) << Attr.getName(); 4409 return true; 4410 } 4411 4412 AttributedType::Kind TAK; 4413 switch (Kind) { 4414 default: llvm_unreachable("Unknown attribute kind"); 4415 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break; 4416 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break; 4417 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break; 4418 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break; 4419 } 4420 4421 Type = S.Context.getAttributedType(TAK, Type, Type); 4422 return false; 4423 } 4424 4425 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) { 4426 assert(!Attr.isInvalid()); 4427 switch (Attr.getKind()) { 4428 default: 4429 llvm_unreachable("not a calling convention attribute"); 4430 case AttributeList::AT_CDecl: 4431 return AttributedType::attr_cdecl; 4432 case AttributeList::AT_FastCall: 4433 return AttributedType::attr_fastcall; 4434 case AttributeList::AT_StdCall: 4435 return AttributedType::attr_stdcall; 4436 case AttributeList::AT_ThisCall: 4437 return AttributedType::attr_thiscall; 4438 case AttributeList::AT_Pascal: 4439 return AttributedType::attr_pascal; 4440 case AttributeList::AT_VectorCall: 4441 return AttributedType::attr_vectorcall; 4442 case AttributeList::AT_Pcs: { 4443 // The attribute may have had a fixit applied where we treated an 4444 // identifier as a string literal. The contents of the string are valid, 4445 // but the form may not be. 4446 StringRef Str; 4447 if (Attr.isArgExpr(0)) 4448 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); 4449 else 4450 Str = Attr.getArgAsIdent(0)->Ident->getName(); 4451 return llvm::StringSwitch<AttributedType::Kind>(Str) 4452 .Case("aapcs", AttributedType::attr_pcs) 4453 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp); 4454 } 4455 case AttributeList::AT_PnaclCall: 4456 return AttributedType::attr_pnaclcall; 4457 case AttributeList::AT_IntelOclBicc: 4458 return AttributedType::attr_inteloclbicc; 4459 case AttributeList::AT_MSABI: 4460 return AttributedType::attr_ms_abi; 4461 case AttributeList::AT_SysVABI: 4462 return AttributedType::attr_sysv_abi; 4463 } 4464 llvm_unreachable("unexpected attribute kind!"); 4465 } 4466 4467 /// Process an individual function attribute. Returns true to 4468 /// indicate that the attribute was handled, false if it wasn't. 4469 static bool handleFunctionTypeAttr(TypeProcessingState &state, 4470 AttributeList &attr, 4471 QualType &type) { 4472 Sema &S = state.getSema(); 4473 4474 FunctionTypeUnwrapper unwrapped(S, type); 4475 4476 if (attr.getKind() == AttributeList::AT_NoReturn) { 4477 if (S.CheckNoReturnAttr(attr)) 4478 return true; 4479 4480 // Delay if this is not a function type. 4481 if (!unwrapped.isFunctionType()) 4482 return false; 4483 4484 // Otherwise we can process right away. 4485 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 4486 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4487 return true; 4488 } 4489 4490 // ns_returns_retained is not always a type attribute, but if we got 4491 // here, we're treating it as one right now. 4492 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) { 4493 assert(S.getLangOpts().ObjCAutoRefCount && 4494 "ns_returns_retained treated as type attribute in non-ARC"); 4495 if (attr.getNumArgs()) return true; 4496 4497 // Delay if this is not a function type. 4498 if (!unwrapped.isFunctionType()) 4499 return false; 4500 4501 FunctionType::ExtInfo EI 4502 = unwrapped.get()->getExtInfo().withProducesResult(true); 4503 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4504 return true; 4505 } 4506 4507 if (attr.getKind() == AttributeList::AT_Regparm) { 4508 unsigned value; 4509 if (S.CheckRegparmAttr(attr, value)) 4510 return true; 4511 4512 // Delay if this is not a function type. 4513 if (!unwrapped.isFunctionType()) 4514 return false; 4515 4516 // Diagnose regparm with fastcall. 4517 const FunctionType *fn = unwrapped.get(); 4518 CallingConv CC = fn->getCallConv(); 4519 if (CC == CC_X86FastCall) { 4520 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4521 << FunctionType::getNameForCallConv(CC) 4522 << "regparm"; 4523 attr.setInvalid(); 4524 return true; 4525 } 4526 4527 FunctionType::ExtInfo EI = 4528 unwrapped.get()->getExtInfo().withRegParm(value); 4529 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4530 return true; 4531 } 4532 4533 // Delay if the type didn't work out to a function. 4534 if (!unwrapped.isFunctionType()) return false; 4535 4536 // Otherwise, a calling convention. 4537 CallingConv CC; 4538 if (S.CheckCallingConvAttr(attr, CC)) 4539 return true; 4540 4541 const FunctionType *fn = unwrapped.get(); 4542 CallingConv CCOld = fn->getCallConv(); 4543 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr); 4544 4545 if (CCOld != CC) { 4546 // Error out on when there's already an attribute on the type 4547 // and the CCs don't match. 4548 const AttributedType *AT = S.getCallingConvAttributedType(type); 4549 if (AT && AT->getAttrKind() != CCAttrKind) { 4550 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4551 << FunctionType::getNameForCallConv(CC) 4552 << FunctionType::getNameForCallConv(CCOld); 4553 attr.setInvalid(); 4554 return true; 4555 } 4556 } 4557 4558 // Diagnose use of callee-cleanup calling convention on variadic functions. 4559 if (!supportsVariadicCall(CC)) { 4560 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); 4561 if (FnP && FnP->isVariadic()) { 4562 unsigned DiagID = diag::err_cconv_varargs; 4563 // stdcall and fastcall are ignored with a warning for GCC and MS 4564 // compatibility. 4565 if (CC == CC_X86StdCall || CC == CC_X86FastCall) 4566 DiagID = diag::warn_cconv_varargs; 4567 4568 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC); 4569 attr.setInvalid(); 4570 return true; 4571 } 4572 } 4573 4574 // Also diagnose fastcall with regparm. 4575 if (CC == CC_X86FastCall && fn->getHasRegParm()) { 4576 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4577 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); 4578 attr.setInvalid(); 4579 return true; 4580 } 4581 4582 // Modify the CC from the wrapped function type, wrap it all back, and then 4583 // wrap the whole thing in an AttributedType as written. The modified type 4584 // might have a different CC if we ignored the attribute. 4585 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 4586 QualType Equivalent = 4587 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4588 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent); 4589 return true; 4590 } 4591 4592 bool Sema::hasExplicitCallingConv(QualType &T) { 4593 QualType R = T.IgnoreParens(); 4594 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) { 4595 if (AT->isCallingConv()) 4596 return true; 4597 R = AT->getModifiedType().IgnoreParens(); 4598 } 4599 return false; 4600 } 4601 4602 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic) { 4603 FunctionTypeUnwrapper Unwrapped(*this, T); 4604 const FunctionType *FT = Unwrapped.get(); 4605 bool IsVariadic = (isa<FunctionProtoType>(FT) && 4606 cast<FunctionProtoType>(FT)->isVariadic()); 4607 4608 // Only adjust types with the default convention. For example, on Windows we 4609 // should adjust a __cdecl type to __thiscall for instance methods, and a 4610 // __thiscall type to __cdecl for static methods. 4611 CallingConv CurCC = FT->getCallConv(); 4612 CallingConv FromCC = 4613 Context.getDefaultCallingConvention(IsVariadic, IsStatic); 4614 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); 4615 if (CurCC != FromCC || FromCC == ToCC) 4616 return; 4617 4618 if (hasExplicitCallingConv(T)) 4619 return; 4620 4621 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); 4622 QualType Wrapped = Unwrapped.wrap(*this, FT); 4623 T = Context.getAdjustedType(T, Wrapped); 4624 } 4625 4626 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 4627 /// and float scalars, although arrays, pointers, and function return values are 4628 /// allowed in conjunction with this construct. Aggregates with this attribute 4629 /// are invalid, even if they are of the same size as a corresponding scalar. 4630 /// The raw attribute should contain precisely 1 argument, the vector size for 4631 /// the variable, measured in bytes. If curType and rawAttr are well formed, 4632 /// this routine will return a new vector type. 4633 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 4634 Sema &S) { 4635 // Check the attribute arguments. 4636 if (Attr.getNumArgs() != 1) { 4637 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 4638 << Attr.getName() << 1; 4639 Attr.setInvalid(); 4640 return; 4641 } 4642 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4643 llvm::APSInt vecSize(32); 4644 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 4645 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 4646 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 4647 << Attr.getName() << AANT_ArgumentIntegerConstant 4648 << sizeExpr->getSourceRange(); 4649 Attr.setInvalid(); 4650 return; 4651 } 4652 // The base type must be integer (not Boolean or enumeration) or float, and 4653 // can't already be a vector. 4654 if (!CurType->isBuiltinType() || CurType->isBooleanType() || 4655 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) { 4656 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 4657 Attr.setInvalid(); 4658 return; 4659 } 4660 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 4661 // vecSize is specified in bytes - convert to bits. 4662 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 4663 4664 // the vector size needs to be an integral multiple of the type size. 4665 if (vectorSize % typeSize) { 4666 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 4667 << sizeExpr->getSourceRange(); 4668 Attr.setInvalid(); 4669 return; 4670 } 4671 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) { 4672 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large) 4673 << sizeExpr->getSourceRange(); 4674 Attr.setInvalid(); 4675 return; 4676 } 4677 if (vectorSize == 0) { 4678 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 4679 << sizeExpr->getSourceRange(); 4680 Attr.setInvalid(); 4681 return; 4682 } 4683 4684 // Success! Instantiate the vector type, the number of elements is > 0, and 4685 // not required to be a power of 2, unlike GCC. 4686 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 4687 VectorType::GenericVector); 4688 } 4689 4690 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 4691 /// a type. 4692 static void HandleExtVectorTypeAttr(QualType &CurType, 4693 const AttributeList &Attr, 4694 Sema &S) { 4695 // check the attribute arguments. 4696 if (Attr.getNumArgs() != 1) { 4697 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 4698 << Attr.getName() << 1; 4699 return; 4700 } 4701 4702 Expr *sizeExpr; 4703 4704 // Special case where the argument is a template id. 4705 if (Attr.isArgIdent(0)) { 4706 CXXScopeSpec SS; 4707 SourceLocation TemplateKWLoc; 4708 UnqualifiedId id; 4709 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); 4710 4711 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 4712 id, false, false); 4713 if (Size.isInvalid()) 4714 return; 4715 4716 sizeExpr = Size.get(); 4717 } else { 4718 sizeExpr = Attr.getArgAsExpr(0); 4719 } 4720 4721 // Create the vector type. 4722 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 4723 if (!T.isNull()) 4724 CurType = T; 4725 } 4726 4727 static bool isPermittedNeonBaseType(QualType &Ty, 4728 VectorType::VectorKind VecKind, Sema &S) { 4729 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 4730 if (!BTy) 4731 return false; 4732 4733 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 4734 4735 // Signed poly is mathematically wrong, but has been baked into some ABIs by 4736 // now. 4737 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || 4738 Triple.getArch() == llvm::Triple::aarch64_be; 4739 if (VecKind == VectorType::NeonPolyVector) { 4740 if (IsPolyUnsigned) { 4741 // AArch64 polynomial vectors are unsigned and support poly64. 4742 return BTy->getKind() == BuiltinType::UChar || 4743 BTy->getKind() == BuiltinType::UShort || 4744 BTy->getKind() == BuiltinType::ULong || 4745 BTy->getKind() == BuiltinType::ULongLong; 4746 } else { 4747 // AArch32 polynomial vector are signed. 4748 return BTy->getKind() == BuiltinType::SChar || 4749 BTy->getKind() == BuiltinType::Short; 4750 } 4751 } 4752 4753 // Non-polynomial vector types: the usual suspects are allowed, as well as 4754 // float64_t on AArch64. 4755 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 || 4756 Triple.getArch() == llvm::Triple::aarch64_be; 4757 4758 if (Is64Bit && BTy->getKind() == BuiltinType::Double) 4759 return true; 4760 4761 return BTy->getKind() == BuiltinType::SChar || 4762 BTy->getKind() == BuiltinType::UChar || 4763 BTy->getKind() == BuiltinType::Short || 4764 BTy->getKind() == BuiltinType::UShort || 4765 BTy->getKind() == BuiltinType::Int || 4766 BTy->getKind() == BuiltinType::UInt || 4767 BTy->getKind() == BuiltinType::Long || 4768 BTy->getKind() == BuiltinType::ULong || 4769 BTy->getKind() == BuiltinType::LongLong || 4770 BTy->getKind() == BuiltinType::ULongLong || 4771 BTy->getKind() == BuiltinType::Float || 4772 BTy->getKind() == BuiltinType::Half; 4773 } 4774 4775 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 4776 /// "neon_polyvector_type" attributes are used to create vector types that 4777 /// are mangled according to ARM's ABI. Otherwise, these types are identical 4778 /// to those created with the "vector_size" attribute. Unlike "vector_size" 4779 /// the argument to these Neon attributes is the number of vector elements, 4780 /// not the vector size in bytes. The vector width and element type must 4781 /// match one of the standard Neon vector types. 4782 static void HandleNeonVectorTypeAttr(QualType& CurType, 4783 const AttributeList &Attr, Sema &S, 4784 VectorType::VectorKind VecKind) { 4785 // Target must have NEON 4786 if (!S.Context.getTargetInfo().hasFeature("neon")) { 4787 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName(); 4788 Attr.setInvalid(); 4789 return; 4790 } 4791 // Check the attribute arguments. 4792 if (Attr.getNumArgs() != 1) { 4793 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 4794 << Attr.getName() << 1; 4795 Attr.setInvalid(); 4796 return; 4797 } 4798 // The number of elements must be an ICE. 4799 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4800 llvm::APSInt numEltsInt(32); 4801 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 4802 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 4803 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 4804 << Attr.getName() << AANT_ArgumentIntegerConstant 4805 << numEltsExpr->getSourceRange(); 4806 Attr.setInvalid(); 4807 return; 4808 } 4809 // Only certain element types are supported for Neon vectors. 4810 if (!isPermittedNeonBaseType(CurType, VecKind, S)) { 4811 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 4812 Attr.setInvalid(); 4813 return; 4814 } 4815 4816 // The total size of the vector must be 64 or 128 bits. 4817 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 4818 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 4819 unsigned vecSize = typeSize * numElts; 4820 if (vecSize != 64 && vecSize != 128) { 4821 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 4822 Attr.setInvalid(); 4823 return; 4824 } 4825 4826 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 4827 } 4828 4829 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 4830 TypeAttrLocation TAL, AttributeList *attrs) { 4831 // Scan through and apply attributes to this type where it makes sense. Some 4832 // attributes (such as __address_space__, __vector_size__, etc) apply to the 4833 // type, but others can be present in the type specifiers even though they 4834 // apply to the decl. Here we apply type attributes and ignore the rest. 4835 4836 AttributeList *next; 4837 do { 4838 AttributeList &attr = *attrs; 4839 next = attr.getNext(); 4840 4841 // Skip attributes that were marked to be invalid. 4842 if (attr.isInvalid()) 4843 continue; 4844 4845 if (attr.isCXX11Attribute()) { 4846 // [[gnu::...]] attributes are treated as declaration attributes, so may 4847 // not appertain to a DeclaratorChunk, even if we handle them as type 4848 // attributes. 4849 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) { 4850 if (TAL == TAL_DeclChunk) { 4851 state.getSema().Diag(attr.getLoc(), 4852 diag::warn_cxx11_gnu_attribute_on_type) 4853 << attr.getName(); 4854 continue; 4855 } 4856 } else if (TAL != TAL_DeclChunk) { 4857 // Otherwise, only consider type processing for a C++11 attribute if 4858 // it's actually been applied to a type. 4859 continue; 4860 } 4861 } 4862 4863 // If this is an attribute we can handle, do so now, 4864 // otherwise, add it to the FnAttrs list for rechaining. 4865 switch (attr.getKind()) { 4866 default: 4867 // A C++11 attribute on a declarator chunk must appertain to a type. 4868 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { 4869 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 4870 << attr.getName(); 4871 attr.setUsedAsTypeAttr(); 4872 } 4873 break; 4874 4875 case AttributeList::UnknownAttribute: 4876 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 4877 state.getSema().Diag(attr.getLoc(), 4878 diag::warn_unknown_attribute_ignored) 4879 << attr.getName(); 4880 break; 4881 4882 case AttributeList::IgnoredAttribute: 4883 break; 4884 4885 case AttributeList::AT_MayAlias: 4886 // FIXME: This attribute needs to actually be handled, but if we ignore 4887 // it it breaks large amounts of Linux software. 4888 attr.setUsedAsTypeAttr(); 4889 break; 4890 case AttributeList::AT_OpenCLPrivateAddressSpace: 4891 case AttributeList::AT_OpenCLGlobalAddressSpace: 4892 case AttributeList::AT_OpenCLLocalAddressSpace: 4893 case AttributeList::AT_OpenCLConstantAddressSpace: 4894 case AttributeList::AT_AddressSpace: 4895 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 4896 attr.setUsedAsTypeAttr(); 4897 break; 4898 OBJC_POINTER_TYPE_ATTRS_CASELIST: 4899 if (!handleObjCPointerTypeAttr(state, attr, type)) 4900 distributeObjCPointerTypeAttr(state, attr, type); 4901 attr.setUsedAsTypeAttr(); 4902 break; 4903 case AttributeList::AT_VectorSize: 4904 HandleVectorSizeAttr(type, attr, state.getSema()); 4905 attr.setUsedAsTypeAttr(); 4906 break; 4907 case AttributeList::AT_ExtVectorType: 4908 HandleExtVectorTypeAttr(type, attr, state.getSema()); 4909 attr.setUsedAsTypeAttr(); 4910 break; 4911 case AttributeList::AT_NeonVectorType: 4912 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 4913 VectorType::NeonVector); 4914 attr.setUsedAsTypeAttr(); 4915 break; 4916 case AttributeList::AT_NeonPolyVectorType: 4917 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 4918 VectorType::NeonPolyVector); 4919 attr.setUsedAsTypeAttr(); 4920 break; 4921 case AttributeList::AT_OpenCLImageAccess: 4922 // FIXME: there should be some type checking happening here, I would 4923 // imagine, but the original handler's checking was entirely superfluous. 4924 attr.setUsedAsTypeAttr(); 4925 break; 4926 4927 MS_TYPE_ATTRS_CASELIST: 4928 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 4929 attr.setUsedAsTypeAttr(); 4930 break; 4931 4932 case AttributeList::AT_NSReturnsRetained: 4933 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 4934 break; 4935 // fallthrough into the function attrs 4936 4937 FUNCTION_TYPE_ATTRS_CASELIST: 4938 attr.setUsedAsTypeAttr(); 4939 4940 // Never process function type attributes as part of the 4941 // declaration-specifiers. 4942 if (TAL == TAL_DeclSpec) 4943 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 4944 4945 // Otherwise, handle the possible delays. 4946 else if (!handleFunctionTypeAttr(state, attr, type)) 4947 distributeFunctionTypeAttr(state, attr, type); 4948 break; 4949 } 4950 } while ((attrs = next)); 4951 } 4952 4953 /// \brief Ensure that the type of the given expression is complete. 4954 /// 4955 /// This routine checks whether the expression \p E has a complete type. If the 4956 /// expression refers to an instantiable construct, that instantiation is 4957 /// performed as needed to complete its type. Furthermore 4958 /// Sema::RequireCompleteType is called for the expression's type (or in the 4959 /// case of a reference type, the referred-to type). 4960 /// 4961 /// \param E The expression whose type is required to be complete. 4962 /// \param Diagnoser The object that will emit a diagnostic if the type is 4963 /// incomplete. 4964 /// 4965 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 4966 /// otherwise. 4967 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){ 4968 QualType T = E->getType(); 4969 4970 // Fast path the case where the type is already complete. 4971 if (!T->isIncompleteType()) 4972 // FIXME: The definition might not be visible. 4973 return false; 4974 4975 // Incomplete array types may be completed by the initializer attached to 4976 // their definitions. For static data members of class templates and for 4977 // variable templates, we need to instantiate the definition to get this 4978 // initializer and complete the type. 4979 if (T->isIncompleteArrayType()) { 4980 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4981 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 4982 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { 4983 SourceLocation PointOfInstantiation = E->getExprLoc(); 4984 4985 if (MemberSpecializationInfo *MSInfo = 4986 Var->getMemberSpecializationInfo()) { 4987 // If we don't already have a point of instantiation, this is it. 4988 if (MSInfo->getPointOfInstantiation().isInvalid()) { 4989 MSInfo->setPointOfInstantiation(PointOfInstantiation); 4990 4991 // This is a modification of an existing AST node. Notify 4992 // listeners. 4993 if (ASTMutationListener *L = getASTMutationListener()) 4994 L->StaticDataMemberInstantiated(Var); 4995 } 4996 } else { 4997 VarTemplateSpecializationDecl *VarSpec = 4998 cast<VarTemplateSpecializationDecl>(Var); 4999 if (VarSpec->getPointOfInstantiation().isInvalid()) 5000 VarSpec->setPointOfInstantiation(PointOfInstantiation); 5001 } 5002 5003 InstantiateVariableDefinition(PointOfInstantiation, Var); 5004 5005 // Update the type to the newly instantiated definition's type both 5006 // here and within the expression. 5007 if (VarDecl *Def = Var->getDefinition()) { 5008 DRE->setDecl(Def); 5009 T = Def->getType(); 5010 DRE->setType(T); 5011 E->setType(T); 5012 } 5013 5014 // We still go on to try to complete the type independently, as it 5015 // may also require instantiations or diagnostics if it remains 5016 // incomplete. 5017 } 5018 } 5019 } 5020 } 5021 5022 // FIXME: Are there other cases which require instantiating something other 5023 // than the type to complete the type of an expression? 5024 5025 // Look through reference types and complete the referred type. 5026 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 5027 T = Ref->getPointeeType(); 5028 5029 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 5030 } 5031 5032 namespace { 5033 struct TypeDiagnoserDiag : Sema::TypeDiagnoser { 5034 unsigned DiagID; 5035 5036 TypeDiagnoserDiag(unsigned DiagID) 5037 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {} 5038 5039 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5040 if (Suppressed) return; 5041 S.Diag(Loc, DiagID) << T; 5042 } 5043 }; 5044 } 5045 5046 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 5047 TypeDiagnoserDiag Diagnoser(DiagID); 5048 return RequireCompleteExprType(E, Diagnoser); 5049 } 5050 5051 /// @brief Ensure that the type T is a complete type. 5052 /// 5053 /// This routine checks whether the type @p T is complete in any 5054 /// context where a complete type is required. If @p T is a complete 5055 /// type, returns false. If @p T is a class template specialization, 5056 /// this routine then attempts to perform class template 5057 /// instantiation. If instantiation fails, or if @p T is incomplete 5058 /// and cannot be completed, issues the diagnostic @p diag (giving it 5059 /// the type @p T) and returns true. 5060 /// 5061 /// @param Loc The location in the source that the incomplete type 5062 /// diagnostic should refer to. 5063 /// 5064 /// @param T The type that this routine is examining for completeness. 5065 /// 5066 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 5067 /// @c false otherwise. 5068 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 5069 TypeDiagnoser &Diagnoser) { 5070 if (RequireCompleteTypeImpl(Loc, T, Diagnoser)) 5071 return true; 5072 if (const TagType *Tag = T->getAs<TagType>()) { 5073 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 5074 Tag->getDecl()->setCompleteDefinitionRequired(); 5075 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 5076 } 5077 } 5078 return false; 5079 } 5080 5081 /// \brief Determine whether there is any declaration of \p D that was ever a 5082 /// definition (perhaps before module merging) and is currently visible. 5083 /// \param D The definition of the entity. 5084 /// \param Suggested Filled in with the declaration that should be made visible 5085 /// in order to provide a definition of this entity. 5086 static bool hasVisibleDefinition(Sema &S, NamedDecl *D, NamedDecl **Suggested) { 5087 // Easy case: if we don't have modules, all declarations are visible. 5088 if (!S.getLangOpts().Modules) 5089 return true; 5090 5091 // If this definition was instantiated from a template, map back to the 5092 // pattern from which it was instantiated. 5093 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 5094 if (auto *Pattern = RD->getTemplateInstantiationPattern()) 5095 RD = Pattern; 5096 D = RD->getDefinition(); 5097 } else if (auto *ED = dyn_cast<EnumDecl>(D)) { 5098 while (auto *NewED = ED->getInstantiatedFromMemberEnum()) 5099 ED = NewED; 5100 if (ED->isFixed()) { 5101 // If the enum has a fixed underlying type, any declaration of it will do. 5102 *Suggested = nullptr; 5103 for (auto *Redecl : ED->redecls()) { 5104 if (LookupResult::isVisible(S, Redecl)) 5105 return true; 5106 if (Redecl->isThisDeclarationADefinition() || 5107 (Redecl->isCanonicalDecl() && !*Suggested)) 5108 *Suggested = Redecl; 5109 } 5110 return false; 5111 } 5112 D = ED->getDefinition(); 5113 } 5114 assert(D && "missing definition for pattern of instantiated definition"); 5115 5116 // FIXME: If we merged any other decl into D, and that declaration is visible, 5117 // then we should consider a definition to be visible. 5118 *Suggested = D; 5119 return LookupResult::isVisible(S, D); 5120 } 5121 5122 /// Locks in the inheritance model for the given class and all of its bases. 5123 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { 5124 RD = RD->getMostRecentDecl(); 5125 if (!RD->hasAttr<MSInheritanceAttr>()) { 5126 MSInheritanceAttr::Spelling IM; 5127 5128 switch (S.MSPointerToMemberRepresentationMethod) { 5129 case LangOptions::PPTMK_BestCase: 5130 IM = RD->calculateInheritanceModel(); 5131 break; 5132 case LangOptions::PPTMK_FullGeneralitySingleInheritance: 5133 IM = MSInheritanceAttr::Keyword_single_inheritance; 5134 break; 5135 case LangOptions::PPTMK_FullGeneralityMultipleInheritance: 5136 IM = MSInheritanceAttr::Keyword_multiple_inheritance; 5137 break; 5138 case LangOptions::PPTMK_FullGeneralityVirtualInheritance: 5139 IM = MSInheritanceAttr::Keyword_unspecified_inheritance; 5140 break; 5141 } 5142 5143 RD->addAttr(MSInheritanceAttr::CreateImplicit( 5144 S.getASTContext(), IM, 5145 /*BestCase=*/S.MSPointerToMemberRepresentationMethod == 5146 LangOptions::PPTMK_BestCase, 5147 S.ImplicitMSInheritanceAttrLoc.isValid() 5148 ? S.ImplicitMSInheritanceAttrLoc 5149 : RD->getSourceRange())); 5150 } 5151 } 5152 5153 /// \brief The implementation of RequireCompleteType 5154 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 5155 TypeDiagnoser &Diagnoser) { 5156 // FIXME: Add this assertion to make sure we always get instantiation points. 5157 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 5158 // FIXME: Add this assertion to help us flush out problems with 5159 // checking for dependent types and type-dependent expressions. 5160 // 5161 // assert(!T->isDependentType() && 5162 // "Can't ask whether a dependent type is complete"); 5163 5164 // If we have a complete type, we're done. 5165 NamedDecl *Def = nullptr; 5166 if (!T->isIncompleteType(&Def)) { 5167 // If we know about the definition but it is not visible, complain. 5168 NamedDecl *SuggestedDef = nullptr; 5169 if (!Diagnoser.Suppressed && Def && 5170 !hasVisibleDefinition(*this, Def, &SuggestedDef)) { 5171 // Suppress this error outside of a SFINAE context if we've already 5172 // emitted the error once for this type. There's no usefulness in 5173 // repeating the diagnostic. 5174 // FIXME: Add a Fix-It that imports the corresponding module or includes 5175 // the header. 5176 Module *Owner = SuggestedDef->getOwningModule(); 5177 Diag(Loc, diag::err_module_private_definition) 5178 << T << Owner->getFullModuleName(); 5179 Diag(SuggestedDef->getLocation(), diag::note_previous_definition); 5180 5181 // Try to recover by implicitly importing this module. 5182 createImplicitModuleImportForErrorRecovery(Loc, Owner); 5183 } 5184 5185 // We lock in the inheritance model once somebody has asked us to ensure 5186 // that a pointer-to-member type is complete. 5187 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5188 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { 5189 if (!MPTy->getClass()->isDependentType()) { 5190 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), 0); 5191 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); 5192 } 5193 } 5194 } 5195 5196 return false; 5197 } 5198 5199 const TagType *Tag = T->getAs<TagType>(); 5200 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>(); 5201 5202 // If there's an unimported definition of this type in a module (for 5203 // instance, because we forward declared it, then imported the definition), 5204 // import that definition now. 5205 // 5206 // FIXME: What about other cases where an import extends a redeclaration 5207 // chain for a declaration that can be accessed through a mechanism other 5208 // than name lookup (eg, referenced in a template, or a variable whose type 5209 // could be completed by the module)? 5210 if (Tag || IFace) { 5211 NamedDecl *D = 5212 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl(); 5213 5214 // Avoid diagnosing invalid decls as incomplete. 5215 if (D->isInvalidDecl()) 5216 return true; 5217 5218 // Give the external AST source a chance to complete the type. 5219 if (auto *Source = Context.getExternalSource()) { 5220 if (Tag) 5221 Source->CompleteType(Tag->getDecl()); 5222 else 5223 Source->CompleteType(IFace->getDecl()); 5224 5225 // If the external source completed the type, go through the motions 5226 // again to ensure we're allowed to use the completed type. 5227 if (!T->isIncompleteType()) 5228 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 5229 } 5230 } 5231 5232 // If we have a class template specialization or a class member of a 5233 // class template specialization, or an array with known size of such, 5234 // try to instantiate it. 5235 QualType MaybeTemplate = T; 5236 while (const ConstantArrayType *Array 5237 = Context.getAsConstantArrayType(MaybeTemplate)) 5238 MaybeTemplate = Array->getElementType(); 5239 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 5240 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 5241 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 5242 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) 5243 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec, 5244 TSK_ImplicitInstantiation, 5245 /*Complain=*/!Diagnoser.Suppressed); 5246 } else if (CXXRecordDecl *Rec 5247 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 5248 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); 5249 if (!Rec->isBeingDefined() && Pattern) { 5250 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); 5251 assert(MSI && "Missing member specialization information?"); 5252 // This record was instantiated from a class within a template. 5253 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 5254 return InstantiateClass(Loc, Rec, Pattern, 5255 getTemplateInstantiationArgs(Rec), 5256 TSK_ImplicitInstantiation, 5257 /*Complain=*/!Diagnoser.Suppressed); 5258 } 5259 } 5260 } 5261 5262 if (Diagnoser.Suppressed) 5263 return true; 5264 5265 // We have an incomplete type. Produce a diagnostic. 5266 if (Ident___float128 && 5267 T == Context.getTypeDeclType(Context.getFloat128StubType())) { 5268 Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128); 5269 return true; 5270 } 5271 5272 Diagnoser.diagnose(*this, Loc, T); 5273 5274 // If the type was a forward declaration of a class/struct/union 5275 // type, produce a note. 5276 if (Tag && !Tag->getDecl()->isInvalidDecl()) 5277 Diag(Tag->getDecl()->getLocation(), 5278 Tag->isBeingDefined() ? diag::note_type_being_defined 5279 : diag::note_forward_declaration) 5280 << QualType(Tag, 0); 5281 5282 // If the Objective-C class was a forward declaration, produce a note. 5283 if (IFace && !IFace->getDecl()->isInvalidDecl()) 5284 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); 5285 5286 // If we have external information that we can use to suggest a fix, 5287 // produce a note. 5288 if (ExternalSource) 5289 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); 5290 5291 return true; 5292 } 5293 5294 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 5295 unsigned DiagID) { 5296 TypeDiagnoserDiag Diagnoser(DiagID); 5297 return RequireCompleteType(Loc, T, Diagnoser); 5298 } 5299 5300 /// \brief Get diagnostic %select index for tag kind for 5301 /// literal type diagnostic message. 5302 /// WARNING: Indexes apply to particular diagnostics only! 5303 /// 5304 /// \returns diagnostic %select index. 5305 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 5306 switch (Tag) { 5307 case TTK_Struct: return 0; 5308 case TTK_Interface: return 1; 5309 case TTK_Class: return 2; 5310 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 5311 } 5312 } 5313 5314 /// @brief Ensure that the type T is a literal type. 5315 /// 5316 /// This routine checks whether the type @p T is a literal type. If @p T is an 5317 /// incomplete type, an attempt is made to complete it. If @p T is a literal 5318 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 5319 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 5320 /// it the type @p T), along with notes explaining why the type is not a 5321 /// literal type, and returns true. 5322 /// 5323 /// @param Loc The location in the source that the non-literal type 5324 /// diagnostic should refer to. 5325 /// 5326 /// @param T The type that this routine is examining for literalness. 5327 /// 5328 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 5329 /// 5330 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 5331 /// @c false otherwise. 5332 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 5333 TypeDiagnoser &Diagnoser) { 5334 assert(!T->isDependentType() && "type should not be dependent"); 5335 5336 QualType ElemType = Context.getBaseElementType(T); 5337 RequireCompleteType(Loc, ElemType, 0); 5338 5339 if (T->isLiteralType(Context)) 5340 return false; 5341 5342 if (Diagnoser.Suppressed) 5343 return true; 5344 5345 Diagnoser.diagnose(*this, Loc, T); 5346 5347 if (T->isVariableArrayType()) 5348 return true; 5349 5350 const RecordType *RT = ElemType->getAs<RecordType>(); 5351 if (!RT) 5352 return true; 5353 5354 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 5355 5356 // A partially-defined class type can't be a literal type, because a literal 5357 // class type must have a trivial destructor (which can't be checked until 5358 // the class definition is complete). 5359 if (!RD->isCompleteDefinition()) { 5360 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T); 5361 return true; 5362 } 5363 5364 // If the class has virtual base classes, then it's not an aggregate, and 5365 // cannot have any constexpr constructors or a trivial default constructor, 5366 // so is non-literal. This is better to diagnose than the resulting absence 5367 // of constexpr constructors. 5368 if (RD->getNumVBases()) { 5369 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 5370 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 5371 for (const auto &I : RD->vbases()) 5372 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here) 5373 << I.getSourceRange(); 5374 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 5375 !RD->hasTrivialDefaultConstructor()) { 5376 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 5377 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 5378 for (const auto &I : RD->bases()) { 5379 if (!I.getType()->isLiteralType(Context)) { 5380 Diag(I.getLocStart(), 5381 diag::note_non_literal_base_class) 5382 << RD << I.getType() << I.getSourceRange(); 5383 return true; 5384 } 5385 } 5386 for (const auto *I : RD->fields()) { 5387 if (!I->getType()->isLiteralType(Context) || 5388 I->getType().isVolatileQualified()) { 5389 Diag(I->getLocation(), diag::note_non_literal_field) 5390 << RD << I << I->getType() 5391 << I->getType().isVolatileQualified(); 5392 return true; 5393 } 5394 } 5395 } else if (!RD->hasTrivialDestructor()) { 5396 // All fields and bases are of literal types, so have trivial destructors. 5397 // If this class's destructor is non-trivial it must be user-declared. 5398 CXXDestructorDecl *Dtor = RD->getDestructor(); 5399 assert(Dtor && "class has literal fields and bases but no dtor?"); 5400 if (!Dtor) 5401 return true; 5402 5403 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 5404 diag::note_non_literal_user_provided_dtor : 5405 diag::note_non_literal_nontrivial_dtor) << RD; 5406 if (!Dtor->isUserProvided()) 5407 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true); 5408 } 5409 5410 return true; 5411 } 5412 5413 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 5414 TypeDiagnoserDiag Diagnoser(DiagID); 5415 return RequireLiteralType(Loc, T, Diagnoser); 5416 } 5417 5418 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 5419 /// and qualified by the nested-name-specifier contained in SS. 5420 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 5421 const CXXScopeSpec &SS, QualType T) { 5422 if (T.isNull()) 5423 return T; 5424 NestedNameSpecifier *NNS; 5425 if (SS.isValid()) 5426 NNS = SS.getScopeRep(); 5427 else { 5428 if (Keyword == ETK_None) 5429 return T; 5430 NNS = nullptr; 5431 } 5432 return Context.getElaboratedType(Keyword, NNS, T); 5433 } 5434 5435 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 5436 ExprResult ER = CheckPlaceholderExpr(E); 5437 if (ER.isInvalid()) return QualType(); 5438 E = ER.get(); 5439 5440 if (!E->isTypeDependent()) { 5441 QualType T = E->getType(); 5442 if (const TagType *TT = T->getAs<TagType>()) 5443 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 5444 } 5445 return Context.getTypeOfExprType(E); 5446 } 5447 5448 /// getDecltypeForExpr - Given an expr, will return the decltype for 5449 /// that expression, according to the rules in C++11 5450 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 5451 static QualType getDecltypeForExpr(Sema &S, Expr *E) { 5452 if (E->isTypeDependent()) 5453 return S.Context.DependentTy; 5454 5455 // C++11 [dcl.type.simple]p4: 5456 // The type denoted by decltype(e) is defined as follows: 5457 // 5458 // - if e is an unparenthesized id-expression or an unparenthesized class 5459 // member access (5.2.5), decltype(e) is the type of the entity named 5460 // by e. If there is no such entity, or if e names a set of overloaded 5461 // functions, the program is ill-formed; 5462 // 5463 // We apply the same rules for Objective-C ivar and property references. 5464 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 5465 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 5466 return VD->getType(); 5467 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 5468 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 5469 return FD->getType(); 5470 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { 5471 return IR->getDecl()->getType(); 5472 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { 5473 if (PR->isExplicitProperty()) 5474 return PR->getExplicitProperty()->getType(); 5475 } 5476 5477 // C++11 [expr.lambda.prim]p18: 5478 // Every occurrence of decltype((x)) where x is a possibly 5479 // parenthesized id-expression that names an entity of automatic 5480 // storage duration is treated as if x were transformed into an 5481 // access to a corresponding data member of the closure type that 5482 // would have been declared if x were an odr-use of the denoted 5483 // entity. 5484 using namespace sema; 5485 if (S.getCurLambda()) { 5486 if (isa<ParenExpr>(E)) { 5487 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 5488 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 5489 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 5490 if (!T.isNull()) 5491 return S.Context.getLValueReferenceType(T); 5492 } 5493 } 5494 } 5495 } 5496 5497 5498 // C++11 [dcl.type.simple]p4: 5499 // [...] 5500 QualType T = E->getType(); 5501 switch (E->getValueKind()) { 5502 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 5503 // type of e; 5504 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 5505 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 5506 // type of e; 5507 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 5508 // - otherwise, decltype(e) is the type of e. 5509 case VK_RValue: break; 5510 } 5511 5512 return T; 5513 } 5514 5515 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) { 5516 ExprResult ER = CheckPlaceholderExpr(E); 5517 if (ER.isInvalid()) return QualType(); 5518 E = ER.get(); 5519 5520 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 5521 } 5522 5523 QualType Sema::BuildUnaryTransformType(QualType BaseType, 5524 UnaryTransformType::UTTKind UKind, 5525 SourceLocation Loc) { 5526 switch (UKind) { 5527 case UnaryTransformType::EnumUnderlyingType: 5528 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 5529 Diag(Loc, diag::err_only_enums_have_underlying_types); 5530 return QualType(); 5531 } else { 5532 QualType Underlying = BaseType; 5533 if (!BaseType->isDependentType()) { 5534 // The enum could be incomplete if we're parsing its definition or 5535 // recovering from an error. 5536 NamedDecl *FwdDecl = nullptr; 5537 if (BaseType->isIncompleteType(&FwdDecl)) { 5538 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; 5539 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; 5540 return QualType(); 5541 } 5542 5543 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 5544 assert(ED && "EnumType has no EnumDecl"); 5545 5546 DiagnoseUseOfDecl(ED, Loc); 5547 5548 Underlying = ED->getIntegerType(); 5549 assert(!Underlying.isNull()); 5550 } 5551 return Context.getUnaryTransformType(BaseType, Underlying, 5552 UnaryTransformType::EnumUnderlyingType); 5553 } 5554 } 5555 llvm_unreachable("unknown unary transform type"); 5556 } 5557 5558 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 5559 if (!T->isDependentType()) { 5560 // FIXME: It isn't entirely clear whether incomplete atomic types 5561 // are allowed or not; for simplicity, ban them for the moment. 5562 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 5563 return QualType(); 5564 5565 int DisallowedKind = -1; 5566 if (T->isArrayType()) 5567 DisallowedKind = 1; 5568 else if (T->isFunctionType()) 5569 DisallowedKind = 2; 5570 else if (T->isReferenceType()) 5571 DisallowedKind = 3; 5572 else if (T->isAtomicType()) 5573 DisallowedKind = 4; 5574 else if (T.hasQualifiers()) 5575 DisallowedKind = 5; 5576 else if (!T.isTriviallyCopyableType(Context)) 5577 // Some other non-trivially-copyable type (probably a C++ class) 5578 DisallowedKind = 6; 5579 5580 if (DisallowedKind != -1) { 5581 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 5582 return QualType(); 5583 } 5584 5585 // FIXME: Do we need any handling for ARC here? 5586 } 5587 5588 // Build the pointer type. 5589 return Context.getAtomicType(T); 5590 } 5591