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