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