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