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