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