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