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