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