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