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