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