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