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