SemaType.cpp revision edd2cb381e9c7a45354677c7fb6a93ae2a0080b7
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 // If template instantiation fails or the type is just incomplete, we have to 1732 // add an extra slot to the member pointer. Yes, this does cause problems 1733 // when passing pointers between TUs that disagree about the size. 1734 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1735 CXXRecordDecl *RD = Class->getAsCXXRecordDecl(); 1736 if (!RD->hasAttr<MSInheritanceAttr>()) { 1737 // Lock in the inheritance model on the first use of a member pointer. 1738 // Otherwise we may disagree about the size at different points in the TU. 1739 // FIXME: MSVC picks a model on the first use that needs to know the size, 1740 // rather than on the first mention of the type, e.g. typedefs. 1741 if (RequireCompleteType(Loc, Class, 0) && !RD->isBeingDefined()) { 1742 // We know it doesn't have an attribute and it's incomplete, so use the 1743 // unspecified inheritance model. If we're in the record body, we can 1744 // figure out the inheritance model. 1745 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(), 1746 E = RD->redecls_end(); I != E; ++I) { 1747 I->addAttr(::new (Context) UnspecifiedInheritanceAttr( 1748 RD->getSourceRange(), Context)); 1749 } 1750 } 1751 } 1752 } 1753 1754 return Context.getMemberPointerType(T, Class.getTypePtr()); 1755} 1756 1757/// \brief Build a block pointer type. 1758/// 1759/// \param T The type to which we'll be building a block pointer. 1760/// 1761/// \param Loc The source location, used for diagnostics. 1762/// 1763/// \param Entity The name of the entity that involves the block pointer 1764/// type, if known. 1765/// 1766/// \returns A suitable block pointer type, if there are no 1767/// errors. Otherwise, returns a NULL type. 1768QualType Sema::BuildBlockPointerType(QualType T, 1769 SourceLocation Loc, 1770 DeclarationName Entity) { 1771 if (!T->isFunctionType()) { 1772 Diag(Loc, diag::err_nonfunction_block_type); 1773 return QualType(); 1774 } 1775 1776 return Context.getBlockPointerType(T); 1777} 1778 1779QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 1780 QualType QT = Ty.get(); 1781 if (QT.isNull()) { 1782 if (TInfo) *TInfo = 0; 1783 return QualType(); 1784 } 1785 1786 TypeSourceInfo *DI = 0; 1787 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 1788 QT = LIT->getType(); 1789 DI = LIT->getTypeSourceInfo(); 1790 } 1791 1792 if (TInfo) *TInfo = DI; 1793 return QT; 1794} 1795 1796static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 1797 Qualifiers::ObjCLifetime ownership, 1798 unsigned chunkIndex); 1799 1800/// Given that this is the declaration of a parameter under ARC, 1801/// attempt to infer attributes and such for pointer-to-whatever 1802/// types. 1803static void inferARCWriteback(TypeProcessingState &state, 1804 QualType &declSpecType) { 1805 Sema &S = state.getSema(); 1806 Declarator &declarator = state.getDeclarator(); 1807 1808 // TODO: should we care about decl qualifiers? 1809 1810 // Check whether the declarator has the expected form. We walk 1811 // from the inside out in order to make the block logic work. 1812 unsigned outermostPointerIndex = 0; 1813 bool isBlockPointer = false; 1814 unsigned numPointers = 0; 1815 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 1816 unsigned chunkIndex = i; 1817 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); 1818 switch (chunk.Kind) { 1819 case DeclaratorChunk::Paren: 1820 // Ignore parens. 1821 break; 1822 1823 case DeclaratorChunk::Reference: 1824 case DeclaratorChunk::Pointer: 1825 // Count the number of pointers. Treat references 1826 // interchangeably as pointers; if they're mis-ordered, normal 1827 // type building will discover that. 1828 outermostPointerIndex = chunkIndex; 1829 numPointers++; 1830 break; 1831 1832 case DeclaratorChunk::BlockPointer: 1833 // If we have a pointer to block pointer, that's an acceptable 1834 // indirect reference; anything else is not an application of 1835 // the rules. 1836 if (numPointers != 1) return; 1837 numPointers++; 1838 outermostPointerIndex = chunkIndex; 1839 isBlockPointer = true; 1840 1841 // We don't care about pointer structure in return values here. 1842 goto done; 1843 1844 case DeclaratorChunk::Array: // suppress if written (id[])? 1845 case DeclaratorChunk::Function: 1846 case DeclaratorChunk::MemberPointer: 1847 return; 1848 } 1849 } 1850 done: 1851 1852 // If we have *one* pointer, then we want to throw the qualifier on 1853 // the declaration-specifiers, which means that it needs to be a 1854 // retainable object type. 1855 if (numPointers == 1) { 1856 // If it's not a retainable object type, the rule doesn't apply. 1857 if (!declSpecType->isObjCRetainableType()) return; 1858 1859 // If it already has lifetime, don't do anything. 1860 if (declSpecType.getObjCLifetime()) return; 1861 1862 // Otherwise, modify the type in-place. 1863 Qualifiers qs; 1864 1865 if (declSpecType->isObjCARCImplicitlyUnretainedType()) 1866 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); 1867 else 1868 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); 1869 declSpecType = S.Context.getQualifiedType(declSpecType, qs); 1870 1871 // If we have *two* pointers, then we want to throw the qualifier on 1872 // the outermost pointer. 1873 } else if (numPointers == 2) { 1874 // If we don't have a block pointer, we need to check whether the 1875 // declaration-specifiers gave us something that will turn into a 1876 // retainable object pointer after we slap the first pointer on it. 1877 if (!isBlockPointer && !declSpecType->isObjCObjectType()) 1878 return; 1879 1880 // Look for an explicit lifetime attribute there. 1881 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); 1882 if (chunk.Kind != DeclaratorChunk::Pointer && 1883 chunk.Kind != DeclaratorChunk::BlockPointer) 1884 return; 1885 for (const AttributeList *attr = chunk.getAttrs(); attr; 1886 attr = attr->getNext()) 1887 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 1888 return; 1889 1890 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, 1891 outermostPointerIndex); 1892 1893 // Any other number of pointers/references does not trigger the rule. 1894 } else return; 1895 1896 // TODO: mark whether we did this inference? 1897} 1898 1899static void diagnoseIgnoredQualifiers( 1900 Sema &S, unsigned Quals, 1901 SourceLocation FallbackLoc, 1902 SourceLocation ConstQualLoc = SourceLocation(), 1903 SourceLocation VolatileQualLoc = SourceLocation(), 1904 SourceLocation RestrictQualLoc = SourceLocation(), 1905 SourceLocation AtomicQualLoc = SourceLocation()) { 1906 if (!Quals) 1907 return; 1908 1909 const SourceManager &SM = S.getSourceManager(); 1910 1911 struct Qual { 1912 unsigned Mask; 1913 const char *Name; 1914 SourceLocation Loc; 1915 } const QualKinds[4] = { 1916 { DeclSpec::TQ_const, "const", ConstQualLoc }, 1917 { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc }, 1918 { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc }, 1919 { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc } 1920 }; 1921 1922 llvm::SmallString<32> QualStr; 1923 unsigned NumQuals = 0; 1924 SourceLocation Loc; 1925 FixItHint FixIts[4]; 1926 1927 // Build a string naming the redundant qualifiers. 1928 for (unsigned I = 0; I != 4; ++I) { 1929 if (Quals & QualKinds[I].Mask) { 1930 if (!QualStr.empty()) QualStr += ' '; 1931 QualStr += QualKinds[I].Name; 1932 1933 // If we have a location for the qualifier, offer a fixit. 1934 SourceLocation QualLoc = QualKinds[I].Loc; 1935 if (!QualLoc.isInvalid()) { 1936 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); 1937 if (Loc.isInvalid() || SM.isBeforeInTranslationUnit(QualLoc, Loc)) 1938 Loc = QualLoc; 1939 } 1940 1941 ++NumQuals; 1942 } 1943 } 1944 1945 S.Diag(Loc.isInvalid() ? FallbackLoc : Loc, diag::warn_qual_return_type) 1946 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; 1947} 1948 1949// Diagnose pointless type qualifiers on the return type of a function. 1950static void diagnoseIgnoredFunctionQualifiers(Sema &S, QualType RetTy, 1951 Declarator &D, 1952 unsigned FunctionChunkIndex) { 1953 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) { 1954 // FIXME: TypeSourceInfo doesn't preserve location information for 1955 // qualifiers. 1956 diagnoseIgnoredQualifiers(S, RetTy.getLocalCVRQualifiers(), 1957 D.getIdentifierLoc()); 1958 return; 1959 } 1960 1961 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, 1962 End = D.getNumTypeObjects(); 1963 OuterChunkIndex != End; ++OuterChunkIndex) { 1964 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); 1965 switch (OuterChunk.Kind) { 1966 case DeclaratorChunk::Paren: 1967 continue; 1968 1969 case DeclaratorChunk::Pointer: { 1970 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; 1971 diagnoseIgnoredQualifiers( 1972 S, PTI.TypeQuals, 1973 SourceLocation(), 1974 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), 1975 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), 1976 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), 1977 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc)); 1978 return; 1979 } 1980 1981 case DeclaratorChunk::Function: 1982 case DeclaratorChunk::BlockPointer: 1983 case DeclaratorChunk::Reference: 1984 case DeclaratorChunk::Array: 1985 case DeclaratorChunk::MemberPointer: 1986 // FIXME: We can't currently provide an accurate source location and a 1987 // fix-it hint for these. 1988 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; 1989 diagnoseIgnoredQualifiers(S, RetTy.getCVRQualifiers() | AtomicQual, 1990 D.getIdentifierLoc()); 1991 return; 1992 } 1993 1994 llvm_unreachable("unknown declarator chunk kind"); 1995 } 1996 1997 // If the qualifiers come from a conversion function type, don't diagnose 1998 // them -- they're not necessarily redundant, since such a conversion 1999 // operator can be explicitly called as "x.operator const int()". 2000 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 2001 return; 2002 2003 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers 2004 // which are present there. 2005 diagnoseIgnoredQualifiers(S, D.getDeclSpec().getTypeQualifiers(), 2006 D.getIdentifierLoc(), 2007 D.getDeclSpec().getConstSpecLoc(), 2008 D.getDeclSpec().getVolatileSpecLoc(), 2009 D.getDeclSpec().getRestrictSpecLoc(), 2010 D.getDeclSpec().getAtomicSpecLoc()); 2011} 2012 2013static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, 2014 TypeSourceInfo *&ReturnTypeInfo) { 2015 Sema &SemaRef = state.getSema(); 2016 Declarator &D = state.getDeclarator(); 2017 QualType T; 2018 ReturnTypeInfo = 0; 2019 2020 // The TagDecl owned by the DeclSpec. 2021 TagDecl *OwnedTagDecl = 0; 2022 2023 switch (D.getName().getKind()) { 2024 case UnqualifiedId::IK_ImplicitSelfParam: 2025 case UnqualifiedId::IK_OperatorFunctionId: 2026 case UnqualifiedId::IK_Identifier: 2027 case UnqualifiedId::IK_LiteralOperatorId: 2028 case UnqualifiedId::IK_TemplateId: 2029 T = ConvertDeclSpecToType(state); 2030 2031 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 2032 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2033 // Owned declaration is embedded in declarator. 2034 OwnedTagDecl->setEmbeddedInDeclarator(true); 2035 } 2036 break; 2037 2038 case UnqualifiedId::IK_ConstructorName: 2039 case UnqualifiedId::IK_ConstructorTemplateId: 2040 case UnqualifiedId::IK_DestructorName: 2041 // Constructors and destructors don't have return types. Use 2042 // "void" instead. 2043 T = SemaRef.Context.VoidTy; 2044 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList()) 2045 processTypeAttrs(state, T, TAL_DeclSpec, attrs); 2046 break; 2047 2048 case UnqualifiedId::IK_ConversionFunctionId: 2049 // The result type of a conversion function is the type that it 2050 // converts to. 2051 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, 2052 &ReturnTypeInfo); 2053 break; 2054 } 2055 2056 if (D.getAttributes()) 2057 distributeTypeAttrsFromDeclarator(state, T); 2058 2059 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 2060 // In C++11, a function declarator using 'auto' must have a trailing return 2061 // type (this is checked later) and we can skip this. In other languages 2062 // using auto, we need to check regardless. 2063 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 2064 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) { 2065 int Error = -1; 2066 2067 switch (D.getContext()) { 2068 case Declarator::KNRTypeListContext: 2069 llvm_unreachable("K&R type lists aren't allowed in C++"); 2070 case Declarator::LambdaExprContext: 2071 llvm_unreachable("Can't specify a type specifier in lambda grammar"); 2072 case Declarator::ObjCParameterContext: 2073 case Declarator::ObjCResultContext: 2074 case Declarator::PrototypeContext: 2075 Error = 0; // Function prototype 2076 break; 2077 case Declarator::MemberContext: 2078 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) 2079 break; 2080 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { 2081 case TTK_Enum: llvm_unreachable("unhandled tag kind"); 2082 case TTK_Struct: Error = 1; /* Struct member */ break; 2083 case TTK_Union: Error = 2; /* Union member */ break; 2084 case TTK_Class: Error = 3; /* Class member */ break; 2085 case TTK_Interface: Error = 4; /* Interface member */ break; 2086 } 2087 break; 2088 case Declarator::CXXCatchContext: 2089 case Declarator::ObjCCatchContext: 2090 Error = 5; // Exception declaration 2091 break; 2092 case Declarator::TemplateParamContext: 2093 Error = 6; // Template parameter 2094 break; 2095 case Declarator::BlockLiteralContext: 2096 Error = 7; // Block literal 2097 break; 2098 case Declarator::TemplateTypeArgContext: 2099 Error = 8; // Template type argument 2100 break; 2101 case Declarator::AliasDeclContext: 2102 case Declarator::AliasTemplateContext: 2103 Error = 10; // Type alias 2104 break; 2105 case Declarator::TrailingReturnContext: 2106 Error = 11; // Function return type 2107 break; 2108 case Declarator::TypeNameContext: 2109 Error = 12; // Generic 2110 break; 2111 case Declarator::FileContext: 2112 case Declarator::BlockContext: 2113 case Declarator::ForContext: 2114 case Declarator::ConditionContext: 2115 case Declarator::CXXNewContext: 2116 break; 2117 } 2118 2119 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 2120 Error = 9; 2121 2122 // In Objective-C it is an error to use 'auto' on a function declarator. 2123 if (D.isFunctionDeclarator()) 2124 Error = 11; 2125 2126 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator 2127 // contains a trailing return type. That is only legal at the outermost 2128 // level. Check all declarator chunks (outermost first) anyway, to give 2129 // better diagnostics. 2130 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) { 2131 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2132 unsigned chunkIndex = e - i - 1; 2133 state.setCurrentChunkIndex(chunkIndex); 2134 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 2135 if (DeclType.Kind == DeclaratorChunk::Function) { 2136 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2137 if (FTI.hasTrailingReturnType()) { 2138 Error = -1; 2139 break; 2140 } 2141 } 2142 } 2143 } 2144 2145 if (Error != -1) { 2146 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2147 diag::err_auto_not_allowed) 2148 << Error; 2149 T = SemaRef.Context.IntTy; 2150 D.setInvalidType(true); 2151 } else 2152 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2153 diag::warn_cxx98_compat_auto_type_specifier); 2154 } 2155 2156 if (SemaRef.getLangOpts().CPlusPlus && 2157 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 2158 // Check the contexts where C++ forbids the declaration of a new class 2159 // or enumeration in a type-specifier-seq. 2160 switch (D.getContext()) { 2161 case Declarator::TrailingReturnContext: 2162 // Class and enumeration definitions are syntactically not allowed in 2163 // trailing return types. 2164 llvm_unreachable("parser should not have allowed this"); 2165 break; 2166 case Declarator::FileContext: 2167 case Declarator::MemberContext: 2168 case Declarator::BlockContext: 2169 case Declarator::ForContext: 2170 case Declarator::BlockLiteralContext: 2171 case Declarator::LambdaExprContext: 2172 // C++11 [dcl.type]p3: 2173 // A type-specifier-seq shall not define a class or enumeration unless 2174 // it appears in the type-id of an alias-declaration (7.1.3) that is not 2175 // the declaration of a template-declaration. 2176 case Declarator::AliasDeclContext: 2177 break; 2178 case Declarator::AliasTemplateContext: 2179 SemaRef.Diag(OwnedTagDecl->getLocation(), 2180 diag::err_type_defined_in_alias_template) 2181 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2182 D.setInvalidType(true); 2183 break; 2184 case Declarator::TypeNameContext: 2185 case Declarator::TemplateParamContext: 2186 case Declarator::CXXNewContext: 2187 case Declarator::CXXCatchContext: 2188 case Declarator::ObjCCatchContext: 2189 case Declarator::TemplateTypeArgContext: 2190 SemaRef.Diag(OwnedTagDecl->getLocation(), 2191 diag::err_type_defined_in_type_specifier) 2192 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2193 D.setInvalidType(true); 2194 break; 2195 case Declarator::PrototypeContext: 2196 case Declarator::ObjCParameterContext: 2197 case Declarator::ObjCResultContext: 2198 case Declarator::KNRTypeListContext: 2199 // C++ [dcl.fct]p6: 2200 // Types shall not be defined in return or parameter types. 2201 SemaRef.Diag(OwnedTagDecl->getLocation(), 2202 diag::err_type_defined_in_param_type) 2203 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2204 D.setInvalidType(true); 2205 break; 2206 case Declarator::ConditionContext: 2207 // C++ 6.4p2: 2208 // The type-specifier-seq shall not contain typedef and shall not declare 2209 // a new class or enumeration. 2210 SemaRef.Diag(OwnedTagDecl->getLocation(), 2211 diag::err_type_defined_in_condition); 2212 D.setInvalidType(true); 2213 break; 2214 } 2215 } 2216 2217 return T; 2218} 2219 2220static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ 2221 std::string Quals = 2222 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString(); 2223 2224 switch (FnTy->getRefQualifier()) { 2225 case RQ_None: 2226 break; 2227 2228 case RQ_LValue: 2229 if (!Quals.empty()) 2230 Quals += ' '; 2231 Quals += '&'; 2232 break; 2233 2234 case RQ_RValue: 2235 if (!Quals.empty()) 2236 Quals += ' '; 2237 Quals += "&&"; 2238 break; 2239 } 2240 2241 return Quals; 2242} 2243 2244/// Check that the function type T, which has a cv-qualifier or a ref-qualifier, 2245/// can be contained within the declarator chunk DeclType, and produce an 2246/// appropriate diagnostic if not. 2247static void checkQualifiedFunction(Sema &S, QualType T, 2248 DeclaratorChunk &DeclType) { 2249 // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a 2250 // cv-qualifier or a ref-qualifier can only appear at the topmost level 2251 // of a type. 2252 int DiagKind = -1; 2253 switch (DeclType.Kind) { 2254 case DeclaratorChunk::Paren: 2255 case DeclaratorChunk::MemberPointer: 2256 // These cases are permitted. 2257 return; 2258 case DeclaratorChunk::Array: 2259 case DeclaratorChunk::Function: 2260 // These cases don't allow function types at all; no need to diagnose the 2261 // qualifiers separately. 2262 return; 2263 case DeclaratorChunk::BlockPointer: 2264 DiagKind = 0; 2265 break; 2266 case DeclaratorChunk::Pointer: 2267 DiagKind = 1; 2268 break; 2269 case DeclaratorChunk::Reference: 2270 DiagKind = 2; 2271 break; 2272 } 2273 2274 assert(DiagKind != -1); 2275 S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type) 2276 << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T 2277 << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>()); 2278} 2279 2280/// Produce an approprioate diagnostic for an ambiguity between a function 2281/// declarator and a C++ direct-initializer. 2282static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, 2283 DeclaratorChunk &DeclType, QualType RT) { 2284 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2285 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity"); 2286 2287 // If the return type is void there is no ambiguity. 2288 if (RT->isVoidType()) 2289 return; 2290 2291 // An initializer for a non-class type can have at most one argument. 2292 if (!RT->isRecordType() && FTI.NumArgs > 1) 2293 return; 2294 2295 // An initializer for a reference must have exactly one argument. 2296 if (RT->isReferenceType() && FTI.NumArgs != 1) 2297 return; 2298 2299 // Only warn if this declarator is declaring a function at block scope, and 2300 // doesn't have a storage class (such as 'extern') specified. 2301 if (!D.isFunctionDeclarator() || 2302 D.getFunctionDefinitionKind() != FDK_Declaration || 2303 !S.CurContext->isFunctionOrMethod() || 2304 D.getDeclSpec().getStorageClassSpecAsWritten() 2305 != DeclSpec::SCS_unspecified) 2306 return; 2307 2308 // Inside a condition, a direct initializer is not permitted. We allow one to 2309 // be parsed in order to give better diagnostics in condition parsing. 2310 if (D.getContext() == Declarator::ConditionContext) 2311 return; 2312 2313 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); 2314 2315 S.Diag(DeclType.Loc, 2316 FTI.NumArgs ? diag::warn_parens_disambiguated_as_function_declaration 2317 : diag::warn_empty_parens_are_function_decl) 2318 << ParenRange; 2319 2320 // If the declaration looks like: 2321 // T var1, 2322 // f(); 2323 // and name lookup finds a function named 'f', then the ',' was 2324 // probably intended to be a ';'. 2325 if (!D.isFirstDeclarator() && D.getIdentifier()) { 2326 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); 2327 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); 2328 if (Comma.getFileID() != Name.getFileID() || 2329 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { 2330 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 2331 Sema::LookupOrdinaryName); 2332 if (S.LookupName(Result, S.getCurScope())) 2333 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) 2334 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") 2335 << D.getIdentifier(); 2336 } 2337 } 2338 2339 if (FTI.NumArgs > 0) { 2340 // For a declaration with parameters, eg. "T var(T());", suggest adding parens 2341 // around the first parameter to turn the declaration into a variable 2342 // declaration. 2343 SourceRange Range = FTI.ArgInfo[0].Param->getSourceRange(); 2344 SourceLocation B = Range.getBegin(); 2345 SourceLocation E = S.PP.getLocForEndOfToken(Range.getEnd()); 2346 // FIXME: Maybe we should suggest adding braces instead of parens 2347 // in C++11 for classes that don't have an initializer_list constructor. 2348 S.Diag(B, diag::note_additional_parens_for_variable_declaration) 2349 << FixItHint::CreateInsertion(B, "(") 2350 << FixItHint::CreateInsertion(E, ")"); 2351 } else { 2352 // For a declaration without parameters, eg. "T var();", suggest replacing the 2353 // parens with an initializer to turn the declaration into a variable 2354 // declaration. 2355 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 2356 2357 // Empty parens mean value-initialization, and no parens mean 2358 // default initialization. These are equivalent if the default 2359 // constructor is user-provided or if zero-initialization is a 2360 // no-op. 2361 if (RD && RD->hasDefinition() && 2362 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) 2363 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) 2364 << FixItHint::CreateRemoval(ParenRange); 2365 else { 2366 std::string Init = S.getFixItZeroInitializerForType(RT); 2367 if (Init.empty() && S.LangOpts.CPlusPlus11) 2368 Init = "{}"; 2369 if (!Init.empty()) 2370 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) 2371 << FixItHint::CreateReplacement(ParenRange, Init); 2372 } 2373 } 2374} 2375 2376static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 2377 QualType declSpecType, 2378 TypeSourceInfo *TInfo) { 2379 2380 QualType T = declSpecType; 2381 Declarator &D = state.getDeclarator(); 2382 Sema &S = state.getSema(); 2383 ASTContext &Context = S.Context; 2384 const LangOptions &LangOpts = S.getLangOpts(); 2385 2386 // The name we're declaring, if any. 2387 DeclarationName Name; 2388 if (D.getIdentifier()) 2389 Name = D.getIdentifier(); 2390 2391 // Does this declaration declare a typedef-name? 2392 bool IsTypedefName = 2393 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 2394 D.getContext() == Declarator::AliasDeclContext || 2395 D.getContext() == Declarator::AliasTemplateContext; 2396 2397 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 2398 bool IsQualifiedFunction = T->isFunctionProtoType() && 2399 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 || 2400 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 2401 2402 // Walk the DeclTypeInfo, building the recursive type as we go. 2403 // DeclTypeInfos are ordered from the identifier out, which is 2404 // opposite of what we want :). 2405 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2406 unsigned chunkIndex = e - i - 1; 2407 state.setCurrentChunkIndex(chunkIndex); 2408 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 2409 if (IsQualifiedFunction) { 2410 checkQualifiedFunction(S, T, DeclType); 2411 IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren; 2412 } 2413 switch (DeclType.Kind) { 2414 case DeclaratorChunk::Paren: 2415 T = S.BuildParenType(T); 2416 break; 2417 case DeclaratorChunk::BlockPointer: 2418 // If blocks are disabled, emit an error. 2419 if (!LangOpts.Blocks) 2420 S.Diag(DeclType.Loc, diag::err_blocks_disable); 2421 2422 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 2423 if (DeclType.Cls.TypeQuals) 2424 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 2425 break; 2426 case DeclaratorChunk::Pointer: 2427 // Verify that we're not building a pointer to pointer to function with 2428 // exception specification. 2429 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2430 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2431 D.setInvalidType(true); 2432 // Build the type anyway. 2433 } 2434 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) { 2435 T = Context.getObjCObjectPointerType(T); 2436 if (DeclType.Ptr.TypeQuals) 2437 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 2438 break; 2439 } 2440 T = S.BuildPointerType(T, DeclType.Loc, Name); 2441 if (DeclType.Ptr.TypeQuals) 2442 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 2443 2444 break; 2445 case DeclaratorChunk::Reference: { 2446 // Verify that we're not building a reference to pointer to function with 2447 // exception specification. 2448 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2449 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2450 D.setInvalidType(true); 2451 // Build the type anyway. 2452 } 2453 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 2454 2455 Qualifiers Quals; 2456 if (DeclType.Ref.HasRestrict) 2457 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 2458 break; 2459 } 2460 case DeclaratorChunk::Array: { 2461 // Verify that we're not building an array of pointers to function with 2462 // exception specification. 2463 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2464 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2465 D.setInvalidType(true); 2466 // Build the type anyway. 2467 } 2468 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 2469 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 2470 ArrayType::ArraySizeModifier ASM; 2471 if (ATI.isStar) 2472 ASM = ArrayType::Star; 2473 else if (ATI.hasStatic) 2474 ASM = ArrayType::Static; 2475 else 2476 ASM = ArrayType::Normal; 2477 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 2478 // FIXME: This check isn't quite right: it allows star in prototypes 2479 // for function definitions, and disallows some edge cases detailed 2480 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 2481 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 2482 ASM = ArrayType::Normal; 2483 D.setInvalidType(true); 2484 } 2485 2486 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static 2487 // shall appear only in a declaration of a function parameter with an 2488 // array type, ... 2489 if (ASM == ArrayType::Static || ATI.TypeQuals) { 2490 if (!(D.isPrototypeContext() || 2491 D.getContext() == Declarator::KNRTypeListContext)) { 2492 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << 2493 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 2494 // Remove the 'static' and the type qualifiers. 2495 if (ASM == ArrayType::Static) 2496 ASM = ArrayType::Normal; 2497 ATI.TypeQuals = 0; 2498 D.setInvalidType(true); 2499 } 2500 2501 // C99 6.7.5.2p1: ... and then only in the outermost array type 2502 // derivation. 2503 unsigned x = chunkIndex; 2504 while (x != 0) { 2505 // Walk outwards along the declarator chunks. 2506 x--; 2507 const DeclaratorChunk &DC = D.getTypeObject(x); 2508 switch (DC.Kind) { 2509 case DeclaratorChunk::Paren: 2510 continue; 2511 case DeclaratorChunk::Array: 2512 case DeclaratorChunk::Pointer: 2513 case DeclaratorChunk::Reference: 2514 case DeclaratorChunk::MemberPointer: 2515 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << 2516 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 2517 if (ASM == ArrayType::Static) 2518 ASM = ArrayType::Normal; 2519 ATI.TypeQuals = 0; 2520 D.setInvalidType(true); 2521 break; 2522 case DeclaratorChunk::Function: 2523 case DeclaratorChunk::BlockPointer: 2524 // These are invalid anyway, so just ignore. 2525 break; 2526 } 2527 } 2528 } 2529 2530 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 2531 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 2532 break; 2533 } 2534 case DeclaratorChunk::Function: { 2535 // If the function declarator has a prototype (i.e. it is not () and 2536 // does not have a K&R-style identifier list), then the arguments are part 2537 // of the type, otherwise the argument list is (). 2538 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2539 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier(); 2540 2541 // Check for auto functions and trailing return type and adjust the 2542 // return type accordingly. 2543 if (!D.isInvalidType()) { 2544 // trailing-return-type is only required if we're declaring a function, 2545 // and not, for instance, a pointer to a function. 2546 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 2547 !FTI.hasTrailingReturnType() && chunkIndex == 0) { 2548 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2549 diag::err_auto_missing_trailing_return); 2550 T = Context.IntTy; 2551 D.setInvalidType(true); 2552 } else if (FTI.hasTrailingReturnType()) { 2553 // T must be exactly 'auto' at this point. See CWG issue 681. 2554 if (isa<ParenType>(T)) { 2555 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2556 diag::err_trailing_return_in_parens) 2557 << T << D.getDeclSpec().getSourceRange(); 2558 D.setInvalidType(true); 2559 } else if (D.getContext() != Declarator::LambdaExprContext && 2560 (T.hasQualifiers() || !isa<AutoType>(T))) { 2561 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2562 diag::err_trailing_return_without_auto) 2563 << T << D.getDeclSpec().getSourceRange(); 2564 D.setInvalidType(true); 2565 } 2566 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); 2567 if (T.isNull()) { 2568 // An error occurred parsing the trailing return type. 2569 T = Context.IntTy; 2570 D.setInvalidType(true); 2571 } 2572 } 2573 } 2574 2575 // C99 6.7.5.3p1: The return type may not be a function or array type. 2576 // For conversion functions, we'll diagnose this particular error later. 2577 if ((T->isArrayType() || T->isFunctionType()) && 2578 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 2579 unsigned diagID = diag::err_func_returning_array_function; 2580 // Last processing chunk in block context means this function chunk 2581 // represents the block. 2582 if (chunkIndex == 0 && 2583 D.getContext() == Declarator::BlockLiteralContext) 2584 diagID = diag::err_block_returning_array_function; 2585 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 2586 T = Context.IntTy; 2587 D.setInvalidType(true); 2588 } 2589 2590 // Do not allow returning half FP value. 2591 // FIXME: This really should be in BuildFunctionType. 2592 if (T->isHalfType()) { 2593 if (S.getLangOpts().OpenCL) { 2594 if (!S.getOpenCLOptions().cl_khr_fp16) { 2595 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T; 2596 D.setInvalidType(true); 2597 } 2598 } else { 2599 S.Diag(D.getIdentifierLoc(), 2600 diag::err_parameters_retval_cannot_have_fp16_type) << 1; 2601 D.setInvalidType(true); 2602 } 2603 } 2604 2605 // cv-qualifiers on return types are pointless except when the type is a 2606 // class type in C++. 2607 if ((T.getCVRQualifiers() || T->isAtomicType()) && 2608 !(S.getLangOpts().CPlusPlus && 2609 (T->isDependentType() || T->isRecordType()))) 2610 diagnoseIgnoredFunctionQualifiers(S, T, D, chunkIndex); 2611 2612 // Objective-C ARC ownership qualifiers are ignored on the function 2613 // return type (by type canonicalization). Complain if this attribute 2614 // was written here. 2615 if (T.getQualifiers().hasObjCLifetime()) { 2616 SourceLocation AttrLoc; 2617 if (chunkIndex + 1 < D.getNumTypeObjects()) { 2618 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 2619 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs(); 2620 Attr; Attr = Attr->getNext()) { 2621 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 2622 AttrLoc = Attr->getLoc(); 2623 break; 2624 } 2625 } 2626 } 2627 if (AttrLoc.isInvalid()) { 2628 for (const AttributeList *Attr 2629 = D.getDeclSpec().getAttributes().getList(); 2630 Attr; Attr = Attr->getNext()) { 2631 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 2632 AttrLoc = Attr->getLoc(); 2633 break; 2634 } 2635 } 2636 } 2637 2638 if (AttrLoc.isValid()) { 2639 // The ownership attributes are almost always written via 2640 // the predefined 2641 // __strong/__weak/__autoreleasing/__unsafe_unretained. 2642 if (AttrLoc.isMacroID()) 2643 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first; 2644 2645 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 2646 << T.getQualifiers().getObjCLifetime(); 2647 } 2648 } 2649 2650 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) { 2651 // C++ [dcl.fct]p6: 2652 // Types shall not be defined in return or parameter types. 2653 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2654 if (Tag->isCompleteDefinition()) 2655 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 2656 << Context.getTypeDeclType(Tag); 2657 } 2658 2659 // Exception specs are not allowed in typedefs. Complain, but add it 2660 // anyway. 2661 if (IsTypedefName && FTI.getExceptionSpecType()) 2662 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef) 2663 << (D.getContext() == Declarator::AliasDeclContext || 2664 D.getContext() == Declarator::AliasTemplateContext); 2665 2666 // If we see "T var();" or "T var(T());" at block scope, it is probably 2667 // an attempt to initialize a variable, not a function declaration. 2668 if (FTI.isAmbiguous) 2669 warnAboutAmbiguousFunction(S, D, DeclType, T); 2670 2671 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) { 2672 // Simple void foo(), where the incoming T is the result type. 2673 T = Context.getFunctionNoProtoType(T); 2674 } else { 2675 // We allow a zero-parameter variadic function in C if the 2676 // function is marked with the "overloadable" attribute. Scan 2677 // for this attribute now. 2678 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) { 2679 bool Overloadable = false; 2680 for (const AttributeList *Attrs = D.getAttributes(); 2681 Attrs; Attrs = Attrs->getNext()) { 2682 if (Attrs->getKind() == AttributeList::AT_Overloadable) { 2683 Overloadable = true; 2684 break; 2685 } 2686 } 2687 2688 if (!Overloadable) 2689 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 2690 } 2691 2692 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) { 2693 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 2694 // definition. 2695 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 2696 D.setInvalidType(true); 2697 // Recover by creating a K&R-style function type. 2698 T = Context.getFunctionNoProtoType(T); 2699 break; 2700 } 2701 2702 FunctionProtoType::ExtProtoInfo EPI; 2703 EPI.Variadic = FTI.isVariadic; 2704 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 2705 EPI.TypeQuals = FTI.TypeQuals; 2706 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 2707 : FTI.RefQualifierIsLValueRef? RQ_LValue 2708 : RQ_RValue; 2709 2710 // Otherwise, we have a function with an argument list that is 2711 // potentially variadic. 2712 SmallVector<QualType, 16> ArgTys; 2713 ArgTys.reserve(FTI.NumArgs); 2714 2715 SmallVector<bool, 16> ConsumedArguments; 2716 ConsumedArguments.reserve(FTI.NumArgs); 2717 bool HasAnyConsumedArguments = false; 2718 2719 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 2720 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 2721 QualType ArgTy = Param->getType(); 2722 assert(!ArgTy.isNull() && "Couldn't parse type?"); 2723 2724 // Adjust the parameter type. 2725 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) && 2726 "Unadjusted type?"); 2727 2728 // Look for 'void'. void is allowed only as a single argument to a 2729 // function with no other parameters (C99 6.7.5.3p10). We record 2730 // int(void) as a FunctionProtoType with an empty argument list. 2731 if (ArgTy->isVoidType()) { 2732 // If this is something like 'float(int, void)', reject it. 'void' 2733 // is an incomplete type (C99 6.2.5p19) and function decls cannot 2734 // have arguments of incomplete type. 2735 if (FTI.NumArgs != 1 || FTI.isVariadic) { 2736 S.Diag(DeclType.Loc, diag::err_void_only_param); 2737 ArgTy = Context.IntTy; 2738 Param->setType(ArgTy); 2739 } else if (FTI.ArgInfo[i].Ident) { 2740 // Reject, but continue to parse 'int(void abc)'. 2741 S.Diag(FTI.ArgInfo[i].IdentLoc, 2742 diag::err_param_with_void_type); 2743 ArgTy = Context.IntTy; 2744 Param->setType(ArgTy); 2745 } else { 2746 // Reject, but continue to parse 'float(const void)'. 2747 if (ArgTy.hasQualifiers()) 2748 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 2749 2750 // Do not add 'void' to the ArgTys list. 2751 break; 2752 } 2753 } else if (ArgTy->isHalfType()) { 2754 // Disallow half FP arguments. 2755 // FIXME: This really should be in BuildFunctionType. 2756 if (S.getLangOpts().OpenCL) { 2757 if (!S.getOpenCLOptions().cl_khr_fp16) { 2758 S.Diag(Param->getLocation(), 2759 diag::err_opencl_half_argument) << ArgTy; 2760 D.setInvalidType(); 2761 Param->setInvalidDecl(); 2762 } 2763 } else { 2764 S.Diag(Param->getLocation(), 2765 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 2766 D.setInvalidType(); 2767 } 2768 } else if (!FTI.hasPrototype) { 2769 if (ArgTy->isPromotableIntegerType()) { 2770 ArgTy = Context.getPromotedIntegerType(ArgTy); 2771 Param->setKNRPromoted(true); 2772 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) { 2773 if (BTy->getKind() == BuiltinType::Float) { 2774 ArgTy = Context.DoubleTy; 2775 Param->setKNRPromoted(true); 2776 } 2777 } 2778 } 2779 2780 if (LangOpts.ObjCAutoRefCount) { 2781 bool Consumed = Param->hasAttr<NSConsumedAttr>(); 2782 ConsumedArguments.push_back(Consumed); 2783 HasAnyConsumedArguments |= Consumed; 2784 } 2785 2786 ArgTys.push_back(ArgTy); 2787 } 2788 2789 if (HasAnyConsumedArguments) 2790 EPI.ConsumedArguments = ConsumedArguments.data(); 2791 2792 SmallVector<QualType, 4> Exceptions; 2793 SmallVector<ParsedType, 2> DynamicExceptions; 2794 SmallVector<SourceRange, 2> DynamicExceptionRanges; 2795 Expr *NoexceptExpr = 0; 2796 2797 if (FTI.getExceptionSpecType() == EST_Dynamic) { 2798 // FIXME: It's rather inefficient to have to split into two vectors 2799 // here. 2800 unsigned N = FTI.NumExceptions; 2801 DynamicExceptions.reserve(N); 2802 DynamicExceptionRanges.reserve(N); 2803 for (unsigned I = 0; I != N; ++I) { 2804 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 2805 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 2806 } 2807 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 2808 NoexceptExpr = FTI.NoexceptExpr; 2809 } 2810 2811 S.checkExceptionSpecification(FTI.getExceptionSpecType(), 2812 DynamicExceptions, 2813 DynamicExceptionRanges, 2814 NoexceptExpr, 2815 Exceptions, 2816 EPI); 2817 2818 T = Context.getFunctionType(T, ArgTys, EPI); 2819 } 2820 2821 break; 2822 } 2823 case DeclaratorChunk::MemberPointer: 2824 // The scope spec must refer to a class, or be dependent. 2825 CXXScopeSpec &SS = DeclType.Mem.Scope(); 2826 QualType ClsType; 2827 if (SS.isInvalid()) { 2828 // Avoid emitting extra errors if we already errored on the scope. 2829 D.setInvalidType(true); 2830 } else if (S.isDependentScopeSpecifier(SS) || 2831 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 2832 NestedNameSpecifier *NNS 2833 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2834 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 2835 switch (NNS->getKind()) { 2836 case NestedNameSpecifier::Identifier: 2837 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 2838 NNS->getAsIdentifier()); 2839 break; 2840 2841 case NestedNameSpecifier::Namespace: 2842 case NestedNameSpecifier::NamespaceAlias: 2843 case NestedNameSpecifier::Global: 2844 llvm_unreachable("Nested-name-specifier must name a type"); 2845 2846 case NestedNameSpecifier::TypeSpec: 2847 case NestedNameSpecifier::TypeSpecWithTemplate: 2848 ClsType = QualType(NNS->getAsType(), 0); 2849 // Note: if the NNS has a prefix and ClsType is a nondependent 2850 // TemplateSpecializationType, then the NNS prefix is NOT included 2851 // in ClsType; hence we wrap ClsType into an ElaboratedType. 2852 // NOTE: in particular, no wrap occurs if ClsType already is an 2853 // Elaborated, DependentName, or DependentTemplateSpecialization. 2854 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 2855 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 2856 break; 2857 } 2858 } else { 2859 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 2860 diag::err_illegal_decl_mempointer_in_nonclass) 2861 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 2862 << DeclType.Mem.Scope().getRange(); 2863 D.setInvalidType(true); 2864 } 2865 2866 if (!ClsType.isNull()) 2867 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier()); 2868 if (T.isNull()) { 2869 T = Context.IntTy; 2870 D.setInvalidType(true); 2871 } else if (DeclType.Mem.TypeQuals) { 2872 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 2873 } 2874 break; 2875 } 2876 2877 if (T.isNull()) { 2878 D.setInvalidType(true); 2879 T = Context.IntTy; 2880 } 2881 2882 // See if there are any attributes on this declarator chunk. 2883 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs())) 2884 processTypeAttrs(state, T, TAL_DeclChunk, attrs); 2885 } 2886 2887 if (LangOpts.CPlusPlus && T->isFunctionType()) { 2888 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 2889 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 2890 2891 // C++ 8.3.5p4: 2892 // A cv-qualifier-seq shall only be part of the function type 2893 // for a nonstatic member function, the function type to which a pointer 2894 // to member refers, or the top-level function type of a function typedef 2895 // declaration. 2896 // 2897 // Core issue 547 also allows cv-qualifiers on function types that are 2898 // top-level template type arguments. 2899 bool FreeFunction; 2900 if (!D.getCXXScopeSpec().isSet()) { 2901 FreeFunction = ((D.getContext() != Declarator::MemberContext && 2902 D.getContext() != Declarator::LambdaExprContext) || 2903 D.getDeclSpec().isFriendSpecified()); 2904 } else { 2905 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 2906 FreeFunction = (DC && !DC->isRecord()); 2907 } 2908 2909 // C++11 [dcl.fct]p6 (w/DR1417): 2910 // An attempt to specify a function type with a cv-qualifier-seq or a 2911 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 2912 // - the function type for a non-static member function, 2913 // - the function type to which a pointer to member refers, 2914 // - the top-level function type of a function typedef declaration or 2915 // alias-declaration, 2916 // - the type-id in the default argument of a type-parameter, or 2917 // - the type-id of a template-argument for a type-parameter 2918 if (IsQualifiedFunction && 2919 !(!FreeFunction && 2920 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 2921 !IsTypedefName && 2922 D.getContext() != Declarator::TemplateTypeArgContext) { 2923 SourceLocation Loc = D.getLocStart(); 2924 SourceRange RemovalRange; 2925 unsigned I; 2926 if (D.isFunctionDeclarator(I)) { 2927 SmallVector<SourceLocation, 4> RemovalLocs; 2928 const DeclaratorChunk &Chunk = D.getTypeObject(I); 2929 assert(Chunk.Kind == DeclaratorChunk::Function); 2930 if (Chunk.Fun.hasRefQualifier()) 2931 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 2932 if (Chunk.Fun.TypeQuals & Qualifiers::Const) 2933 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); 2934 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) 2935 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); 2936 // FIXME: We do not track the location of the __restrict qualifier. 2937 //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) 2938 // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); 2939 if (!RemovalLocs.empty()) { 2940 std::sort(RemovalLocs.begin(), RemovalLocs.end(), 2941 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 2942 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 2943 Loc = RemovalLocs.front(); 2944 } 2945 } 2946 2947 S.Diag(Loc, diag::err_invalid_qualified_function_type) 2948 << FreeFunction << D.isFunctionDeclarator() << T 2949 << getFunctionQualifiersAsString(FnTy) 2950 << FixItHint::CreateRemoval(RemovalRange); 2951 2952 // Strip the cv-qualifiers and ref-qualifiers from the type. 2953 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 2954 EPI.TypeQuals = 0; 2955 EPI.RefQualifier = RQ_None; 2956 2957 T = Context.getFunctionType(FnTy->getResultType(), 2958 ArrayRef<QualType>(FnTy->arg_type_begin(), 2959 FnTy->getNumArgs()), 2960 EPI); 2961 // Rebuild any parens around the identifier in the function type. 2962 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2963 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 2964 break; 2965 T = S.BuildParenType(T); 2966 } 2967 } 2968 } 2969 2970 // Apply any undistributed attributes from the declarator. 2971 if (!T.isNull()) 2972 if (AttributeList *attrs = D.getAttributes()) 2973 processTypeAttrs(state, T, TAL_DeclName, attrs); 2974 2975 // Diagnose any ignored type attributes. 2976 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T); 2977 2978 // C++0x [dcl.constexpr]p9: 2979 // A constexpr specifier used in an object declaration declares the object 2980 // as const. 2981 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 2982 T.addConst(); 2983 } 2984 2985 // If there was an ellipsis in the declarator, the declaration declares a 2986 // parameter pack whose type may be a pack expansion type. 2987 if (D.hasEllipsis() && !T.isNull()) { 2988 // C++0x [dcl.fct]p13: 2989 // A declarator-id or abstract-declarator containing an ellipsis shall 2990 // only be used in a parameter-declaration. Such a parameter-declaration 2991 // is a parameter pack (14.5.3). [...] 2992 switch (D.getContext()) { 2993 case Declarator::PrototypeContext: 2994 // C++0x [dcl.fct]p13: 2995 // [...] When it is part of a parameter-declaration-clause, the 2996 // parameter pack is a function parameter pack (14.5.3). The type T 2997 // of the declarator-id of the function parameter pack shall contain 2998 // a template parameter pack; each template parameter pack in T is 2999 // expanded by the function parameter pack. 3000 // 3001 // We represent function parameter packs as function parameters whose 3002 // type is a pack expansion. 3003 if (!T->containsUnexpandedParameterPack()) { 3004 S.Diag(D.getEllipsisLoc(), 3005 diag::err_function_parameter_pack_without_parameter_packs) 3006 << T << D.getSourceRange(); 3007 D.setEllipsisLoc(SourceLocation()); 3008 } else { 3009 T = Context.getPackExpansionType(T, None); 3010 } 3011 break; 3012 3013 case Declarator::TemplateParamContext: 3014 // C++0x [temp.param]p15: 3015 // If a template-parameter is a [...] is a parameter-declaration that 3016 // declares a parameter pack (8.3.5), then the template-parameter is a 3017 // template parameter pack (14.5.3). 3018 // 3019 // Note: core issue 778 clarifies that, if there are any unexpanded 3020 // parameter packs in the type of the non-type template parameter, then 3021 // it expands those parameter packs. 3022 if (T->containsUnexpandedParameterPack()) 3023 T = Context.getPackExpansionType(T, None); 3024 else 3025 S.Diag(D.getEllipsisLoc(), 3026 LangOpts.CPlusPlus11 3027 ? diag::warn_cxx98_compat_variadic_templates 3028 : diag::ext_variadic_templates); 3029 break; 3030 3031 case Declarator::FileContext: 3032 case Declarator::KNRTypeListContext: 3033 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here? 3034 case Declarator::ObjCResultContext: // FIXME: special diagnostic here? 3035 case Declarator::TypeNameContext: 3036 case Declarator::CXXNewContext: 3037 case Declarator::AliasDeclContext: 3038 case Declarator::AliasTemplateContext: 3039 case Declarator::MemberContext: 3040 case Declarator::BlockContext: 3041 case Declarator::ForContext: 3042 case Declarator::ConditionContext: 3043 case Declarator::CXXCatchContext: 3044 case Declarator::ObjCCatchContext: 3045 case Declarator::BlockLiteralContext: 3046 case Declarator::LambdaExprContext: 3047 case Declarator::TrailingReturnContext: 3048 case Declarator::TemplateTypeArgContext: 3049 // FIXME: We may want to allow parameter packs in block-literal contexts 3050 // in the future. 3051 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter); 3052 D.setEllipsisLoc(SourceLocation()); 3053 break; 3054 } 3055 } 3056 3057 if (T.isNull()) 3058 return Context.getNullTypeSourceInfo(); 3059 else if (D.isInvalidType()) 3060 return Context.getTrivialTypeSourceInfo(T); 3061 3062 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 3063} 3064 3065/// GetTypeForDeclarator - Convert the type for the specified 3066/// declarator to Type instances. 3067/// 3068/// The result of this call will never be null, but the associated 3069/// type may be a null type if there's an unrecoverable error. 3070TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 3071 // Determine the type of the declarator. Not all forms of declarator 3072 // have a type. 3073 3074 TypeProcessingState state(*this, D); 3075 3076 TypeSourceInfo *ReturnTypeInfo = 0; 3077 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 3078 if (T.isNull()) 3079 return Context.getNullTypeSourceInfo(); 3080 3081 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 3082 inferARCWriteback(state, T); 3083 3084 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 3085} 3086 3087static void transferARCOwnershipToDeclSpec(Sema &S, 3088 QualType &declSpecTy, 3089 Qualifiers::ObjCLifetime ownership) { 3090 if (declSpecTy->isObjCRetainableType() && 3091 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 3092 Qualifiers qs; 3093 qs.addObjCLifetime(ownership); 3094 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 3095 } 3096} 3097 3098static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 3099 Qualifiers::ObjCLifetime ownership, 3100 unsigned chunkIndex) { 3101 Sema &S = state.getSema(); 3102 Declarator &D = state.getDeclarator(); 3103 3104 // Look for an explicit lifetime attribute. 3105 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 3106 for (const AttributeList *attr = chunk.getAttrs(); attr; 3107 attr = attr->getNext()) 3108 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 3109 return; 3110 3111 const char *attrStr = 0; 3112 switch (ownership) { 3113 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 3114 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 3115 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 3116 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 3117 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 3118 } 3119 3120 // If there wasn't one, add one (with an invalid source location 3121 // so that we don't make an AttributedType for it). 3122 AttributeList *attr = D.getAttributePool() 3123 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 3124 /*scope*/ 0, SourceLocation(), 3125 &S.Context.Idents.get(attrStr), SourceLocation(), 3126 /*args*/ 0, 0, AttributeList::AS_GNU); 3127 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 3128 3129 // TODO: mark whether we did this inference? 3130} 3131 3132/// \brief Used for transferring ownership in casts resulting in l-values. 3133static void transferARCOwnership(TypeProcessingState &state, 3134 QualType &declSpecTy, 3135 Qualifiers::ObjCLifetime ownership) { 3136 Sema &S = state.getSema(); 3137 Declarator &D = state.getDeclarator(); 3138 3139 int inner = -1; 3140 bool hasIndirection = false; 3141 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3142 DeclaratorChunk &chunk = D.getTypeObject(i); 3143 switch (chunk.Kind) { 3144 case DeclaratorChunk::Paren: 3145 // Ignore parens. 3146 break; 3147 3148 case DeclaratorChunk::Array: 3149 case DeclaratorChunk::Reference: 3150 case DeclaratorChunk::Pointer: 3151 if (inner != -1) 3152 hasIndirection = true; 3153 inner = i; 3154 break; 3155 3156 case DeclaratorChunk::BlockPointer: 3157 if (inner != -1) 3158 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 3159 return; 3160 3161 case DeclaratorChunk::Function: 3162 case DeclaratorChunk::MemberPointer: 3163 return; 3164 } 3165 } 3166 3167 if (inner == -1) 3168 return; 3169 3170 DeclaratorChunk &chunk = D.getTypeObject(inner); 3171 if (chunk.Kind == DeclaratorChunk::Pointer) { 3172 if (declSpecTy->isObjCRetainableType()) 3173 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 3174 if (declSpecTy->isObjCObjectType() && hasIndirection) 3175 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 3176 } else { 3177 assert(chunk.Kind == DeclaratorChunk::Array || 3178 chunk.Kind == DeclaratorChunk::Reference); 3179 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 3180 } 3181} 3182 3183TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 3184 TypeProcessingState state(*this, D); 3185 3186 TypeSourceInfo *ReturnTypeInfo = 0; 3187 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 3188 if (declSpecTy.isNull()) 3189 return Context.getNullTypeSourceInfo(); 3190 3191 if (getLangOpts().ObjCAutoRefCount) { 3192 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 3193 if (ownership != Qualifiers::OCL_None) 3194 transferARCOwnership(state, declSpecTy, ownership); 3195 } 3196 3197 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 3198} 3199 3200/// Map an AttributedType::Kind to an AttributeList::Kind. 3201static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 3202 switch (kind) { 3203 case AttributedType::attr_address_space: 3204 return AttributeList::AT_AddressSpace; 3205 case AttributedType::attr_regparm: 3206 return AttributeList::AT_Regparm; 3207 case AttributedType::attr_vector_size: 3208 return AttributeList::AT_VectorSize; 3209 case AttributedType::attr_neon_vector_type: 3210 return AttributeList::AT_NeonVectorType; 3211 case AttributedType::attr_neon_polyvector_type: 3212 return AttributeList::AT_NeonPolyVectorType; 3213 case AttributedType::attr_objc_gc: 3214 return AttributeList::AT_ObjCGC; 3215 case AttributedType::attr_objc_ownership: 3216 return AttributeList::AT_ObjCOwnership; 3217 case AttributedType::attr_noreturn: 3218 return AttributeList::AT_NoReturn; 3219 case AttributedType::attr_cdecl: 3220 return AttributeList::AT_CDecl; 3221 case AttributedType::attr_fastcall: 3222 return AttributeList::AT_FastCall; 3223 case AttributedType::attr_stdcall: 3224 return AttributeList::AT_StdCall; 3225 case AttributedType::attr_thiscall: 3226 return AttributeList::AT_ThisCall; 3227 case AttributedType::attr_pascal: 3228 return AttributeList::AT_Pascal; 3229 case AttributedType::attr_pcs: 3230 return AttributeList::AT_Pcs; 3231 case AttributedType::attr_pnaclcall: 3232 return AttributeList::AT_PnaclCall; 3233 case AttributedType::attr_inteloclbicc: 3234 return AttributeList::AT_IntelOclBicc; 3235 } 3236 llvm_unreachable("unexpected attribute kind!"); 3237} 3238 3239static void fillAttributedTypeLoc(AttributedTypeLoc TL, 3240 const AttributeList *attrs) { 3241 AttributedType::Kind kind = TL.getAttrKind(); 3242 3243 assert(attrs && "no type attributes in the expected location!"); 3244 AttributeList::Kind parsedKind = getAttrListKind(kind); 3245 while (attrs->getKind() != parsedKind) { 3246 attrs = attrs->getNext(); 3247 assert(attrs && "no matching attribute in expected location!"); 3248 } 3249 3250 TL.setAttrNameLoc(attrs->getLoc()); 3251 if (TL.hasAttrExprOperand()) 3252 TL.setAttrExprOperand(attrs->getArg(0)); 3253 else if (TL.hasAttrEnumOperand()) 3254 TL.setAttrEnumOperandLoc(attrs->getParameterLoc()); 3255 3256 // FIXME: preserve this information to here. 3257 if (TL.hasAttrOperand()) 3258 TL.setAttrOperandParensRange(SourceRange()); 3259} 3260 3261namespace { 3262 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 3263 ASTContext &Context; 3264 const DeclSpec &DS; 3265 3266 public: 3267 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 3268 : Context(Context), DS(DS) {} 3269 3270 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 3271 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 3272 Visit(TL.getModifiedLoc()); 3273 } 3274 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 3275 Visit(TL.getUnqualifiedLoc()); 3276 } 3277 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 3278 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 3279 } 3280 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 3281 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 3282 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 3283 // addition field. What we have is good enough for dispay of location 3284 // of 'fixit' on interface name. 3285 TL.setNameEndLoc(DS.getLocEnd()); 3286 } 3287 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 3288 // Handle the base type, which might not have been written explicitly. 3289 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 3290 TL.setHasBaseTypeAsWritten(false); 3291 TL.getBaseLoc().initialize(Context, SourceLocation()); 3292 } else { 3293 TL.setHasBaseTypeAsWritten(true); 3294 Visit(TL.getBaseLoc()); 3295 } 3296 3297 // Protocol qualifiers. 3298 if (DS.getProtocolQualifiers()) { 3299 assert(TL.getNumProtocols() > 0); 3300 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 3301 TL.setLAngleLoc(DS.getProtocolLAngleLoc()); 3302 TL.setRAngleLoc(DS.getSourceRange().getEnd()); 3303 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i) 3304 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]); 3305 } else { 3306 assert(TL.getNumProtocols() == 0); 3307 TL.setLAngleLoc(SourceLocation()); 3308 TL.setRAngleLoc(SourceLocation()); 3309 } 3310 } 3311 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 3312 TL.setStarLoc(SourceLocation()); 3313 Visit(TL.getPointeeLoc()); 3314 } 3315 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 3316 TypeSourceInfo *TInfo = 0; 3317 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3318 3319 // If we got no declarator info from previous Sema routines, 3320 // just fill with the typespec loc. 3321 if (!TInfo) { 3322 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 3323 return; 3324 } 3325 3326 TypeLoc OldTL = TInfo->getTypeLoc(); 3327 if (TInfo->getType()->getAs<ElaboratedType>()) { 3328 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 3329 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 3330 .castAs<TemplateSpecializationTypeLoc>(); 3331 TL.copy(NamedTL); 3332 } 3333 else 3334 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 3335 } 3336 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 3337 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 3338 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 3339 TL.setParensRange(DS.getTypeofParensRange()); 3340 } 3341 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 3342 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 3343 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 3344 TL.setParensRange(DS.getTypeofParensRange()); 3345 assert(DS.getRepAsType()); 3346 TypeSourceInfo *TInfo = 0; 3347 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3348 TL.setUnderlyingTInfo(TInfo); 3349 } 3350 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 3351 // FIXME: This holds only because we only have one unary transform. 3352 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 3353 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 3354 TL.setParensRange(DS.getTypeofParensRange()); 3355 assert(DS.getRepAsType()); 3356 TypeSourceInfo *TInfo = 0; 3357 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3358 TL.setUnderlyingTInfo(TInfo); 3359 } 3360 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 3361 // By default, use the source location of the type specifier. 3362 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 3363 if (TL.needsExtraLocalData()) { 3364 // Set info for the written builtin specifiers. 3365 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 3366 // Try to have a meaningful source location. 3367 if (TL.getWrittenSignSpec() != TSS_unspecified) 3368 // Sign spec loc overrides the others (e.g., 'unsigned long'). 3369 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 3370 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 3371 // Width spec loc overrides type spec loc (e.g., 'short int'). 3372 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 3373 } 3374 } 3375 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 3376 ElaboratedTypeKeyword Keyword 3377 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 3378 if (DS.getTypeSpecType() == TST_typename) { 3379 TypeSourceInfo *TInfo = 0; 3380 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3381 if (TInfo) { 3382 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 3383 return; 3384 } 3385 } 3386 TL.setElaboratedKeywordLoc(Keyword != ETK_None 3387 ? DS.getTypeSpecTypeLoc() 3388 : SourceLocation()); 3389 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 3390 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3391 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 3392 } 3393 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 3394 assert(DS.getTypeSpecType() == TST_typename); 3395 TypeSourceInfo *TInfo = 0; 3396 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3397 assert(TInfo); 3398 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 3399 } 3400 void VisitDependentTemplateSpecializationTypeLoc( 3401 DependentTemplateSpecializationTypeLoc TL) { 3402 assert(DS.getTypeSpecType() == TST_typename); 3403 TypeSourceInfo *TInfo = 0; 3404 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3405 assert(TInfo); 3406 TL.copy( 3407 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 3408 } 3409 void VisitTagTypeLoc(TagTypeLoc TL) { 3410 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 3411 } 3412 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 3413 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 3414 // or an _Atomic qualifier. 3415 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 3416 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 3417 TL.setParensRange(DS.getTypeofParensRange()); 3418 3419 TypeSourceInfo *TInfo = 0; 3420 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3421 assert(TInfo); 3422 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 3423 } else { 3424 TL.setKWLoc(DS.getAtomicSpecLoc()); 3425 // No parens, to indicate this was spelled as an _Atomic qualifier. 3426 TL.setParensRange(SourceRange()); 3427 Visit(TL.getValueLoc()); 3428 } 3429 } 3430 3431 void VisitTypeLoc(TypeLoc TL) { 3432 // FIXME: add other typespec types and change this to an assert. 3433 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 3434 } 3435 }; 3436 3437 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 3438 ASTContext &Context; 3439 const DeclaratorChunk &Chunk; 3440 3441 public: 3442 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 3443 : Context(Context), Chunk(Chunk) {} 3444 3445 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 3446 llvm_unreachable("qualified type locs not expected here!"); 3447 } 3448 3449 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 3450 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 3451 } 3452 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 3453 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 3454 TL.setCaretLoc(Chunk.Loc); 3455 } 3456 void VisitPointerTypeLoc(PointerTypeLoc TL) { 3457 assert(Chunk.Kind == DeclaratorChunk::Pointer); 3458 TL.setStarLoc(Chunk.Loc); 3459 } 3460 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 3461 assert(Chunk.Kind == DeclaratorChunk::Pointer); 3462 TL.setStarLoc(Chunk.Loc); 3463 } 3464 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 3465 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 3466 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 3467 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 3468 3469 const Type* ClsTy = TL.getClass(); 3470 QualType ClsQT = QualType(ClsTy, 0); 3471 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 3472 // Now copy source location info into the type loc component. 3473 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 3474 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 3475 case NestedNameSpecifier::Identifier: 3476 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 3477 { 3478 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 3479 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 3480 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 3481 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 3482 } 3483 break; 3484 3485 case NestedNameSpecifier::TypeSpec: 3486 case NestedNameSpecifier::TypeSpecWithTemplate: 3487 if (isa<ElaboratedType>(ClsTy)) { 3488 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 3489 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 3490 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 3491 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 3492 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 3493 } else { 3494 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 3495 } 3496 break; 3497 3498 case NestedNameSpecifier::Namespace: 3499 case NestedNameSpecifier::NamespaceAlias: 3500 case NestedNameSpecifier::Global: 3501 llvm_unreachable("Nested-name-specifier must name a type"); 3502 } 3503 3504 // Finally fill in MemberPointerLocInfo fields. 3505 TL.setStarLoc(Chunk.Loc); 3506 TL.setClassTInfo(ClsTInfo); 3507 } 3508 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 3509 assert(Chunk.Kind == DeclaratorChunk::Reference); 3510 // 'Amp' is misleading: this might have been originally 3511 /// spelled with AmpAmp. 3512 TL.setAmpLoc(Chunk.Loc); 3513 } 3514 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 3515 assert(Chunk.Kind == DeclaratorChunk::Reference); 3516 assert(!Chunk.Ref.LValueRef); 3517 TL.setAmpAmpLoc(Chunk.Loc); 3518 } 3519 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 3520 assert(Chunk.Kind == DeclaratorChunk::Array); 3521 TL.setLBracketLoc(Chunk.Loc); 3522 TL.setRBracketLoc(Chunk.EndLoc); 3523 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 3524 } 3525 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 3526 assert(Chunk.Kind == DeclaratorChunk::Function); 3527 TL.setLocalRangeBegin(Chunk.Loc); 3528 TL.setLocalRangeEnd(Chunk.EndLoc); 3529 3530 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 3531 TL.setLParenLoc(FTI.getLParenLoc()); 3532 TL.setRParenLoc(FTI.getRParenLoc()); 3533 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) { 3534 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 3535 TL.setArg(tpi++, Param); 3536 } 3537 // FIXME: exception specs 3538 } 3539 void VisitParenTypeLoc(ParenTypeLoc TL) { 3540 assert(Chunk.Kind == DeclaratorChunk::Paren); 3541 TL.setLParenLoc(Chunk.Loc); 3542 TL.setRParenLoc(Chunk.EndLoc); 3543 } 3544 3545 void VisitTypeLoc(TypeLoc TL) { 3546 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 3547 } 3548 }; 3549} 3550 3551static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 3552 SourceLocation Loc; 3553 switch (Chunk.Kind) { 3554 case DeclaratorChunk::Function: 3555 case DeclaratorChunk::Array: 3556 case DeclaratorChunk::Paren: 3557 llvm_unreachable("cannot be _Atomic qualified"); 3558 3559 case DeclaratorChunk::Pointer: 3560 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); 3561 break; 3562 3563 case DeclaratorChunk::BlockPointer: 3564 case DeclaratorChunk::Reference: 3565 case DeclaratorChunk::MemberPointer: 3566 // FIXME: Provide a source location for the _Atomic keyword. 3567 break; 3568 } 3569 3570 ATL.setKWLoc(Loc); 3571 ATL.setParensRange(SourceRange()); 3572} 3573 3574/// \brief Create and instantiate a TypeSourceInfo with type source information. 3575/// 3576/// \param T QualType referring to the type as written in source code. 3577/// 3578/// \param ReturnTypeInfo For declarators whose return type does not show 3579/// up in the normal place in the declaration specifiers (such as a C++ 3580/// conversion function), this pointer will refer to a type source information 3581/// for that return type. 3582TypeSourceInfo * 3583Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 3584 TypeSourceInfo *ReturnTypeInfo) { 3585 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 3586 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 3587 3588 // Handle parameter packs whose type is a pack expansion. 3589 if (isa<PackExpansionType>(T)) { 3590 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 3591 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 3592 } 3593 3594 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3595 // An AtomicTypeLoc might be produced by an atomic qualifier in this 3596 // declarator chunk. 3597 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 3598 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 3599 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 3600 } 3601 3602 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 3603 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs()); 3604 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 3605 } 3606 3607 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 3608 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 3609 } 3610 3611 // If we have different source information for the return type, use 3612 // that. This really only applies to C++ conversion functions. 3613 if (ReturnTypeInfo) { 3614 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 3615 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 3616 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 3617 } else { 3618 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 3619 } 3620 3621 return TInfo; 3622} 3623 3624/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 3625ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 3626 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 3627 // and Sema during declaration parsing. Try deallocating/caching them when 3628 // it's appropriate, instead of allocating them and keeping them around. 3629 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 3630 TypeAlignment); 3631 new (LocT) LocInfoType(T, TInfo); 3632 assert(LocT->getTypeClass() != T->getTypeClass() && 3633 "LocInfoType's TypeClass conflicts with an existing Type class"); 3634 return ParsedType::make(QualType(LocT, 0)); 3635} 3636 3637void LocInfoType::getAsStringInternal(std::string &Str, 3638 const PrintingPolicy &Policy) const { 3639 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 3640 " was used directly instead of getting the QualType through" 3641 " GetTypeFromParser"); 3642} 3643 3644TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 3645 // C99 6.7.6: Type names have no identifier. This is already validated by 3646 // the parser. 3647 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 3648 3649 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3650 QualType T = TInfo->getType(); 3651 if (D.isInvalidType()) 3652 return true; 3653 3654 // Make sure there are no unused decl attributes on the declarator. 3655 // We don't want to do this for ObjC parameters because we're going 3656 // to apply them to the actual parameter declaration. 3657 // Likewise, we don't want to do this for alias declarations, because 3658 // we are actually going to build a declaration from this eventually. 3659 if (D.getContext() != Declarator::ObjCParameterContext && 3660 D.getContext() != Declarator::AliasDeclContext && 3661 D.getContext() != Declarator::AliasTemplateContext) 3662 checkUnusedDeclAttributes(D); 3663 3664 if (getLangOpts().CPlusPlus) { 3665 // Check that there are no default arguments (C++ only). 3666 CheckExtraCXXDefaultArguments(D); 3667 } 3668 3669 return CreateParsedType(T, TInfo); 3670} 3671 3672ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 3673 QualType T = Context.getObjCInstanceType(); 3674 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 3675 return CreateParsedType(T, TInfo); 3676} 3677 3678 3679//===----------------------------------------------------------------------===// 3680// Type Attribute Processing 3681//===----------------------------------------------------------------------===// 3682 3683/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 3684/// specified type. The attribute contains 1 argument, the id of the address 3685/// space for the type. 3686static void HandleAddressSpaceTypeAttribute(QualType &Type, 3687 const AttributeList &Attr, Sema &S){ 3688 3689 // If this type is already address space qualified, reject it. 3690 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 3691 // qualifiers for two or more different address spaces." 3692 if (Type.getAddressSpace()) { 3693 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 3694 Attr.setInvalid(); 3695 return; 3696 } 3697 3698 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 3699 // qualified by an address-space qualifier." 3700 if (Type->isFunctionType()) { 3701 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 3702 Attr.setInvalid(); 3703 return; 3704 } 3705 3706 // Check the attribute arguments. 3707 if (Attr.getNumArgs() != 1) { 3708 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 3709 Attr.setInvalid(); 3710 return; 3711 } 3712 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 3713 llvm::APSInt addrSpace(32); 3714 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 3715 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 3716 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 3717 << ASArgExpr->getSourceRange(); 3718 Attr.setInvalid(); 3719 return; 3720 } 3721 3722 // Bounds checking. 3723 if (addrSpace.isSigned()) { 3724 if (addrSpace.isNegative()) { 3725 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 3726 << ASArgExpr->getSourceRange(); 3727 Attr.setInvalid(); 3728 return; 3729 } 3730 addrSpace.setIsSigned(false); 3731 } 3732 llvm::APSInt max(addrSpace.getBitWidth()); 3733 max = Qualifiers::MaxAddressSpace; 3734 if (addrSpace > max) { 3735 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 3736 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange(); 3737 Attr.setInvalid(); 3738 return; 3739 } 3740 3741 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 3742 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 3743} 3744 3745/// Does this type have a "direct" ownership qualifier? That is, 3746/// is it written like "__strong id", as opposed to something like 3747/// "typeof(foo)", where that happens to be strong? 3748static bool hasDirectOwnershipQualifier(QualType type) { 3749 // Fast path: no qualifier at all. 3750 assert(type.getQualifiers().hasObjCLifetime()); 3751 3752 while (true) { 3753 // __strong id 3754 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 3755 if (attr->getAttrKind() == AttributedType::attr_objc_ownership) 3756 return true; 3757 3758 type = attr->getModifiedType(); 3759 3760 // X *__strong (...) 3761 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 3762 type = paren->getInnerType(); 3763 3764 // That's it for things we want to complain about. In particular, 3765 // we do not want to look through typedefs, typeof(expr), 3766 // typeof(type), or any other way that the type is somehow 3767 // abstracted. 3768 } else { 3769 3770 return false; 3771 } 3772 } 3773} 3774 3775/// handleObjCOwnershipTypeAttr - Process an objc_ownership 3776/// attribute on the specified type. 3777/// 3778/// Returns 'true' if the attribute was handled. 3779static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 3780 AttributeList &attr, 3781 QualType &type) { 3782 bool NonObjCPointer = false; 3783 3784 if (!type->isDependentType()) { 3785 if (const PointerType *ptr = type->getAs<PointerType>()) { 3786 QualType pointee = ptr->getPointeeType(); 3787 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 3788 return false; 3789 // It is important not to lose the source info that there was an attribute 3790 // applied to non-objc pointer. We will create an attributed type but 3791 // its type will be the same as the original type. 3792 NonObjCPointer = true; 3793 } else if (!type->isObjCRetainableType()) { 3794 return false; 3795 } 3796 3797 // Don't accept an ownership attribute in the declspec if it would 3798 // just be the return type of a block pointer. 3799 if (state.isProcessingDeclSpec()) { 3800 Declarator &D = state.getDeclarator(); 3801 if (maybeMovePastReturnType(D, D.getNumTypeObjects())) 3802 return false; 3803 } 3804 } 3805 3806 Sema &S = state.getSema(); 3807 SourceLocation AttrLoc = attr.getLoc(); 3808 if (AttrLoc.isMacroID()) 3809 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; 3810 3811 if (!attr.getParameterName()) { 3812 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string) 3813 << "objc_ownership" << 1; 3814 attr.setInvalid(); 3815 return true; 3816 } 3817 3818 // Consume lifetime attributes without further comment outside of 3819 // ARC mode. 3820 if (!S.getLangOpts().ObjCAutoRefCount) 3821 return true; 3822 3823 Qualifiers::ObjCLifetime lifetime; 3824 if (attr.getParameterName()->isStr("none")) 3825 lifetime = Qualifiers::OCL_ExplicitNone; 3826 else if (attr.getParameterName()->isStr("strong")) 3827 lifetime = Qualifiers::OCL_Strong; 3828 else if (attr.getParameterName()->isStr("weak")) 3829 lifetime = Qualifiers::OCL_Weak; 3830 else if (attr.getParameterName()->isStr("autoreleasing")) 3831 lifetime = Qualifiers::OCL_Autoreleasing; 3832 else { 3833 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 3834 << "objc_ownership" << attr.getParameterName(); 3835 attr.setInvalid(); 3836 return true; 3837 } 3838 3839 SplitQualType underlyingType = type.split(); 3840 3841 // Check for redundant/conflicting ownership qualifiers. 3842 if (Qualifiers::ObjCLifetime previousLifetime 3843 = type.getQualifiers().getObjCLifetime()) { 3844 // If it's written directly, that's an error. 3845 if (hasDirectOwnershipQualifier(type)) { 3846 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 3847 << type; 3848 return true; 3849 } 3850 3851 // Otherwise, if the qualifiers actually conflict, pull sugar off 3852 // until we reach a type that is directly qualified. 3853 if (previousLifetime != lifetime) { 3854 // This should always terminate: the canonical type is 3855 // qualified, so some bit of sugar must be hiding it. 3856 while (!underlyingType.Quals.hasObjCLifetime()) { 3857 underlyingType = underlyingType.getSingleStepDesugaredType(); 3858 } 3859 underlyingType.Quals.removeObjCLifetime(); 3860 } 3861 } 3862 3863 underlyingType.Quals.addObjCLifetime(lifetime); 3864 3865 if (NonObjCPointer) { 3866 StringRef name = attr.getName()->getName(); 3867 switch (lifetime) { 3868 case Qualifiers::OCL_None: 3869 case Qualifiers::OCL_ExplicitNone: 3870 break; 3871 case Qualifiers::OCL_Strong: name = "__strong"; break; 3872 case Qualifiers::OCL_Weak: name = "__weak"; break; 3873 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 3874 } 3875 S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type) 3876 << name << type; 3877 } 3878 3879 QualType origType = type; 3880 if (!NonObjCPointer) 3881 type = S.Context.getQualifiedType(underlyingType); 3882 3883 // If we have a valid source location for the attribute, use an 3884 // AttributedType instead. 3885 if (AttrLoc.isValid()) 3886 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 3887 origType, type); 3888 3889 // Forbid __weak if the runtime doesn't support it. 3890 if (lifetime == Qualifiers::OCL_Weak && 3891 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) { 3892 3893 // Actually, delay this until we know what we're parsing. 3894 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 3895 S.DelayedDiagnostics.add( 3896 sema::DelayedDiagnostic::makeForbiddenType( 3897 S.getSourceManager().getExpansionLoc(AttrLoc), 3898 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0)); 3899 } else { 3900 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime); 3901 } 3902 3903 attr.setInvalid(); 3904 return true; 3905 } 3906 3907 // Forbid __weak for class objects marked as 3908 // objc_arc_weak_reference_unavailable 3909 if (lifetime == Qualifiers::OCL_Weak) { 3910 if (const ObjCObjectPointerType *ObjT = 3911 type->getAs<ObjCObjectPointerType>()) { 3912 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 3913 if (Class->isArcWeakrefUnavailable()) { 3914 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 3915 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 3916 diag::note_class_declared); 3917 } 3918 } 3919 } 3920 } 3921 3922 return true; 3923} 3924 3925/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 3926/// attribute on the specified type. Returns true to indicate that 3927/// the attribute was handled, false to indicate that the type does 3928/// not permit the attribute. 3929static bool handleObjCGCTypeAttr(TypeProcessingState &state, 3930 AttributeList &attr, 3931 QualType &type) { 3932 Sema &S = state.getSema(); 3933 3934 // Delay if this isn't some kind of pointer. 3935 if (!type->isPointerType() && 3936 !type->isObjCObjectPointerType() && 3937 !type->isBlockPointerType()) 3938 return false; 3939 3940 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 3941 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 3942 attr.setInvalid(); 3943 return true; 3944 } 3945 3946 // Check the attribute arguments. 3947 if (!attr.getParameterName()) { 3948 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string) 3949 << "objc_gc" << 1; 3950 attr.setInvalid(); 3951 return true; 3952 } 3953 Qualifiers::GC GCAttr; 3954 if (attr.getNumArgs() != 0) { 3955 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 3956 attr.setInvalid(); 3957 return true; 3958 } 3959 if (attr.getParameterName()->isStr("weak")) 3960 GCAttr = Qualifiers::Weak; 3961 else if (attr.getParameterName()->isStr("strong")) 3962 GCAttr = Qualifiers::Strong; 3963 else { 3964 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 3965 << "objc_gc" << attr.getParameterName(); 3966 attr.setInvalid(); 3967 return true; 3968 } 3969 3970 QualType origType = type; 3971 type = S.Context.getObjCGCQualType(origType, GCAttr); 3972 3973 // Make an attributed type to preserve the source information. 3974 if (attr.getLoc().isValid()) 3975 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 3976 origType, type); 3977 3978 return true; 3979} 3980 3981namespace { 3982 /// A helper class to unwrap a type down to a function for the 3983 /// purposes of applying attributes there. 3984 /// 3985 /// Use: 3986 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 3987 /// if (unwrapped.isFunctionType()) { 3988 /// const FunctionType *fn = unwrapped.get(); 3989 /// // change fn somehow 3990 /// T = unwrapped.wrap(fn); 3991 /// } 3992 struct FunctionTypeUnwrapper { 3993 enum WrapKind { 3994 Desugar, 3995 Parens, 3996 Pointer, 3997 BlockPointer, 3998 Reference, 3999 MemberPointer 4000 }; 4001 4002 QualType Original; 4003 const FunctionType *Fn; 4004 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 4005 4006 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 4007 while (true) { 4008 const Type *Ty = T.getTypePtr(); 4009 if (isa<FunctionType>(Ty)) { 4010 Fn = cast<FunctionType>(Ty); 4011 return; 4012 } else if (isa<ParenType>(Ty)) { 4013 T = cast<ParenType>(Ty)->getInnerType(); 4014 Stack.push_back(Parens); 4015 } else if (isa<PointerType>(Ty)) { 4016 T = cast<PointerType>(Ty)->getPointeeType(); 4017 Stack.push_back(Pointer); 4018 } else if (isa<BlockPointerType>(Ty)) { 4019 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4020 Stack.push_back(BlockPointer); 4021 } else if (isa<MemberPointerType>(Ty)) { 4022 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4023 Stack.push_back(MemberPointer); 4024 } else if (isa<ReferenceType>(Ty)) { 4025 T = cast<ReferenceType>(Ty)->getPointeeType(); 4026 Stack.push_back(Reference); 4027 } else { 4028 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 4029 if (Ty == DTy) { 4030 Fn = 0; 4031 return; 4032 } 4033 4034 T = QualType(DTy, 0); 4035 Stack.push_back(Desugar); 4036 } 4037 } 4038 } 4039 4040 bool isFunctionType() const { return (Fn != 0); } 4041 const FunctionType *get() const { return Fn; } 4042 4043 QualType wrap(Sema &S, const FunctionType *New) { 4044 // If T wasn't modified from the unwrapped type, do nothing. 4045 if (New == get()) return Original; 4046 4047 Fn = New; 4048 return wrap(S.Context, Original, 0); 4049 } 4050 4051 private: 4052 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 4053 if (I == Stack.size()) 4054 return C.getQualifiedType(Fn, Old.getQualifiers()); 4055 4056 // Build up the inner type, applying the qualifiers from the old 4057 // type to the new type. 4058 SplitQualType SplitOld = Old.split(); 4059 4060 // As a special case, tail-recurse if there are no qualifiers. 4061 if (SplitOld.Quals.empty()) 4062 return wrap(C, SplitOld.Ty, I); 4063 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 4064 } 4065 4066 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 4067 if (I == Stack.size()) return QualType(Fn, 0); 4068 4069 switch (static_cast<WrapKind>(Stack[I++])) { 4070 case Desugar: 4071 // This is the point at which we potentially lose source 4072 // information. 4073 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 4074 4075 case Parens: { 4076 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 4077 return C.getParenType(New); 4078 } 4079 4080 case Pointer: { 4081 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 4082 return C.getPointerType(New); 4083 } 4084 4085 case BlockPointer: { 4086 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 4087 return C.getBlockPointerType(New); 4088 } 4089 4090 case MemberPointer: { 4091 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 4092 QualType New = wrap(C, OldMPT->getPointeeType(), I); 4093 return C.getMemberPointerType(New, OldMPT->getClass()); 4094 } 4095 4096 case Reference: { 4097 const ReferenceType *OldRef = cast<ReferenceType>(Old); 4098 QualType New = wrap(C, OldRef->getPointeeType(), I); 4099 if (isa<LValueReferenceType>(OldRef)) 4100 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 4101 else 4102 return C.getRValueReferenceType(New); 4103 } 4104 } 4105 4106 llvm_unreachable("unknown wrapping kind"); 4107 } 4108 }; 4109} 4110 4111/// Process an individual function attribute. Returns true to 4112/// indicate that the attribute was handled, false if it wasn't. 4113static bool handleFunctionTypeAttr(TypeProcessingState &state, 4114 AttributeList &attr, 4115 QualType &type) { 4116 Sema &S = state.getSema(); 4117 4118 FunctionTypeUnwrapper unwrapped(S, type); 4119 4120 if (attr.getKind() == AttributeList::AT_NoReturn) { 4121 if (S.CheckNoReturnAttr(attr)) 4122 return true; 4123 4124 // Delay if this is not a function type. 4125 if (!unwrapped.isFunctionType()) 4126 return false; 4127 4128 // Otherwise we can process right away. 4129 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 4130 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4131 return true; 4132 } 4133 4134 // ns_returns_retained is not always a type attribute, but if we got 4135 // here, we're treating it as one right now. 4136 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) { 4137 assert(S.getLangOpts().ObjCAutoRefCount && 4138 "ns_returns_retained treated as type attribute in non-ARC"); 4139 if (attr.getNumArgs()) return true; 4140 4141 // Delay if this is not a function type. 4142 if (!unwrapped.isFunctionType()) 4143 return false; 4144 4145 FunctionType::ExtInfo EI 4146 = unwrapped.get()->getExtInfo().withProducesResult(true); 4147 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4148 return true; 4149 } 4150 4151 if (attr.getKind() == AttributeList::AT_Regparm) { 4152 unsigned value; 4153 if (S.CheckRegparmAttr(attr, value)) 4154 return true; 4155 4156 // Delay if this is not a function type. 4157 if (!unwrapped.isFunctionType()) 4158 return false; 4159 4160 // Diagnose regparm with fastcall. 4161 const FunctionType *fn = unwrapped.get(); 4162 CallingConv CC = fn->getCallConv(); 4163 if (CC == CC_X86FastCall) { 4164 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4165 << FunctionType::getNameForCallConv(CC) 4166 << "regparm"; 4167 attr.setInvalid(); 4168 return true; 4169 } 4170 4171 FunctionType::ExtInfo EI = 4172 unwrapped.get()->getExtInfo().withRegParm(value); 4173 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4174 return true; 4175 } 4176 4177 // Delay if the type didn't work out to a function. 4178 if (!unwrapped.isFunctionType()) return false; 4179 4180 // Otherwise, a calling convention. 4181 CallingConv CC; 4182 if (S.CheckCallingConvAttr(attr, CC)) 4183 return true; 4184 4185 const FunctionType *fn = unwrapped.get(); 4186 CallingConv CCOld = fn->getCallConv(); 4187 if (S.Context.getCanonicalCallConv(CC) == 4188 S.Context.getCanonicalCallConv(CCOld)) { 4189 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC); 4190 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4191 return true; 4192 } 4193 4194 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) { 4195 // Should we diagnose reapplications of the same convention? 4196 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4197 << FunctionType::getNameForCallConv(CC) 4198 << FunctionType::getNameForCallConv(CCOld); 4199 attr.setInvalid(); 4200 return true; 4201 } 4202 4203 // Diagnose the use of X86 fastcall on varargs or unprototyped functions. 4204 if (CC == CC_X86FastCall) { 4205 if (isa<FunctionNoProtoType>(fn)) { 4206 S.Diag(attr.getLoc(), diag::err_cconv_knr) 4207 << FunctionType::getNameForCallConv(CC); 4208 attr.setInvalid(); 4209 return true; 4210 } 4211 4212 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn); 4213 if (FnP->isVariadic()) { 4214 S.Diag(attr.getLoc(), diag::err_cconv_varargs) 4215 << FunctionType::getNameForCallConv(CC); 4216 attr.setInvalid(); 4217 return true; 4218 } 4219 4220 // Also diagnose fastcall with regparm. 4221 if (fn->getHasRegParm()) { 4222 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4223 << "regparm" 4224 << FunctionType::getNameForCallConv(CC); 4225 attr.setInvalid(); 4226 return true; 4227 } 4228 } 4229 4230 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 4231 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4232 return true; 4233} 4234 4235/// Handle OpenCL image access qualifiers: read_only, write_only, read_write 4236static void HandleOpenCLImageAccessAttribute(QualType& CurType, 4237 const AttributeList &Attr, 4238 Sema &S) { 4239 // Check the attribute arguments. 4240 if (Attr.getNumArgs() != 1) { 4241 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 4242 Attr.setInvalid(); 4243 return; 4244 } 4245 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 4246 llvm::APSInt arg(32); 4247 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 4248 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) { 4249 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 4250 << "opencl_image_access" << sizeExpr->getSourceRange(); 4251 Attr.setInvalid(); 4252 return; 4253 } 4254 unsigned iarg = static_cast<unsigned>(arg.getZExtValue()); 4255 switch (iarg) { 4256 case CLIA_read_only: 4257 case CLIA_write_only: 4258 case CLIA_read_write: 4259 // Implemented in a separate patch 4260 break; 4261 default: 4262 // Implemented in a separate patch 4263 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 4264 << sizeExpr->getSourceRange(); 4265 Attr.setInvalid(); 4266 break; 4267 } 4268} 4269 4270/// HandleVectorSizeAttribute - this attribute is only applicable to integral 4271/// and float scalars, although arrays, pointers, and function return values are 4272/// allowed in conjunction with this construct. Aggregates with this attribute 4273/// are invalid, even if they are of the same size as a corresponding scalar. 4274/// The raw attribute should contain precisely 1 argument, the vector size for 4275/// the variable, measured in bytes. If curType and rawAttr are well formed, 4276/// this routine will return a new vector type. 4277static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 4278 Sema &S) { 4279 // Check the attribute arguments. 4280 if (Attr.getNumArgs() != 1) { 4281 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 4282 Attr.setInvalid(); 4283 return; 4284 } 4285 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 4286 llvm::APSInt vecSize(32); 4287 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 4288 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 4289 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 4290 << "vector_size" << sizeExpr->getSourceRange(); 4291 Attr.setInvalid(); 4292 return; 4293 } 4294 // the base type must be integer or float, and can't already be a vector. 4295 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) { 4296 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 4297 Attr.setInvalid(); 4298 return; 4299 } 4300 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 4301 // vecSize is specified in bytes - convert to bits. 4302 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 4303 4304 // the vector size needs to be an integral multiple of the type size. 4305 if (vectorSize % typeSize) { 4306 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 4307 << sizeExpr->getSourceRange(); 4308 Attr.setInvalid(); 4309 return; 4310 } 4311 if (vectorSize == 0) { 4312 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 4313 << sizeExpr->getSourceRange(); 4314 Attr.setInvalid(); 4315 return; 4316 } 4317 4318 // Success! Instantiate the vector type, the number of elements is > 0, and 4319 // not required to be a power of 2, unlike GCC. 4320 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 4321 VectorType::GenericVector); 4322} 4323 4324/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 4325/// a type. 4326static void HandleExtVectorTypeAttr(QualType &CurType, 4327 const AttributeList &Attr, 4328 Sema &S) { 4329 Expr *sizeExpr; 4330 4331 // Special case where the argument is a template id. 4332 if (Attr.getParameterName()) { 4333 CXXScopeSpec SS; 4334 SourceLocation TemplateKWLoc; 4335 UnqualifiedId id; 4336 id.setIdentifier(Attr.getParameterName(), Attr.getLoc()); 4337 4338 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 4339 id, false, false); 4340 if (Size.isInvalid()) 4341 return; 4342 4343 sizeExpr = Size.get(); 4344 } else { 4345 // check the attribute arguments. 4346 if (Attr.getNumArgs() != 1) { 4347 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 4348 return; 4349 } 4350 sizeExpr = Attr.getArg(0); 4351 } 4352 4353 // Create the vector type. 4354 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 4355 if (!T.isNull()) 4356 CurType = T; 4357} 4358 4359/// HandleNeonVectorTypeAttr - The "neon_vector_type" and 4360/// "neon_polyvector_type" attributes are used to create vector types that 4361/// are mangled according to ARM's ABI. Otherwise, these types are identical 4362/// to those created with the "vector_size" attribute. Unlike "vector_size" 4363/// the argument to these Neon attributes is the number of vector elements, 4364/// not the vector size in bytes. The vector width and element type must 4365/// match one of the standard Neon vector types. 4366static void HandleNeonVectorTypeAttr(QualType& CurType, 4367 const AttributeList &Attr, Sema &S, 4368 VectorType::VectorKind VecKind, 4369 const char *AttrName) { 4370 // Check the attribute arguments. 4371 if (Attr.getNumArgs() != 1) { 4372 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 4373 Attr.setInvalid(); 4374 return; 4375 } 4376 // The number of elements must be an ICE. 4377 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0)); 4378 llvm::APSInt numEltsInt(32); 4379 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 4380 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 4381 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 4382 << AttrName << numEltsExpr->getSourceRange(); 4383 Attr.setInvalid(); 4384 return; 4385 } 4386 // Only certain element types are supported for Neon vectors. 4387 const BuiltinType* BTy = CurType->getAs<BuiltinType>(); 4388 if (!BTy || 4389 (VecKind == VectorType::NeonPolyVector && 4390 BTy->getKind() != BuiltinType::SChar && 4391 BTy->getKind() != BuiltinType::Short) || 4392 (BTy->getKind() != BuiltinType::SChar && 4393 BTy->getKind() != BuiltinType::UChar && 4394 BTy->getKind() != BuiltinType::Short && 4395 BTy->getKind() != BuiltinType::UShort && 4396 BTy->getKind() != BuiltinType::Int && 4397 BTy->getKind() != BuiltinType::UInt && 4398 BTy->getKind() != BuiltinType::LongLong && 4399 BTy->getKind() != BuiltinType::ULongLong && 4400 BTy->getKind() != BuiltinType::Float)) { 4401 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType; 4402 Attr.setInvalid(); 4403 return; 4404 } 4405 // The total size of the vector must be 64 or 128 bits. 4406 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 4407 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 4408 unsigned vecSize = typeSize * numElts; 4409 if (vecSize != 64 && vecSize != 128) { 4410 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 4411 Attr.setInvalid(); 4412 return; 4413 } 4414 4415 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 4416} 4417 4418static void processTypeAttrs(TypeProcessingState &state, QualType &type, 4419 TypeAttrLocation TAL, AttributeList *attrs) { 4420 // Scan through and apply attributes to this type where it makes sense. Some 4421 // attributes (such as __address_space__, __vector_size__, etc) apply to the 4422 // type, but others can be present in the type specifiers even though they 4423 // apply to the decl. Here we apply type attributes and ignore the rest. 4424 4425 AttributeList *next; 4426 do { 4427 AttributeList &attr = *attrs; 4428 next = attr.getNext(); 4429 4430 // Skip attributes that were marked to be invalid. 4431 if (attr.isInvalid()) 4432 continue; 4433 4434 if (attr.isCXX11Attribute()) { 4435 // [[gnu::...]] attributes are treated as declaration attributes, so may 4436 // not appertain to a DeclaratorChunk, even if we handle them as type 4437 // attributes. 4438 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) { 4439 if (TAL == TAL_DeclChunk) { 4440 state.getSema().Diag(attr.getLoc(), 4441 diag::warn_cxx11_gnu_attribute_on_type) 4442 << attr.getName(); 4443 continue; 4444 } 4445 } else if (TAL != TAL_DeclChunk) { 4446 // Otherwise, only consider type processing for a C++11 attribute if 4447 // it's actually been applied to a type. 4448 continue; 4449 } 4450 } 4451 4452 // If this is an attribute we can handle, do so now, 4453 // otherwise, add it to the FnAttrs list for rechaining. 4454 switch (attr.getKind()) { 4455 default: 4456 // A C++11 attribute on a declarator chunk must appertain to a type. 4457 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { 4458 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 4459 << attr.getName(); 4460 attr.setUsedAsTypeAttr(); 4461 } 4462 break; 4463 4464 case AttributeList::UnknownAttribute: 4465 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 4466 state.getSema().Diag(attr.getLoc(), 4467 diag::warn_unknown_attribute_ignored) 4468 << attr.getName(); 4469 break; 4470 4471 case AttributeList::IgnoredAttribute: 4472 break; 4473 4474 case AttributeList::AT_MayAlias: 4475 // FIXME: This attribute needs to actually be handled, but if we ignore 4476 // it it breaks large amounts of Linux software. 4477 attr.setUsedAsTypeAttr(); 4478 break; 4479 case AttributeList::AT_AddressSpace: 4480 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 4481 attr.setUsedAsTypeAttr(); 4482 break; 4483 OBJC_POINTER_TYPE_ATTRS_CASELIST: 4484 if (!handleObjCPointerTypeAttr(state, attr, type)) 4485 distributeObjCPointerTypeAttr(state, attr, type); 4486 attr.setUsedAsTypeAttr(); 4487 break; 4488 case AttributeList::AT_VectorSize: 4489 HandleVectorSizeAttr(type, attr, state.getSema()); 4490 attr.setUsedAsTypeAttr(); 4491 break; 4492 case AttributeList::AT_ExtVectorType: 4493 HandleExtVectorTypeAttr(type, attr, state.getSema()); 4494 attr.setUsedAsTypeAttr(); 4495 break; 4496 case AttributeList::AT_NeonVectorType: 4497 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 4498 VectorType::NeonVector, "neon_vector_type"); 4499 attr.setUsedAsTypeAttr(); 4500 break; 4501 case AttributeList::AT_NeonPolyVectorType: 4502 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 4503 VectorType::NeonPolyVector, 4504 "neon_polyvector_type"); 4505 attr.setUsedAsTypeAttr(); 4506 break; 4507 case AttributeList::AT_OpenCLImageAccess: 4508 HandleOpenCLImageAccessAttribute(type, attr, state.getSema()); 4509 attr.setUsedAsTypeAttr(); 4510 break; 4511 4512 case AttributeList::AT_Win64: 4513 case AttributeList::AT_Ptr32: 4514 case AttributeList::AT_Ptr64: 4515 // FIXME: Don't ignore these. We have partial handling for them as 4516 // declaration attributes in SemaDeclAttr.cpp; that should be moved here. 4517 attr.setUsedAsTypeAttr(); 4518 break; 4519 4520 case AttributeList::AT_NSReturnsRetained: 4521 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 4522 break; 4523 // fallthrough into the function attrs 4524 4525 FUNCTION_TYPE_ATTRS_CASELIST: 4526 attr.setUsedAsTypeAttr(); 4527 4528 // Never process function type attributes as part of the 4529 // declaration-specifiers. 4530 if (TAL == TAL_DeclSpec) 4531 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 4532 4533 // Otherwise, handle the possible delays. 4534 else if (!handleFunctionTypeAttr(state, attr, type)) 4535 distributeFunctionTypeAttr(state, attr, type); 4536 break; 4537 } 4538 } while ((attrs = next)); 4539} 4540 4541/// \brief Ensure that the type of the given expression is complete. 4542/// 4543/// This routine checks whether the expression \p E has a complete type. If the 4544/// expression refers to an instantiable construct, that instantiation is 4545/// performed as needed to complete its type. Furthermore 4546/// Sema::RequireCompleteType is called for the expression's type (or in the 4547/// case of a reference type, the referred-to type). 4548/// 4549/// \param E The expression whose type is required to be complete. 4550/// \param Diagnoser The object that will emit a diagnostic if the type is 4551/// incomplete. 4552/// 4553/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 4554/// otherwise. 4555bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){ 4556 QualType T = E->getType(); 4557 4558 // Fast path the case where the type is already complete. 4559 if (!T->isIncompleteType()) 4560 return false; 4561 4562 // Incomplete array types may be completed by the initializer attached to 4563 // their definitions. For static data members of class templates we need to 4564 // instantiate the definition to get this initializer and complete the type. 4565 if (T->isIncompleteArrayType()) { 4566 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4567 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 4568 if (Var->isStaticDataMember() && 4569 Var->getInstantiatedFromStaticDataMember()) { 4570 4571 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 4572 assert(MSInfo && "Missing member specialization information?"); 4573 if (MSInfo->getTemplateSpecializationKind() 4574 != TSK_ExplicitSpecialization) { 4575 // If we don't already have a point of instantiation, this is it. 4576 if (MSInfo->getPointOfInstantiation().isInvalid()) { 4577 MSInfo->setPointOfInstantiation(E->getLocStart()); 4578 4579 // This is a modification of an existing AST node. Notify 4580 // listeners. 4581 if (ASTMutationListener *L = getASTMutationListener()) 4582 L->StaticDataMemberInstantiated(Var); 4583 } 4584 4585 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var); 4586 4587 // Update the type to the newly instantiated definition's type both 4588 // here and within the expression. 4589 if (VarDecl *Def = Var->getDefinition()) { 4590 DRE->setDecl(Def); 4591 T = Def->getType(); 4592 DRE->setType(T); 4593 E->setType(T); 4594 } 4595 } 4596 4597 // We still go on to try to complete the type independently, as it 4598 // may also require instantiations or diagnostics if it remains 4599 // incomplete. 4600 } 4601 } 4602 } 4603 } 4604 4605 // FIXME: Are there other cases which require instantiating something other 4606 // than the type to complete the type of an expression? 4607 4608 // Look through reference types and complete the referred type. 4609 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 4610 T = Ref->getPointeeType(); 4611 4612 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 4613} 4614 4615namespace { 4616 struct TypeDiagnoserDiag : Sema::TypeDiagnoser { 4617 unsigned DiagID; 4618 4619 TypeDiagnoserDiag(unsigned DiagID) 4620 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {} 4621 4622 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 4623 if (Suppressed) return; 4624 S.Diag(Loc, DiagID) << T; 4625 } 4626 }; 4627} 4628 4629bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 4630 TypeDiagnoserDiag Diagnoser(DiagID); 4631 return RequireCompleteExprType(E, Diagnoser); 4632} 4633 4634/// @brief Ensure that the type T is a complete type. 4635/// 4636/// This routine checks whether the type @p T is complete in any 4637/// context where a complete type is required. If @p T is a complete 4638/// type, returns false. If @p T is a class template specialization, 4639/// this routine then attempts to perform class template 4640/// instantiation. If instantiation fails, or if @p T is incomplete 4641/// and cannot be completed, issues the diagnostic @p diag (giving it 4642/// the type @p T) and returns true. 4643/// 4644/// @param Loc The location in the source that the incomplete type 4645/// diagnostic should refer to. 4646/// 4647/// @param T The type that this routine is examining for completeness. 4648/// 4649/// @returns @c true if @p T is incomplete and a diagnostic was emitted, 4650/// @c false otherwise. 4651bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 4652 TypeDiagnoser &Diagnoser) { 4653 // FIXME: Add this assertion to make sure we always get instantiation points. 4654 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 4655 // FIXME: Add this assertion to help us flush out problems with 4656 // checking for dependent types and type-dependent expressions. 4657 // 4658 // assert(!T->isDependentType() && 4659 // "Can't ask whether a dependent type is complete"); 4660 4661 // If we have a complete type, we're done. 4662 NamedDecl *Def = 0; 4663 if (!T->isIncompleteType(&Def)) { 4664 // If we know about the definition but it is not visible, complain. 4665 if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(Def)) { 4666 // Suppress this error outside of a SFINAE context if we've already 4667 // emitted the error once for this type. There's no usefulness in 4668 // repeating the diagnostic. 4669 // FIXME: Add a Fix-It that imports the corresponding module or includes 4670 // the header. 4671 Module *Owner = Def->getOwningModule(); 4672 Diag(Loc, diag::err_module_private_definition) 4673 << T << Owner->getFullModuleName(); 4674 Diag(Def->getLocation(), diag::note_previous_definition); 4675 4676 if (!isSFINAEContext()) { 4677 // Recover by implicitly importing this module. 4678 createImplicitModuleImport(Loc, Owner); 4679 } 4680 } 4681 4682 return false; 4683 } 4684 4685 const TagType *Tag = T->getAs<TagType>(); 4686 const ObjCInterfaceType *IFace = 0; 4687 4688 if (Tag) { 4689 // Avoid diagnosing invalid decls as incomplete. 4690 if (Tag->getDecl()->isInvalidDecl()) 4691 return true; 4692 4693 // Give the external AST source a chance to complete the type. 4694 if (Tag->getDecl()->hasExternalLexicalStorage()) { 4695 Context.getExternalSource()->CompleteType(Tag->getDecl()); 4696 if (!Tag->isIncompleteType()) 4697 return false; 4698 } 4699 } 4700 else if ((IFace = T->getAs<ObjCInterfaceType>())) { 4701 // Avoid diagnosing invalid decls as incomplete. 4702 if (IFace->getDecl()->isInvalidDecl()) 4703 return true; 4704 4705 // Give the external AST source a chance to complete the type. 4706 if (IFace->getDecl()->hasExternalLexicalStorage()) { 4707 Context.getExternalSource()->CompleteType(IFace->getDecl()); 4708 if (!IFace->isIncompleteType()) 4709 return false; 4710 } 4711 } 4712 4713 // If we have a class template specialization or a class member of a 4714 // class template specialization, or an array with known size of such, 4715 // try to instantiate it. 4716 QualType MaybeTemplate = T; 4717 while (const ConstantArrayType *Array 4718 = Context.getAsConstantArrayType(MaybeTemplate)) 4719 MaybeTemplate = Array->getElementType(); 4720 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 4721 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 4722 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 4723 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) 4724 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec, 4725 TSK_ImplicitInstantiation, 4726 /*Complain=*/!Diagnoser.Suppressed); 4727 } else if (CXXRecordDecl *Rec 4728 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 4729 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); 4730 if (!Rec->isBeingDefined() && Pattern) { 4731 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); 4732 assert(MSI && "Missing member specialization information?"); 4733 // This record was instantiated from a class within a template. 4734 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 4735 return InstantiateClass(Loc, Rec, Pattern, 4736 getTemplateInstantiationArgs(Rec), 4737 TSK_ImplicitInstantiation, 4738 /*Complain=*/!Diagnoser.Suppressed); 4739 } 4740 } 4741 } 4742 4743 if (Diagnoser.Suppressed) 4744 return true; 4745 4746 // We have an incomplete type. Produce a diagnostic. 4747 Diagnoser.diagnose(*this, Loc, T); 4748 4749 // If the type was a forward declaration of a class/struct/union 4750 // type, produce a note. 4751 if (Tag && !Tag->getDecl()->isInvalidDecl()) 4752 Diag(Tag->getDecl()->getLocation(), 4753 Tag->isBeingDefined() ? diag::note_type_being_defined 4754 : diag::note_forward_declaration) 4755 << QualType(Tag, 0); 4756 4757 // If the Objective-C class was a forward declaration, produce a note. 4758 if (IFace && !IFace->getDecl()->isInvalidDecl()) 4759 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); 4760 4761 return true; 4762} 4763 4764bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 4765 unsigned DiagID) { 4766 TypeDiagnoserDiag Diagnoser(DiagID); 4767 return RequireCompleteType(Loc, T, Diagnoser); 4768} 4769 4770/// \brief Get diagnostic %select index for tag kind for 4771/// literal type diagnostic message. 4772/// WARNING: Indexes apply to particular diagnostics only! 4773/// 4774/// \returns diagnostic %select index. 4775static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 4776 switch (Tag) { 4777 case TTK_Struct: return 0; 4778 case TTK_Interface: return 1; 4779 case TTK_Class: return 2; 4780 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 4781 } 4782} 4783 4784/// @brief Ensure that the type T is a literal type. 4785/// 4786/// This routine checks whether the type @p T is a literal type. If @p T is an 4787/// incomplete type, an attempt is made to complete it. If @p T is a literal 4788/// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 4789/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 4790/// it the type @p T), along with notes explaining why the type is not a 4791/// literal type, and returns true. 4792/// 4793/// @param Loc The location in the source that the non-literal type 4794/// diagnostic should refer to. 4795/// 4796/// @param T The type that this routine is examining for literalness. 4797/// 4798/// @param Diagnoser Emits a diagnostic if T is not a literal type. 4799/// 4800/// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 4801/// @c false otherwise. 4802bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 4803 TypeDiagnoser &Diagnoser) { 4804 assert(!T->isDependentType() && "type should not be dependent"); 4805 4806 QualType ElemType = Context.getBaseElementType(T); 4807 RequireCompleteType(Loc, ElemType, 0); 4808 4809 if (T->isLiteralType()) 4810 return false; 4811 4812 if (Diagnoser.Suppressed) 4813 return true; 4814 4815 Diagnoser.diagnose(*this, Loc, T); 4816 4817 if (T->isVariableArrayType()) 4818 return true; 4819 4820 const RecordType *RT = ElemType->getAs<RecordType>(); 4821 if (!RT) 4822 return true; 4823 4824 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4825 4826 // A partially-defined class type can't be a literal type, because a literal 4827 // class type must have a trivial destructor (which can't be checked until 4828 // the class definition is complete). 4829 if (!RD->isCompleteDefinition()) { 4830 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T); 4831 return true; 4832 } 4833 4834 // If the class has virtual base classes, then it's not an aggregate, and 4835 // cannot have any constexpr constructors or a trivial default constructor, 4836 // so is non-literal. This is better to diagnose than the resulting absence 4837 // of constexpr constructors. 4838 if (RD->getNumVBases()) { 4839 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 4840 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 4841 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 4842 E = RD->vbases_end(); I != E; ++I) 4843 Diag(I->getLocStart(), 4844 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 4845 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 4846 !RD->hasTrivialDefaultConstructor()) { 4847 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 4848 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 4849 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4850 E = RD->bases_end(); I != E; ++I) { 4851 if (!I->getType()->isLiteralType()) { 4852 Diag(I->getLocStart(), 4853 diag::note_non_literal_base_class) 4854 << RD << I->getType() << I->getSourceRange(); 4855 return true; 4856 } 4857 } 4858 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 4859 E = RD->field_end(); I != E; ++I) { 4860 if (!I->getType()->isLiteralType() || 4861 I->getType().isVolatileQualified()) { 4862 Diag(I->getLocation(), diag::note_non_literal_field) 4863 << RD << *I << I->getType() 4864 << I->getType().isVolatileQualified(); 4865 return true; 4866 } 4867 } 4868 } else if (!RD->hasTrivialDestructor()) { 4869 // All fields and bases are of literal types, so have trivial destructors. 4870 // If this class's destructor is non-trivial it must be user-declared. 4871 CXXDestructorDecl *Dtor = RD->getDestructor(); 4872 assert(Dtor && "class has literal fields and bases but no dtor?"); 4873 if (!Dtor) 4874 return true; 4875 4876 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 4877 diag::note_non_literal_user_provided_dtor : 4878 diag::note_non_literal_nontrivial_dtor) << RD; 4879 if (!Dtor->isUserProvided()) 4880 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true); 4881 } 4882 4883 return true; 4884} 4885 4886bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 4887 TypeDiagnoserDiag Diagnoser(DiagID); 4888 return RequireLiteralType(Loc, T, Diagnoser); 4889} 4890 4891/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 4892/// and qualified by the nested-name-specifier contained in SS. 4893QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 4894 const CXXScopeSpec &SS, QualType T) { 4895 if (T.isNull()) 4896 return T; 4897 NestedNameSpecifier *NNS; 4898 if (SS.isValid()) 4899 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 4900 else { 4901 if (Keyword == ETK_None) 4902 return T; 4903 NNS = 0; 4904 } 4905 return Context.getElaboratedType(Keyword, NNS, T); 4906} 4907 4908QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 4909 ExprResult ER = CheckPlaceholderExpr(E); 4910 if (ER.isInvalid()) return QualType(); 4911 E = ER.take(); 4912 4913 if (!E->isTypeDependent()) { 4914 QualType T = E->getType(); 4915 if (const TagType *TT = T->getAs<TagType>()) 4916 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 4917 } 4918 return Context.getTypeOfExprType(E); 4919} 4920 4921/// getDecltypeForExpr - Given an expr, will return the decltype for 4922/// that expression, according to the rules in C++11 4923/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 4924static QualType getDecltypeForExpr(Sema &S, Expr *E) { 4925 if (E->isTypeDependent()) 4926 return S.Context.DependentTy; 4927 4928 // C++11 [dcl.type.simple]p4: 4929 // The type denoted by decltype(e) is defined as follows: 4930 // 4931 // - if e is an unparenthesized id-expression or an unparenthesized class 4932 // member access (5.2.5), decltype(e) is the type of the entity named 4933 // by e. If there is no such entity, or if e names a set of overloaded 4934 // functions, the program is ill-formed; 4935 // 4936 // We apply the same rules for Objective-C ivar and property references. 4937 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 4938 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 4939 return VD->getType(); 4940 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 4941 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 4942 return FD->getType(); 4943 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { 4944 return IR->getDecl()->getType(); 4945 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { 4946 if (PR->isExplicitProperty()) 4947 return PR->getExplicitProperty()->getType(); 4948 } 4949 4950 // C++11 [expr.lambda.prim]p18: 4951 // Every occurrence of decltype((x)) where x is a possibly 4952 // parenthesized id-expression that names an entity of automatic 4953 // storage duration is treated as if x were transformed into an 4954 // access to a corresponding data member of the closure type that 4955 // would have been declared if x were an odr-use of the denoted 4956 // entity. 4957 using namespace sema; 4958 if (S.getCurLambda()) { 4959 if (isa<ParenExpr>(E)) { 4960 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4961 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 4962 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 4963 if (!T.isNull()) 4964 return S.Context.getLValueReferenceType(T); 4965 } 4966 } 4967 } 4968 } 4969 4970 4971 // C++11 [dcl.type.simple]p4: 4972 // [...] 4973 QualType T = E->getType(); 4974 switch (E->getValueKind()) { 4975 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 4976 // type of e; 4977 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 4978 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 4979 // type of e; 4980 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 4981 // - otherwise, decltype(e) is the type of e. 4982 case VK_RValue: break; 4983 } 4984 4985 return T; 4986} 4987 4988QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) { 4989 ExprResult ER = CheckPlaceholderExpr(E); 4990 if (ER.isInvalid()) return QualType(); 4991 E = ER.take(); 4992 4993 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 4994} 4995 4996QualType Sema::BuildUnaryTransformType(QualType BaseType, 4997 UnaryTransformType::UTTKind UKind, 4998 SourceLocation Loc) { 4999 switch (UKind) { 5000 case UnaryTransformType::EnumUnderlyingType: 5001 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 5002 Diag(Loc, diag::err_only_enums_have_underlying_types); 5003 return QualType(); 5004 } else { 5005 QualType Underlying = BaseType; 5006 if (!BaseType->isDependentType()) { 5007 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 5008 assert(ED && "EnumType has no EnumDecl"); 5009 DiagnoseUseOfDecl(ED, Loc); 5010 Underlying = ED->getIntegerType(); 5011 } 5012 assert(!Underlying.isNull()); 5013 return Context.getUnaryTransformType(BaseType, Underlying, 5014 UnaryTransformType::EnumUnderlyingType); 5015 } 5016 } 5017 llvm_unreachable("unknown unary transform type"); 5018} 5019 5020QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 5021 if (!T->isDependentType()) { 5022 // FIXME: It isn't entirely clear whether incomplete atomic types 5023 // are allowed or not; for simplicity, ban them for the moment. 5024 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 5025 return QualType(); 5026 5027 int DisallowedKind = -1; 5028 if (T->isArrayType()) 5029 DisallowedKind = 1; 5030 else if (T->isFunctionType()) 5031 DisallowedKind = 2; 5032 else if (T->isReferenceType()) 5033 DisallowedKind = 3; 5034 else if (T->isAtomicType()) 5035 DisallowedKind = 4; 5036 else if (T.hasQualifiers()) 5037 DisallowedKind = 5; 5038 else if (!T.isTriviallyCopyableType(Context)) 5039 // Some other non-trivially-copyable type (probably a C++ class) 5040 DisallowedKind = 6; 5041 5042 if (DisallowedKind != -1) { 5043 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 5044 return QualType(); 5045 } 5046 5047 // FIXME: Do we need any handling for ARC here? 5048 } 5049 5050 // Build the pointer type. 5051 return Context.getAtomicType(T); 5052} 5053