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