1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements type-related semantic analysis. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/ASTStructuralEquivalence.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/TypeLoc.h" 23 #include "clang/AST/TypeLocVisitor.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Lex/Preprocessor.h" 27 #include "clang/Sema/DeclSpec.h" 28 #include "clang/Sema/DelayedDiagnostic.h" 29 #include "clang/Sema/Lookup.h" 30 #include "clang/Sema/ScopeInfo.h" 31 #include "clang/Sema/SemaInternal.h" 32 #include "clang/Sema/Template.h" 33 #include "clang/Sema/TemplateInstCallback.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/SmallString.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/Support/ErrorHandling.h" 38 39 using namespace clang; 40 41 enum TypeDiagSelector { 42 TDS_Function, 43 TDS_Pointer, 44 TDS_ObjCObjOrBlock 45 }; 46 47 /// isOmittedBlockReturnType - Return true if this declarator is missing a 48 /// return type because this is a omitted return type on a block literal. 49 static bool isOmittedBlockReturnType(const Declarator &D) { 50 if (D.getContext() != DeclaratorContext::BlockLiteralContext || 51 D.getDeclSpec().hasTypeSpecifier()) 52 return false; 53 54 if (D.getNumTypeObjects() == 0) 55 return true; // ^{ ... } 56 57 if (D.getNumTypeObjects() == 1 && 58 D.getTypeObject(0).Kind == DeclaratorChunk::Function) 59 return true; // ^(int X, float Y) { ... } 60 61 return false; 62 } 63 64 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which 65 /// doesn't apply to the given type. 66 static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, 67 QualType type) { 68 TypeDiagSelector WhichType; 69 bool useExpansionLoc = true; 70 switch (attr.getKind()) { 71 case ParsedAttr::AT_ObjCGC: 72 WhichType = TDS_Pointer; 73 break; 74 case ParsedAttr::AT_ObjCOwnership: 75 WhichType = TDS_ObjCObjOrBlock; 76 break; 77 default: 78 // Assume everything else was a function attribute. 79 WhichType = TDS_Function; 80 useExpansionLoc = false; 81 break; 82 } 83 84 SourceLocation loc = attr.getLoc(); 85 StringRef name = attr.getName()->getName(); 86 87 // The GC attributes are usually written with macros; special-case them. 88 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident 89 : nullptr; 90 if (useExpansionLoc && loc.isMacroID() && II) { 91 if (II->isStr("strong")) { 92 if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; 93 } else if (II->isStr("weak")) { 94 if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; 95 } 96 } 97 98 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType 99 << type; 100 } 101 102 // objc_gc applies to Objective-C pointers or, otherwise, to the 103 // smallest available pointer type (i.e. 'void*' in 'void**'). 104 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \ 105 case ParsedAttr::AT_ObjCGC: \ 106 case ParsedAttr::AT_ObjCOwnership 107 108 // Calling convention attributes. 109 #define CALLING_CONV_ATTRS_CASELIST \ 110 case ParsedAttr::AT_CDecl: \ 111 case ParsedAttr::AT_FastCall: \ 112 case ParsedAttr::AT_StdCall: \ 113 case ParsedAttr::AT_ThisCall: \ 114 case ParsedAttr::AT_RegCall: \ 115 case ParsedAttr::AT_Pascal: \ 116 case ParsedAttr::AT_SwiftCall: \ 117 case ParsedAttr::AT_VectorCall: \ 118 case ParsedAttr::AT_AArch64VectorPcs: \ 119 case ParsedAttr::AT_MSABI: \ 120 case ParsedAttr::AT_SysVABI: \ 121 case ParsedAttr::AT_Pcs: \ 122 case ParsedAttr::AT_IntelOclBicc: \ 123 case ParsedAttr::AT_PreserveMost: \ 124 case ParsedAttr::AT_PreserveAll 125 126 // Function type attributes. 127 #define FUNCTION_TYPE_ATTRS_CASELIST \ 128 case ParsedAttr::AT_NSReturnsRetained: \ 129 case ParsedAttr::AT_NoReturn: \ 130 case ParsedAttr::AT_Regparm: \ 131 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \ 132 case ParsedAttr::AT_AnyX86NoCfCheck: \ 133 CALLING_CONV_ATTRS_CASELIST 134 135 // Microsoft-specific type qualifiers. 136 #define MS_TYPE_ATTRS_CASELIST \ 137 case ParsedAttr::AT_Ptr32: \ 138 case ParsedAttr::AT_Ptr64: \ 139 case ParsedAttr::AT_SPtr: \ 140 case ParsedAttr::AT_UPtr 141 142 // Nullability qualifiers. 143 #define NULLABILITY_TYPE_ATTRS_CASELIST \ 144 case ParsedAttr::AT_TypeNonNull: \ 145 case ParsedAttr::AT_TypeNullable: \ 146 case ParsedAttr::AT_TypeNullUnspecified 147 148 namespace { 149 /// An object which stores processing state for the entire 150 /// GetTypeForDeclarator process. 151 class TypeProcessingState { 152 Sema &sema; 153 154 /// The declarator being processed. 155 Declarator &declarator; 156 157 /// The index of the declarator chunk we're currently processing. 158 /// May be the total number of valid chunks, indicating the 159 /// DeclSpec. 160 unsigned chunkIndex; 161 162 /// Whether there are non-trivial modifications to the decl spec. 163 bool trivial; 164 165 /// Whether we saved the attributes in the decl spec. 166 bool hasSavedAttrs; 167 168 /// The original set of attributes on the DeclSpec. 169 SmallVector<ParsedAttr *, 2> savedAttrs; 170 171 /// A list of attributes to diagnose the uselessness of when the 172 /// processing is complete. 173 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs; 174 175 /// Attributes corresponding to AttributedTypeLocs that we have not yet 176 /// populated. 177 // FIXME: The two-phase mechanism by which we construct Types and fill 178 // their TypeLocs makes it hard to correctly assign these. We keep the 179 // attributes in creation order as an attempt to make them line up 180 // properly. 181 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>; 182 SmallVector<TypeAttrPair, 8> AttrsForTypes; 183 bool AttrsForTypesSorted = true; 184 185 /// Flag to indicate we parsed a noderef attribute. This is used for 186 /// validating that noderef was used on a pointer or array. 187 bool parsedNoDeref; 188 189 public: 190 TypeProcessingState(Sema &sema, Declarator &declarator) 191 : sema(sema), declarator(declarator), 192 chunkIndex(declarator.getNumTypeObjects()), trivial(true), 193 hasSavedAttrs(false), parsedNoDeref(false) {} 194 195 Sema &getSema() const { 196 return sema; 197 } 198 199 Declarator &getDeclarator() const { 200 return declarator; 201 } 202 203 bool isProcessingDeclSpec() const { 204 return chunkIndex == declarator.getNumTypeObjects(); 205 } 206 207 unsigned getCurrentChunkIndex() const { 208 return chunkIndex; 209 } 210 211 void setCurrentChunkIndex(unsigned idx) { 212 assert(idx <= declarator.getNumTypeObjects()); 213 chunkIndex = idx; 214 } 215 216 ParsedAttributesView &getCurrentAttributes() const { 217 if (isProcessingDeclSpec()) 218 return getMutableDeclSpec().getAttributes(); 219 return declarator.getTypeObject(chunkIndex).getAttrs(); 220 } 221 222 /// Save the current set of attributes on the DeclSpec. 223 void saveDeclSpecAttrs() { 224 // Don't try to save them multiple times. 225 if (hasSavedAttrs) return; 226 227 DeclSpec &spec = getMutableDeclSpec(); 228 for (ParsedAttr &AL : spec.getAttributes()) 229 savedAttrs.push_back(&AL); 230 trivial &= savedAttrs.empty(); 231 hasSavedAttrs = true; 232 } 233 234 /// Record that we had nowhere to put the given type attribute. 235 /// We will diagnose such attributes later. 236 void addIgnoredTypeAttr(ParsedAttr &attr) { 237 ignoredTypeAttrs.push_back(&attr); 238 } 239 240 /// Diagnose all the ignored type attributes, given that the 241 /// declarator worked out to the given type. 242 void diagnoseIgnoredTypeAttrs(QualType type) const { 243 for (auto *Attr : ignoredTypeAttrs) 244 diagnoseBadTypeAttribute(getSema(), *Attr, type); 245 } 246 247 /// Get an attributed type for the given attribute, and remember the Attr 248 /// object so that we can attach it to the AttributedTypeLoc. 249 QualType getAttributedType(Attr *A, QualType ModifiedType, 250 QualType EquivType) { 251 QualType T = 252 sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType); 253 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A}); 254 AttrsForTypesSorted = false; 255 return T; 256 } 257 258 /// Completely replace the \c auto in \p TypeWithAuto by 259 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if 260 /// necessary. 261 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) { 262 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement); 263 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) { 264 // Attributed type still should be an attributed type after replacement. 265 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr()); 266 for (TypeAttrPair &A : AttrsForTypes) { 267 if (A.first == AttrTy) 268 A.first = NewAttrTy; 269 } 270 AttrsForTypesSorted = false; 271 } 272 return T; 273 } 274 275 /// Extract and remove the Attr* for a given attributed type. 276 const Attr *takeAttrForAttributedType(const AttributedType *AT) { 277 if (!AttrsForTypesSorted) { 278 std::stable_sort(AttrsForTypes.begin(), AttrsForTypes.end(), 279 [](const TypeAttrPair &A, const TypeAttrPair &B) { 280 return A.first < B.first; 281 }); 282 AttrsForTypesSorted = true; 283 } 284 285 // FIXME: This is quadratic if we have lots of reuses of the same 286 // attributed type. 287 for (auto It = std::partition_point( 288 AttrsForTypes.begin(), AttrsForTypes.end(), 289 [=](const TypeAttrPair &A) { return A.first < AT; }); 290 It != AttrsForTypes.end() && It->first == AT; ++It) { 291 if (It->second) { 292 const Attr *Result = It->second; 293 It->second = nullptr; 294 return Result; 295 } 296 } 297 298 llvm_unreachable("no Attr* for AttributedType*"); 299 } 300 301 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; } 302 303 bool didParseNoDeref() const { return parsedNoDeref; } 304 305 ~TypeProcessingState() { 306 if (trivial) return; 307 308 restoreDeclSpecAttrs(); 309 } 310 311 private: 312 DeclSpec &getMutableDeclSpec() const { 313 return const_cast<DeclSpec&>(declarator.getDeclSpec()); 314 } 315 316 void restoreDeclSpecAttrs() { 317 assert(hasSavedAttrs); 318 319 getMutableDeclSpec().getAttributes().clearListOnly(); 320 for (ParsedAttr *AL : savedAttrs) 321 getMutableDeclSpec().getAttributes().addAtEnd(AL); 322 } 323 }; 324 } // end anonymous namespace 325 326 static void moveAttrFromListToList(ParsedAttr &attr, 327 ParsedAttributesView &fromList, 328 ParsedAttributesView &toList) { 329 fromList.remove(&attr); 330 toList.addAtEnd(&attr); 331 } 332 333 /// The location of a type attribute. 334 enum TypeAttrLocation { 335 /// The attribute is in the decl-specifier-seq. 336 TAL_DeclSpec, 337 /// The attribute is part of a DeclaratorChunk. 338 TAL_DeclChunk, 339 /// The attribute is immediately after the declaration's name. 340 TAL_DeclName 341 }; 342 343 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 344 TypeAttrLocation TAL, ParsedAttributesView &attrs); 345 346 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 347 QualType &type); 348 349 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, 350 ParsedAttr &attr, QualType &type); 351 352 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 353 QualType &type); 354 355 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 356 ParsedAttr &attr, QualType &type); 357 358 static bool handleObjCPointerTypeAttr(TypeProcessingState &state, 359 ParsedAttr &attr, QualType &type) { 360 if (attr.getKind() == ParsedAttr::AT_ObjCGC) 361 return handleObjCGCTypeAttr(state, attr, type); 362 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership); 363 return handleObjCOwnershipTypeAttr(state, attr, type); 364 } 365 366 /// Given the index of a declarator chunk, check whether that chunk 367 /// directly specifies the return type of a function and, if so, find 368 /// an appropriate place for it. 369 /// 370 /// \param i - a notional index which the search will start 371 /// immediately inside 372 /// 373 /// \param onlyBlockPointers Whether we should only look into block 374 /// pointer types (vs. all pointer types). 375 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, 376 unsigned i, 377 bool onlyBlockPointers) { 378 assert(i <= declarator.getNumTypeObjects()); 379 380 DeclaratorChunk *result = nullptr; 381 382 // First, look inwards past parens for a function declarator. 383 for (; i != 0; --i) { 384 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); 385 switch (fnChunk.Kind) { 386 case DeclaratorChunk::Paren: 387 continue; 388 389 // If we find anything except a function, bail out. 390 case DeclaratorChunk::Pointer: 391 case DeclaratorChunk::BlockPointer: 392 case DeclaratorChunk::Array: 393 case DeclaratorChunk::Reference: 394 case DeclaratorChunk::MemberPointer: 395 case DeclaratorChunk::Pipe: 396 return result; 397 398 // If we do find a function declarator, scan inwards from that, 399 // looking for a (block-)pointer declarator. 400 case DeclaratorChunk::Function: 401 for (--i; i != 0; --i) { 402 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1); 403 switch (ptrChunk.Kind) { 404 case DeclaratorChunk::Paren: 405 case DeclaratorChunk::Array: 406 case DeclaratorChunk::Function: 407 case DeclaratorChunk::Reference: 408 case DeclaratorChunk::Pipe: 409 continue; 410 411 case DeclaratorChunk::MemberPointer: 412 case DeclaratorChunk::Pointer: 413 if (onlyBlockPointers) 414 continue; 415 416 LLVM_FALLTHROUGH; 417 418 case DeclaratorChunk::BlockPointer: 419 result = &ptrChunk; 420 goto continue_outer; 421 } 422 llvm_unreachable("bad declarator chunk kind"); 423 } 424 425 // If we run out of declarators doing that, we're done. 426 return result; 427 } 428 llvm_unreachable("bad declarator chunk kind"); 429 430 // Okay, reconsider from our new point. 431 continue_outer: ; 432 } 433 434 // Ran out of chunks, bail out. 435 return result; 436 } 437 438 /// Given that an objc_gc attribute was written somewhere on a 439 /// declaration *other* than on the declarator itself (for which, use 440 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it 441 /// didn't apply in whatever position it was written in, try to move 442 /// it to a more appropriate position. 443 static void distributeObjCPointerTypeAttr(TypeProcessingState &state, 444 ParsedAttr &attr, QualType type) { 445 Declarator &declarator = state.getDeclarator(); 446 447 // Move it to the outermost normal or block pointer declarator. 448 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 449 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 450 switch (chunk.Kind) { 451 case DeclaratorChunk::Pointer: 452 case DeclaratorChunk::BlockPointer: { 453 // But don't move an ARC ownership attribute to the return type 454 // of a block. 455 DeclaratorChunk *destChunk = nullptr; 456 if (state.isProcessingDeclSpec() && 457 attr.getKind() == ParsedAttr::AT_ObjCOwnership) 458 destChunk = maybeMovePastReturnType(declarator, i - 1, 459 /*onlyBlockPointers=*/true); 460 if (!destChunk) destChunk = &chunk; 461 462 moveAttrFromListToList(attr, state.getCurrentAttributes(), 463 destChunk->getAttrs()); 464 return; 465 } 466 467 case DeclaratorChunk::Paren: 468 case DeclaratorChunk::Array: 469 continue; 470 471 // We may be starting at the return type of a block. 472 case DeclaratorChunk::Function: 473 if (state.isProcessingDeclSpec() && 474 attr.getKind() == ParsedAttr::AT_ObjCOwnership) { 475 if (DeclaratorChunk *dest = maybeMovePastReturnType( 476 declarator, i, 477 /*onlyBlockPointers=*/true)) { 478 moveAttrFromListToList(attr, state.getCurrentAttributes(), 479 dest->getAttrs()); 480 return; 481 } 482 } 483 goto error; 484 485 // Don't walk through these. 486 case DeclaratorChunk::Reference: 487 case DeclaratorChunk::MemberPointer: 488 case DeclaratorChunk::Pipe: 489 goto error; 490 } 491 } 492 error: 493 494 diagnoseBadTypeAttribute(state.getSema(), attr, type); 495 } 496 497 /// Distribute an objc_gc type attribute that was written on the 498 /// declarator. 499 static void distributeObjCPointerTypeAttrFromDeclarator( 500 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) { 501 Declarator &declarator = state.getDeclarator(); 502 503 // objc_gc goes on the innermost pointer to something that's not a 504 // pointer. 505 unsigned innermost = -1U; 506 bool considerDeclSpec = true; 507 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 508 DeclaratorChunk &chunk = declarator.getTypeObject(i); 509 switch (chunk.Kind) { 510 case DeclaratorChunk::Pointer: 511 case DeclaratorChunk::BlockPointer: 512 innermost = i; 513 continue; 514 515 case DeclaratorChunk::Reference: 516 case DeclaratorChunk::MemberPointer: 517 case DeclaratorChunk::Paren: 518 case DeclaratorChunk::Array: 519 case DeclaratorChunk::Pipe: 520 continue; 521 522 case DeclaratorChunk::Function: 523 considerDeclSpec = false; 524 goto done; 525 } 526 } 527 done: 528 529 // That might actually be the decl spec if we weren't blocked by 530 // anything in the declarator. 531 if (considerDeclSpec) { 532 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { 533 // Splice the attribute into the decl spec. Prevents the 534 // attribute from being applied multiple times and gives 535 // the source-location-filler something to work with. 536 state.saveDeclSpecAttrs(); 537 declarator.getMutableDeclSpec().getAttributes().takeOneFrom( 538 declarator.getAttributes(), &attr); 539 return; 540 } 541 } 542 543 // Otherwise, if we found an appropriate chunk, splice the attribute 544 // into it. 545 if (innermost != -1U) { 546 moveAttrFromListToList(attr, declarator.getAttributes(), 547 declarator.getTypeObject(innermost).getAttrs()); 548 return; 549 } 550 551 // Otherwise, diagnose when we're done building the type. 552 declarator.getAttributes().remove(&attr); 553 state.addIgnoredTypeAttr(attr); 554 } 555 556 /// A function type attribute was written somewhere in a declaration 557 /// *other* than on the declarator itself or in the decl spec. Given 558 /// that it didn't apply in whatever position it was written in, try 559 /// to move it to a more appropriate position. 560 static void distributeFunctionTypeAttr(TypeProcessingState &state, 561 ParsedAttr &attr, QualType type) { 562 Declarator &declarator = state.getDeclarator(); 563 564 // Try to push the attribute from the return type of a function to 565 // the function itself. 566 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 567 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 568 switch (chunk.Kind) { 569 case DeclaratorChunk::Function: 570 moveAttrFromListToList(attr, state.getCurrentAttributes(), 571 chunk.getAttrs()); 572 return; 573 574 case DeclaratorChunk::Paren: 575 case DeclaratorChunk::Pointer: 576 case DeclaratorChunk::BlockPointer: 577 case DeclaratorChunk::Array: 578 case DeclaratorChunk::Reference: 579 case DeclaratorChunk::MemberPointer: 580 case DeclaratorChunk::Pipe: 581 continue; 582 } 583 } 584 585 diagnoseBadTypeAttribute(state.getSema(), attr, type); 586 } 587 588 /// Try to distribute a function type attribute to the innermost 589 /// function chunk or type. Returns true if the attribute was 590 /// distributed, false if no location was found. 591 static bool distributeFunctionTypeAttrToInnermost( 592 TypeProcessingState &state, ParsedAttr &attr, 593 ParsedAttributesView &attrList, QualType &declSpecType) { 594 Declarator &declarator = state.getDeclarator(); 595 596 // Put it on the innermost function chunk, if there is one. 597 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 598 DeclaratorChunk &chunk = declarator.getTypeObject(i); 599 if (chunk.Kind != DeclaratorChunk::Function) continue; 600 601 moveAttrFromListToList(attr, attrList, chunk.getAttrs()); 602 return true; 603 } 604 605 return handleFunctionTypeAttr(state, attr, declSpecType); 606 } 607 608 /// A function type attribute was written in the decl spec. Try to 609 /// apply it somewhere. 610 static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, 611 ParsedAttr &attr, 612 QualType &declSpecType) { 613 state.saveDeclSpecAttrs(); 614 615 // C++11 attributes before the decl specifiers actually appertain to 616 // the declarators. Move them straight there. We don't support the 617 // 'put them wherever you like' semantics we allow for GNU attributes. 618 if (attr.isCXX11Attribute()) { 619 moveAttrFromListToList(attr, state.getCurrentAttributes(), 620 state.getDeclarator().getAttributes()); 621 return; 622 } 623 624 // Try to distribute to the innermost. 625 if (distributeFunctionTypeAttrToInnermost( 626 state, attr, state.getCurrentAttributes(), declSpecType)) 627 return; 628 629 // If that failed, diagnose the bad attribute when the declarator is 630 // fully built. 631 state.addIgnoredTypeAttr(attr); 632 } 633 634 /// A function type attribute was written on the declarator. Try to 635 /// apply it somewhere. 636 static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, 637 ParsedAttr &attr, 638 QualType &declSpecType) { 639 Declarator &declarator = state.getDeclarator(); 640 641 // Try to distribute to the innermost. 642 if (distributeFunctionTypeAttrToInnermost( 643 state, attr, declarator.getAttributes(), declSpecType)) 644 return; 645 646 // If that failed, diagnose the bad attribute when the declarator is 647 // fully built. 648 declarator.getAttributes().remove(&attr); 649 state.addIgnoredTypeAttr(attr); 650 } 651 652 /// Given that there are attributes written on the declarator 653 /// itself, try to distribute any type attributes to the appropriate 654 /// declarator chunk. 655 /// 656 /// These are attributes like the following: 657 /// int f ATTR; 658 /// int (f ATTR)(); 659 /// but not necessarily this: 660 /// int f() ATTR; 661 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, 662 QualType &declSpecType) { 663 // Collect all the type attributes from the declarator itself. 664 assert(!state.getDeclarator().getAttributes().empty() && 665 "declarator has no attrs!"); 666 // The called functions in this loop actually remove things from the current 667 // list, so iterating over the existing list isn't possible. Instead, make a 668 // non-owning copy and iterate over that. 669 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()}; 670 for (ParsedAttr &attr : AttrsCopy) { 671 // Do not distribute C++11 attributes. They have strict rules for what 672 // they appertain to. 673 if (attr.isCXX11Attribute()) 674 continue; 675 676 switch (attr.getKind()) { 677 OBJC_POINTER_TYPE_ATTRS_CASELIST: 678 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType); 679 break; 680 681 FUNCTION_TYPE_ATTRS_CASELIST: 682 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType); 683 break; 684 685 MS_TYPE_ATTRS_CASELIST: 686 // Microsoft type attributes cannot go after the declarator-id. 687 continue; 688 689 NULLABILITY_TYPE_ATTRS_CASELIST: 690 // Nullability specifiers cannot go after the declarator-id. 691 692 // Objective-C __kindof does not get distributed. 693 case ParsedAttr::AT_ObjCKindOf: 694 continue; 695 696 default: 697 break; 698 } 699 } 700 } 701 702 /// Add a synthetic '()' to a block-literal declarator if it is 703 /// required, given the return type. 704 static void maybeSynthesizeBlockSignature(TypeProcessingState &state, 705 QualType declSpecType) { 706 Declarator &declarator = state.getDeclarator(); 707 708 // First, check whether the declarator would produce a function, 709 // i.e. whether the innermost semantic chunk is a function. 710 if (declarator.isFunctionDeclarator()) { 711 // If so, make that declarator a prototyped declarator. 712 declarator.getFunctionTypeInfo().hasPrototype = true; 713 return; 714 } 715 716 // If there are any type objects, the type as written won't name a 717 // function, regardless of the decl spec type. This is because a 718 // block signature declarator is always an abstract-declarator, and 719 // abstract-declarators can't just be parentheses chunks. Therefore 720 // we need to build a function chunk unless there are no type 721 // objects and the decl spec type is a function. 722 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) 723 return; 724 725 // Note that there *are* cases with invalid declarators where 726 // declarators consist solely of parentheses. In general, these 727 // occur only in failed efforts to make function declarators, so 728 // faking up the function chunk is still the right thing to do. 729 730 // Otherwise, we need to fake up a function declarator. 731 SourceLocation loc = declarator.getBeginLoc(); 732 733 // ...and *prepend* it to the declarator. 734 SourceLocation NoLoc; 735 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( 736 /*HasProto=*/true, 737 /*IsAmbiguous=*/false, 738 /*LParenLoc=*/NoLoc, 739 /*ArgInfo=*/nullptr, 740 /*NumArgs=*/0, 741 /*EllipsisLoc=*/NoLoc, 742 /*RParenLoc=*/NoLoc, 743 /*RefQualifierIsLvalueRef=*/true, 744 /*RefQualifierLoc=*/NoLoc, 745 /*MutableLoc=*/NoLoc, EST_None, 746 /*ESpecRange=*/SourceRange(), 747 /*Exceptions=*/nullptr, 748 /*ExceptionRanges=*/nullptr, 749 /*NumExceptions=*/0, 750 /*NoexceptExpr=*/nullptr, 751 /*ExceptionSpecTokens=*/nullptr, 752 /*DeclsInPrototype=*/None, loc, loc, declarator)); 753 754 // For consistency, make sure the state still has us as processing 755 // the decl spec. 756 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); 757 state.setCurrentChunkIndex(declarator.getNumTypeObjects()); 758 } 759 760 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, 761 unsigned &TypeQuals, 762 QualType TypeSoFar, 763 unsigned RemoveTQs, 764 unsigned DiagID) { 765 // If this occurs outside a template instantiation, warn the user about 766 // it; they probably didn't mean to specify a redundant qualifier. 767 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; 768 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), 769 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()), 770 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), 771 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) { 772 if (!(RemoveTQs & Qual.first)) 773 continue; 774 775 if (!S.inTemplateInstantiation()) { 776 if (TypeQuals & Qual.first) 777 S.Diag(Qual.second, DiagID) 778 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar 779 << FixItHint::CreateRemoval(Qual.second); 780 } 781 782 TypeQuals &= ~Qual.first; 783 } 784 } 785 786 /// Return true if this is omitted block return type. Also check type 787 /// attributes and type qualifiers when returning true. 788 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, 789 QualType Result) { 790 if (!isOmittedBlockReturnType(declarator)) 791 return false; 792 793 // Warn if we see type attributes for omitted return type on a block literal. 794 SmallVector<ParsedAttr *, 2> ToBeRemoved; 795 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) { 796 if (AL.isInvalid() || !AL.isTypeAttr()) 797 continue; 798 S.Diag(AL.getLoc(), 799 diag::warn_block_literal_attributes_on_omitted_return_type) 800 << AL.getName(); 801 ToBeRemoved.push_back(&AL); 802 } 803 // Remove bad attributes from the list. 804 for (ParsedAttr *AL : ToBeRemoved) 805 declarator.getMutableDeclSpec().getAttributes().remove(AL); 806 807 // Warn if we see type qualifiers for omitted return type on a block literal. 808 const DeclSpec &DS = declarator.getDeclSpec(); 809 unsigned TypeQuals = DS.getTypeQualifiers(); 810 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1, 811 diag::warn_block_literal_qualifiers_on_omitted_return_type); 812 declarator.getMutableDeclSpec().ClearTypeQualifiers(); 813 814 return true; 815 } 816 817 /// Apply Objective-C type arguments to the given type. 818 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type, 819 ArrayRef<TypeSourceInfo *> typeArgs, 820 SourceRange typeArgsRange, 821 bool failOnError = false) { 822 // We can only apply type arguments to an Objective-C class type. 823 const auto *objcObjectType = type->getAs<ObjCObjectType>(); 824 if (!objcObjectType || !objcObjectType->getInterface()) { 825 S.Diag(loc, diag::err_objc_type_args_non_class) 826 << type 827 << typeArgsRange; 828 829 if (failOnError) 830 return QualType(); 831 return type; 832 } 833 834 // The class type must be parameterized. 835 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface(); 836 ObjCTypeParamList *typeParams = objcClass->getTypeParamList(); 837 if (!typeParams) { 838 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class) 839 << objcClass->getDeclName() 840 << FixItHint::CreateRemoval(typeArgsRange); 841 842 if (failOnError) 843 return QualType(); 844 845 return type; 846 } 847 848 // The type must not already be specialized. 849 if (objcObjectType->isSpecialized()) { 850 S.Diag(loc, diag::err_objc_type_args_specialized_class) 851 << type 852 << FixItHint::CreateRemoval(typeArgsRange); 853 854 if (failOnError) 855 return QualType(); 856 857 return type; 858 } 859 860 // Check the type arguments. 861 SmallVector<QualType, 4> finalTypeArgs; 862 unsigned numTypeParams = typeParams->size(); 863 bool anyPackExpansions = false; 864 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) { 865 TypeSourceInfo *typeArgInfo = typeArgs[i]; 866 QualType typeArg = typeArgInfo->getType(); 867 868 // Type arguments cannot have explicit qualifiers or nullability. 869 // We ignore indirect sources of these, e.g. behind typedefs or 870 // template arguments. 871 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) { 872 bool diagnosed = false; 873 SourceRange rangeToRemove; 874 if (auto attr = qual.getAs<AttributedTypeLoc>()) { 875 rangeToRemove = attr.getLocalSourceRange(); 876 if (attr.getTypePtr()->getImmediateNullability()) { 877 typeArg = attr.getTypePtr()->getModifiedType(); 878 S.Diag(attr.getBeginLoc(), 879 diag::err_objc_type_arg_explicit_nullability) 880 << typeArg << FixItHint::CreateRemoval(rangeToRemove); 881 diagnosed = true; 882 } 883 } 884 885 if (!diagnosed) { 886 S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified) 887 << typeArg << typeArg.getQualifiers().getAsString() 888 << FixItHint::CreateRemoval(rangeToRemove); 889 } 890 } 891 892 // Remove qualifiers even if they're non-local. 893 typeArg = typeArg.getUnqualifiedType(); 894 895 finalTypeArgs.push_back(typeArg); 896 897 if (typeArg->getAs<PackExpansionType>()) 898 anyPackExpansions = true; 899 900 // Find the corresponding type parameter, if there is one. 901 ObjCTypeParamDecl *typeParam = nullptr; 902 if (!anyPackExpansions) { 903 if (i < numTypeParams) { 904 typeParam = typeParams->begin()[i]; 905 } else { 906 // Too many arguments. 907 S.Diag(loc, diag::err_objc_type_args_wrong_arity) 908 << false 909 << objcClass->getDeclName() 910 << (unsigned)typeArgs.size() 911 << numTypeParams; 912 S.Diag(objcClass->getLocation(), diag::note_previous_decl) 913 << objcClass; 914 915 if (failOnError) 916 return QualType(); 917 918 return type; 919 } 920 } 921 922 // Objective-C object pointer types must be substitutable for the bounds. 923 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) { 924 // If we don't have a type parameter to match against, assume 925 // everything is fine. There was a prior pack expansion that 926 // means we won't be able to match anything. 927 if (!typeParam) { 928 assert(anyPackExpansions && "Too many arguments?"); 929 continue; 930 } 931 932 // Retrieve the bound. 933 QualType bound = typeParam->getUnderlyingType(); 934 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>(); 935 936 // Determine whether the type argument is substitutable for the bound. 937 if (typeArgObjC->isObjCIdType()) { 938 // When the type argument is 'id', the only acceptable type 939 // parameter bound is 'id'. 940 if (boundObjC->isObjCIdType()) 941 continue; 942 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) { 943 // Otherwise, we follow the assignability rules. 944 continue; 945 } 946 947 // Diagnose the mismatch. 948 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), 949 diag::err_objc_type_arg_does_not_match_bound) 950 << typeArg << bound << typeParam->getDeclName(); 951 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) 952 << typeParam->getDeclName(); 953 954 if (failOnError) 955 return QualType(); 956 957 return type; 958 } 959 960 // Block pointer types are permitted for unqualified 'id' bounds. 961 if (typeArg->isBlockPointerType()) { 962 // If we don't have a type parameter to match against, assume 963 // everything is fine. There was a prior pack expansion that 964 // means we won't be able to match anything. 965 if (!typeParam) { 966 assert(anyPackExpansions && "Too many arguments?"); 967 continue; 968 } 969 970 // Retrieve the bound. 971 QualType bound = typeParam->getUnderlyingType(); 972 if (bound->isBlockCompatibleObjCPointerType(S.Context)) 973 continue; 974 975 // Diagnose the mismatch. 976 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), 977 diag::err_objc_type_arg_does_not_match_bound) 978 << typeArg << bound << typeParam->getDeclName(); 979 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) 980 << typeParam->getDeclName(); 981 982 if (failOnError) 983 return QualType(); 984 985 return type; 986 } 987 988 // Dependent types will be checked at instantiation time. 989 if (typeArg->isDependentType()) { 990 continue; 991 } 992 993 // Diagnose non-id-compatible type arguments. 994 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), 995 diag::err_objc_type_arg_not_id_compatible) 996 << typeArg << typeArgInfo->getTypeLoc().getSourceRange(); 997 998 if (failOnError) 999 return QualType(); 1000 1001 return type; 1002 } 1003 1004 // Make sure we didn't have the wrong number of arguments. 1005 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) { 1006 S.Diag(loc, diag::err_objc_type_args_wrong_arity) 1007 << (typeArgs.size() < typeParams->size()) 1008 << objcClass->getDeclName() 1009 << (unsigned)finalTypeArgs.size() 1010 << (unsigned)numTypeParams; 1011 S.Diag(objcClass->getLocation(), diag::note_previous_decl) 1012 << objcClass; 1013 1014 if (failOnError) 1015 return QualType(); 1016 1017 return type; 1018 } 1019 1020 // Success. Form the specialized type. 1021 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false); 1022 } 1023 1024 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, 1025 SourceLocation ProtocolLAngleLoc, 1026 ArrayRef<ObjCProtocolDecl *> Protocols, 1027 ArrayRef<SourceLocation> ProtocolLocs, 1028 SourceLocation ProtocolRAngleLoc, 1029 bool FailOnError) { 1030 QualType Result = QualType(Decl->getTypeForDecl(), 0); 1031 if (!Protocols.empty()) { 1032 bool HasError; 1033 Result = Context.applyObjCProtocolQualifiers(Result, Protocols, 1034 HasError); 1035 if (HasError) { 1036 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers) 1037 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); 1038 if (FailOnError) Result = QualType(); 1039 } 1040 if (FailOnError && Result.isNull()) 1041 return QualType(); 1042 } 1043 1044 return Result; 1045 } 1046 1047 QualType Sema::BuildObjCObjectType(QualType BaseType, 1048 SourceLocation Loc, 1049 SourceLocation TypeArgsLAngleLoc, 1050 ArrayRef<TypeSourceInfo *> TypeArgs, 1051 SourceLocation TypeArgsRAngleLoc, 1052 SourceLocation ProtocolLAngleLoc, 1053 ArrayRef<ObjCProtocolDecl *> Protocols, 1054 ArrayRef<SourceLocation> ProtocolLocs, 1055 SourceLocation ProtocolRAngleLoc, 1056 bool FailOnError) { 1057 QualType Result = BaseType; 1058 if (!TypeArgs.empty()) { 1059 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs, 1060 SourceRange(TypeArgsLAngleLoc, 1061 TypeArgsRAngleLoc), 1062 FailOnError); 1063 if (FailOnError && Result.isNull()) 1064 return QualType(); 1065 } 1066 1067 if (!Protocols.empty()) { 1068 bool HasError; 1069 Result = Context.applyObjCProtocolQualifiers(Result, Protocols, 1070 HasError); 1071 if (HasError) { 1072 Diag(Loc, diag::err_invalid_protocol_qualifiers) 1073 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); 1074 if (FailOnError) Result = QualType(); 1075 } 1076 if (FailOnError && Result.isNull()) 1077 return QualType(); 1078 } 1079 1080 return Result; 1081 } 1082 1083 TypeResult Sema::actOnObjCProtocolQualifierType( 1084 SourceLocation lAngleLoc, 1085 ArrayRef<Decl *> protocols, 1086 ArrayRef<SourceLocation> protocolLocs, 1087 SourceLocation rAngleLoc) { 1088 // Form id<protocol-list>. 1089 QualType Result = Context.getObjCObjectType( 1090 Context.ObjCBuiltinIdTy, { }, 1091 llvm::makeArrayRef( 1092 (ObjCProtocolDecl * const *)protocols.data(), 1093 protocols.size()), 1094 false); 1095 Result = Context.getObjCObjectPointerType(Result); 1096 1097 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); 1098 TypeLoc ResultTL = ResultTInfo->getTypeLoc(); 1099 1100 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>(); 1101 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit 1102 1103 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc() 1104 .castAs<ObjCObjectTypeLoc>(); 1105 ObjCObjectTL.setHasBaseTypeAsWritten(false); 1106 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation()); 1107 1108 // No type arguments. 1109 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); 1110 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); 1111 1112 // Fill in protocol qualifiers. 1113 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc); 1114 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc); 1115 for (unsigned i = 0, n = protocols.size(); i != n; ++i) 1116 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]); 1117 1118 // We're done. Return the completed type to the parser. 1119 return CreateParsedType(Result, ResultTInfo); 1120 } 1121 1122 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers( 1123 Scope *S, 1124 SourceLocation Loc, 1125 ParsedType BaseType, 1126 SourceLocation TypeArgsLAngleLoc, 1127 ArrayRef<ParsedType> TypeArgs, 1128 SourceLocation TypeArgsRAngleLoc, 1129 SourceLocation ProtocolLAngleLoc, 1130 ArrayRef<Decl *> Protocols, 1131 ArrayRef<SourceLocation> ProtocolLocs, 1132 SourceLocation ProtocolRAngleLoc) { 1133 TypeSourceInfo *BaseTypeInfo = nullptr; 1134 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo); 1135 if (T.isNull()) 1136 return true; 1137 1138 // Handle missing type-source info. 1139 if (!BaseTypeInfo) 1140 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc); 1141 1142 // Extract type arguments. 1143 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos; 1144 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) { 1145 TypeSourceInfo *TypeArgInfo = nullptr; 1146 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo); 1147 if (TypeArg.isNull()) { 1148 ActualTypeArgInfos.clear(); 1149 break; 1150 } 1151 1152 assert(TypeArgInfo && "No type source info?"); 1153 ActualTypeArgInfos.push_back(TypeArgInfo); 1154 } 1155 1156 // Build the object type. 1157 QualType Result = BuildObjCObjectType( 1158 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(), 1159 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc, 1160 ProtocolLAngleLoc, 1161 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(), 1162 Protocols.size()), 1163 ProtocolLocs, ProtocolRAngleLoc, 1164 /*FailOnError=*/false); 1165 1166 if (Result == T) 1167 return BaseType; 1168 1169 // Create source information for this type. 1170 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); 1171 TypeLoc ResultTL = ResultTInfo->getTypeLoc(); 1172 1173 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an 1174 // object pointer type. Fill in source information for it. 1175 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) { 1176 // The '*' is implicit. 1177 ObjCObjectPointerTL.setStarLoc(SourceLocation()); 1178 ResultTL = ObjCObjectPointerTL.getPointeeLoc(); 1179 } 1180 1181 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) { 1182 // Protocol qualifier information. 1183 if (OTPTL.getNumProtocols() > 0) { 1184 assert(OTPTL.getNumProtocols() == Protocols.size()); 1185 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc); 1186 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc); 1187 for (unsigned i = 0, n = Protocols.size(); i != n; ++i) 1188 OTPTL.setProtocolLoc(i, ProtocolLocs[i]); 1189 } 1190 1191 // We're done. Return the completed type to the parser. 1192 return CreateParsedType(Result, ResultTInfo); 1193 } 1194 1195 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>(); 1196 1197 // Type argument information. 1198 if (ObjCObjectTL.getNumTypeArgs() > 0) { 1199 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()); 1200 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc); 1201 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc); 1202 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i) 1203 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]); 1204 } else { 1205 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); 1206 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); 1207 } 1208 1209 // Protocol qualifier information. 1210 if (ObjCObjectTL.getNumProtocols() > 0) { 1211 assert(ObjCObjectTL.getNumProtocols() == Protocols.size()); 1212 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc); 1213 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc); 1214 for (unsigned i = 0, n = Protocols.size(); i != n; ++i) 1215 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]); 1216 } else { 1217 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation()); 1218 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation()); 1219 } 1220 1221 // Base type. 1222 ObjCObjectTL.setHasBaseTypeAsWritten(true); 1223 if (ObjCObjectTL.getType() == T) 1224 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc()); 1225 else 1226 ObjCObjectTL.getBaseLoc().initialize(Context, Loc); 1227 1228 // We're done. Return the completed type to the parser. 1229 return CreateParsedType(Result, ResultTInfo); 1230 } 1231 1232 static OpenCLAccessAttr::Spelling 1233 getImageAccess(const ParsedAttributesView &Attrs) { 1234 for (const ParsedAttr &AL : Attrs) 1235 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess) 1236 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling()); 1237 return OpenCLAccessAttr::Keyword_read_only; 1238 } 1239 1240 /// Convert the specified declspec to the appropriate type 1241 /// object. 1242 /// \param state Specifies the declarator containing the declaration specifier 1243 /// to be converted, along with other associated processing state. 1244 /// \returns The type described by the declaration specifiers. This function 1245 /// never returns null. 1246 static QualType ConvertDeclSpecToType(TypeProcessingState &state) { 1247 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 1248 // checking. 1249 1250 Sema &S = state.getSema(); 1251 Declarator &declarator = state.getDeclarator(); 1252 DeclSpec &DS = declarator.getMutableDeclSpec(); 1253 SourceLocation DeclLoc = declarator.getIdentifierLoc(); 1254 if (DeclLoc.isInvalid()) 1255 DeclLoc = DS.getBeginLoc(); 1256 1257 ASTContext &Context = S.Context; 1258 1259 QualType Result; 1260 switch (DS.getTypeSpecType()) { 1261 case DeclSpec::TST_void: 1262 Result = Context.VoidTy; 1263 break; 1264 case DeclSpec::TST_char: 1265 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 1266 Result = Context.CharTy; 1267 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 1268 Result = Context.SignedCharTy; 1269 else { 1270 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 1271 "Unknown TSS value"); 1272 Result = Context.UnsignedCharTy; 1273 } 1274 break; 1275 case DeclSpec::TST_wchar: 1276 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 1277 Result = Context.WCharTy; 1278 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 1279 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 1280 << DS.getSpecifierName(DS.getTypeSpecType(), 1281 Context.getPrintingPolicy()); 1282 Result = Context.getSignedWCharType(); 1283 } else { 1284 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 1285 "Unknown TSS value"); 1286 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 1287 << DS.getSpecifierName(DS.getTypeSpecType(), 1288 Context.getPrintingPolicy()); 1289 Result = Context.getUnsignedWCharType(); 1290 } 1291 break; 1292 case DeclSpec::TST_char8: 1293 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 1294 "Unknown TSS value"); 1295 Result = Context.Char8Ty; 1296 break; 1297 case DeclSpec::TST_char16: 1298 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 1299 "Unknown TSS value"); 1300 Result = Context.Char16Ty; 1301 break; 1302 case DeclSpec::TST_char32: 1303 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 1304 "Unknown TSS value"); 1305 Result = Context.Char32Ty; 1306 break; 1307 case DeclSpec::TST_unspecified: 1308 // If this is a missing declspec in a block literal return context, then it 1309 // is inferred from the return statements inside the block. 1310 // The declspec is always missing in a lambda expr context; it is either 1311 // specified with a trailing return type or inferred. 1312 if (S.getLangOpts().CPlusPlus14 && 1313 declarator.getContext() == DeclaratorContext::LambdaExprContext) { 1314 // In C++1y, a lambda's implicit return type is 'auto'. 1315 Result = Context.getAutoDeductType(); 1316 break; 1317 } else if (declarator.getContext() == 1318 DeclaratorContext::LambdaExprContext || 1319 checkOmittedBlockReturnType(S, declarator, 1320 Context.DependentTy)) { 1321 Result = Context.DependentTy; 1322 break; 1323 } 1324 1325 // Unspecified typespec defaults to int in C90. However, the C90 grammar 1326 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 1327 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 1328 // Note that the one exception to this is function definitions, which are 1329 // allowed to be completely missing a declspec. This is handled in the 1330 // parser already though by it pretending to have seen an 'int' in this 1331 // case. 1332 if (S.getLangOpts().ImplicitInt) { 1333 // In C89 mode, we only warn if there is a completely missing declspec 1334 // when one is not allowed. 1335 if (DS.isEmpty()) { 1336 S.Diag(DeclLoc, diag::ext_missing_declspec) 1337 << DS.getSourceRange() 1338 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int"); 1339 } 1340 } else if (!DS.hasTypeSpecifier()) { 1341 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 1342 // "At least one type specifier shall be given in the declaration 1343 // specifiers in each declaration, and in the specifier-qualifier list in 1344 // each struct declaration and type name." 1345 if (S.getLangOpts().CPlusPlus) { 1346 S.Diag(DeclLoc, diag::err_missing_type_specifier) 1347 << DS.getSourceRange(); 1348 1349 // When this occurs in C++ code, often something is very broken with the 1350 // value being declared, poison it as invalid so we don't get chains of 1351 // errors. 1352 declarator.setInvalidType(true); 1353 } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){ 1354 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type) 1355 << DS.getSourceRange(); 1356 declarator.setInvalidType(true); 1357 } else { 1358 S.Diag(DeclLoc, diag::ext_missing_type_specifier) 1359 << DS.getSourceRange(); 1360 } 1361 } 1362 1363 LLVM_FALLTHROUGH; 1364 case DeclSpec::TST_int: { 1365 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 1366 switch (DS.getTypeSpecWidth()) { 1367 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 1368 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 1369 case DeclSpec::TSW_long: Result = Context.LongTy; break; 1370 case DeclSpec::TSW_longlong: 1371 Result = Context.LongLongTy; 1372 1373 // 'long long' is a C99 or C++11 feature. 1374 if (!S.getLangOpts().C99) { 1375 if (S.getLangOpts().CPlusPlus) 1376 S.Diag(DS.getTypeSpecWidthLoc(), 1377 S.getLangOpts().CPlusPlus11 ? 1378 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 1379 else 1380 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 1381 } 1382 break; 1383 } 1384 } else { 1385 switch (DS.getTypeSpecWidth()) { 1386 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 1387 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 1388 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 1389 case DeclSpec::TSW_longlong: 1390 Result = Context.UnsignedLongLongTy; 1391 1392 // 'long long' is a C99 or C++11 feature. 1393 if (!S.getLangOpts().C99) { 1394 if (S.getLangOpts().CPlusPlus) 1395 S.Diag(DS.getTypeSpecWidthLoc(), 1396 S.getLangOpts().CPlusPlus11 ? 1397 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 1398 else 1399 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 1400 } 1401 break; 1402 } 1403 } 1404 break; 1405 } 1406 case DeclSpec::TST_accum: { 1407 switch (DS.getTypeSpecWidth()) { 1408 case DeclSpec::TSW_short: 1409 Result = Context.ShortAccumTy; 1410 break; 1411 case DeclSpec::TSW_unspecified: 1412 Result = Context.AccumTy; 1413 break; 1414 case DeclSpec::TSW_long: 1415 Result = Context.LongAccumTy; 1416 break; 1417 case DeclSpec::TSW_longlong: 1418 llvm_unreachable("Unable to specify long long as _Accum width"); 1419 } 1420 1421 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) 1422 Result = Context.getCorrespondingUnsignedType(Result); 1423 1424 if (DS.isTypeSpecSat()) 1425 Result = Context.getCorrespondingSaturatedType(Result); 1426 1427 break; 1428 } 1429 case DeclSpec::TST_fract: { 1430 switch (DS.getTypeSpecWidth()) { 1431 case DeclSpec::TSW_short: 1432 Result = Context.ShortFractTy; 1433 break; 1434 case DeclSpec::TSW_unspecified: 1435 Result = Context.FractTy; 1436 break; 1437 case DeclSpec::TSW_long: 1438 Result = Context.LongFractTy; 1439 break; 1440 case DeclSpec::TSW_longlong: 1441 llvm_unreachable("Unable to specify long long as _Fract width"); 1442 } 1443 1444 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) 1445 Result = Context.getCorrespondingUnsignedType(Result); 1446 1447 if (DS.isTypeSpecSat()) 1448 Result = Context.getCorrespondingSaturatedType(Result); 1449 1450 break; 1451 } 1452 case DeclSpec::TST_int128: 1453 if (!S.Context.getTargetInfo().hasInt128Type() && 1454 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) 1455 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) 1456 << "__int128"; 1457 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) 1458 Result = Context.UnsignedInt128Ty; 1459 else 1460 Result = Context.Int128Ty; 1461 break; 1462 case DeclSpec::TST_float16: 1463 // CUDA host and device may have different _Float16 support, therefore 1464 // do not diagnose _Float16 usage to avoid false alarm. 1465 // ToDo: more precise diagnostics for CUDA. 1466 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA && 1467 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) 1468 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) 1469 << "_Float16"; 1470 Result = Context.Float16Ty; 1471 break; 1472 case DeclSpec::TST_half: Result = Context.HalfTy; break; 1473 case DeclSpec::TST_float: Result = Context.FloatTy; break; 1474 case DeclSpec::TST_double: 1475 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 1476 Result = Context.LongDoubleTy; 1477 else 1478 Result = Context.DoubleTy; 1479 break; 1480 case DeclSpec::TST_float128: 1481 if (!S.Context.getTargetInfo().hasFloat128Type() && 1482 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) 1483 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) 1484 << "__float128"; 1485 Result = Context.Float128Ty; 1486 break; 1487 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 1488 break; 1489 case DeclSpec::TST_decimal32: // _Decimal32 1490 case DeclSpec::TST_decimal64: // _Decimal64 1491 case DeclSpec::TST_decimal128: // _Decimal128 1492 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 1493 Result = Context.IntTy; 1494 declarator.setInvalidType(true); 1495 break; 1496 case DeclSpec::TST_class: 1497 case DeclSpec::TST_enum: 1498 case DeclSpec::TST_union: 1499 case DeclSpec::TST_struct: 1500 case DeclSpec::TST_interface: { 1501 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()); 1502 if (!D) { 1503 // This can happen in C++ with ambiguous lookups. 1504 Result = Context.IntTy; 1505 declarator.setInvalidType(true); 1506 break; 1507 } 1508 1509 // If the type is deprecated or unavailable, diagnose it. 1510 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); 1511 1512 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 1513 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!"); 1514 1515 // TypeQuals handled by caller. 1516 Result = Context.getTypeDeclType(D); 1517 1518 // In both C and C++, make an ElaboratedType. 1519 ElaboratedTypeKeyword Keyword 1520 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); 1521 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result, 1522 DS.isTypeSpecOwned() ? D : nullptr); 1523 break; 1524 } 1525 case DeclSpec::TST_typename: { 1526 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 1527 DS.getTypeSpecSign() == 0 && 1528 "Can't handle qualifiers on typedef names yet!"); 1529 Result = S.GetTypeFromParser(DS.getRepAsType()); 1530 if (Result.isNull()) { 1531 declarator.setInvalidType(true); 1532 } 1533 1534 // TypeQuals handled by caller. 1535 break; 1536 } 1537 case DeclSpec::TST_typeofType: 1538 // FIXME: Preserve type source info. 1539 Result = S.GetTypeFromParser(DS.getRepAsType()); 1540 assert(!Result.isNull() && "Didn't get a type for typeof?"); 1541 if (!Result->isDependentType()) 1542 if (const TagType *TT = Result->getAs<TagType>()) 1543 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); 1544 // TypeQuals handled by caller. 1545 Result = Context.getTypeOfType(Result); 1546 break; 1547 case DeclSpec::TST_typeofExpr: { 1548 Expr *E = DS.getRepAsExpr(); 1549 assert(E && "Didn't get an expression for typeof?"); 1550 // TypeQuals handled by caller. 1551 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); 1552 if (Result.isNull()) { 1553 Result = Context.IntTy; 1554 declarator.setInvalidType(true); 1555 } 1556 break; 1557 } 1558 case DeclSpec::TST_decltype: { 1559 Expr *E = DS.getRepAsExpr(); 1560 assert(E && "Didn't get an expression for decltype?"); 1561 // TypeQuals handled by caller. 1562 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); 1563 if (Result.isNull()) { 1564 Result = Context.IntTy; 1565 declarator.setInvalidType(true); 1566 } 1567 break; 1568 } 1569 case DeclSpec::TST_underlyingType: 1570 Result = S.GetTypeFromParser(DS.getRepAsType()); 1571 assert(!Result.isNull() && "Didn't get a type for __underlying_type?"); 1572 Result = S.BuildUnaryTransformType(Result, 1573 UnaryTransformType::EnumUnderlyingType, 1574 DS.getTypeSpecTypeLoc()); 1575 if (Result.isNull()) { 1576 Result = Context.IntTy; 1577 declarator.setInvalidType(true); 1578 } 1579 break; 1580 1581 case DeclSpec::TST_auto: 1582 Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false); 1583 break; 1584 1585 case DeclSpec::TST_auto_type: 1586 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false); 1587 break; 1588 1589 case DeclSpec::TST_decltype_auto: 1590 Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto, 1591 /*IsDependent*/ false); 1592 break; 1593 1594 case DeclSpec::TST_unknown_anytype: 1595 Result = Context.UnknownAnyTy; 1596 break; 1597 1598 case DeclSpec::TST_atomic: 1599 Result = S.GetTypeFromParser(DS.getRepAsType()); 1600 assert(!Result.isNull() && "Didn't get a type for _Atomic?"); 1601 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); 1602 if (Result.isNull()) { 1603 Result = Context.IntTy; 1604 declarator.setInvalidType(true); 1605 } 1606 break; 1607 1608 #define GENERIC_IMAGE_TYPE(ImgType, Id) \ 1609 case DeclSpec::TST_##ImgType##_t: \ 1610 switch (getImageAccess(DS.getAttributes())) { \ 1611 case OpenCLAccessAttr::Keyword_write_only: \ 1612 Result = Context.Id##WOTy; \ 1613 break; \ 1614 case OpenCLAccessAttr::Keyword_read_write: \ 1615 Result = Context.Id##RWTy; \ 1616 break; \ 1617 case OpenCLAccessAttr::Keyword_read_only: \ 1618 Result = Context.Id##ROTy; \ 1619 break; \ 1620 } \ 1621 break; 1622 #include "clang/Basic/OpenCLImageTypes.def" 1623 1624 case DeclSpec::TST_error: 1625 Result = Context.IntTy; 1626 declarator.setInvalidType(true); 1627 break; 1628 } 1629 1630 if (S.getLangOpts().OpenCL && 1631 S.checkOpenCLDisabledTypeDeclSpec(DS, Result)) 1632 declarator.setInvalidType(true); 1633 1634 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum || 1635 DS.getTypeSpecType() == DeclSpec::TST_fract; 1636 1637 // Only fixed point types can be saturated 1638 if (DS.isTypeSpecSat() && !IsFixedPointType) 1639 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec) 1640 << DS.getSpecifierName(DS.getTypeSpecType(), 1641 Context.getPrintingPolicy()); 1642 1643 // Handle complex types. 1644 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 1645 if (S.getLangOpts().Freestanding) 1646 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 1647 Result = Context.getComplexType(Result); 1648 } else if (DS.isTypeAltiVecVector()) { 1649 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); 1650 assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); 1651 VectorType::VectorKind VecKind = VectorType::AltiVecVector; 1652 if (DS.isTypeAltiVecPixel()) 1653 VecKind = VectorType::AltiVecPixel; 1654 else if (DS.isTypeAltiVecBool()) 1655 VecKind = VectorType::AltiVecBool; 1656 Result = Context.getVectorType(Result, 128/typeSize, VecKind); 1657 } 1658 1659 // FIXME: Imaginary. 1660 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) 1661 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); 1662 1663 // Before we process any type attributes, synthesize a block literal 1664 // function declarator if necessary. 1665 if (declarator.getContext() == DeclaratorContext::BlockLiteralContext) 1666 maybeSynthesizeBlockSignature(state, Result); 1667 1668 // Apply any type attributes from the decl spec. This may cause the 1669 // list of type attributes to be temporarily saved while the type 1670 // attributes are pushed around. 1671 // pipe attributes will be handled later ( at GetFullTypeForDeclarator ) 1672 if (!DS.isTypeSpecPipe()) 1673 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes()); 1674 1675 // Apply const/volatile/restrict qualifiers to T. 1676 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 1677 // Warn about CV qualifiers on function types. 1678 // C99 6.7.3p8: 1679 // If the specification of a function type includes any type qualifiers, 1680 // the behavior is undefined. 1681 // C++11 [dcl.fct]p7: 1682 // The effect of a cv-qualifier-seq in a function declarator is not the 1683 // same as adding cv-qualification on top of the function type. In the 1684 // latter case, the cv-qualifiers are ignored. 1685 if (TypeQuals && Result->isFunctionType()) { 1686 diagnoseAndRemoveTypeQualifiers( 1687 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile, 1688 S.getLangOpts().CPlusPlus 1689 ? diag::warn_typecheck_function_qualifiers_ignored 1690 : diag::warn_typecheck_function_qualifiers_unspecified); 1691 // No diagnostic for 'restrict' or '_Atomic' applied to a 1692 // function type; we'll diagnose those later, in BuildQualifiedType. 1693 } 1694 1695 // C++11 [dcl.ref]p1: 1696 // Cv-qualified references are ill-formed except when the 1697 // cv-qualifiers are introduced through the use of a typedef-name 1698 // or decltype-specifier, in which case the cv-qualifiers are ignored. 1699 // 1700 // There don't appear to be any other contexts in which a cv-qualified 1701 // reference type could be formed, so the 'ill-formed' clause here appears 1702 // to never happen. 1703 if (TypeQuals && Result->isReferenceType()) { 1704 diagnoseAndRemoveTypeQualifiers( 1705 S, DS, TypeQuals, Result, 1706 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic, 1707 diag::warn_typecheck_reference_qualifiers); 1708 } 1709 1710 // C90 6.5.3 constraints: "The same type qualifier shall not appear more 1711 // than once in the same specifier-list or qualifier-list, either directly 1712 // or via one or more typedefs." 1713 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus 1714 && TypeQuals & Result.getCVRQualifiers()) { 1715 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { 1716 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) 1717 << "const"; 1718 } 1719 1720 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { 1721 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) 1722 << "volatile"; 1723 } 1724 1725 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to 1726 // produce a warning in this case. 1727 } 1728 1729 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); 1730 1731 // If adding qualifiers fails, just use the unqualified type. 1732 if (Qualified.isNull()) 1733 declarator.setInvalidType(true); 1734 else 1735 Result = Qualified; 1736 } 1737 1738 assert(!Result.isNull() && "This function should not return a null type"); 1739 return Result; 1740 } 1741 1742 static std::string getPrintableNameForEntity(DeclarationName Entity) { 1743 if (Entity) 1744 return Entity.getAsString(); 1745 1746 return "type name"; 1747 } 1748 1749 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 1750 Qualifiers Qs, const DeclSpec *DS) { 1751 if (T.isNull()) 1752 return QualType(); 1753 1754 // Ignore any attempt to form a cv-qualified reference. 1755 if (T->isReferenceType()) { 1756 Qs.removeConst(); 1757 Qs.removeVolatile(); 1758 } 1759 1760 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 1761 // object or incomplete types shall not be restrict-qualified." 1762 if (Qs.hasRestrict()) { 1763 unsigned DiagID = 0; 1764 QualType ProblemTy; 1765 1766 if (T->isAnyPointerType() || T->isReferenceType() || 1767 T->isMemberPointerType()) { 1768 QualType EltTy; 1769 if (T->isObjCObjectPointerType()) 1770 EltTy = T; 1771 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) 1772 EltTy = PTy->getPointeeType(); 1773 else 1774 EltTy = T->getPointeeType(); 1775 1776 // If we have a pointer or reference, the pointee must have an object 1777 // incomplete type. 1778 if (!EltTy->isIncompleteOrObjectType()) { 1779 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 1780 ProblemTy = EltTy; 1781 } 1782 } else if (!T->isDependentType()) { 1783 DiagID = diag::err_typecheck_invalid_restrict_not_pointer; 1784 ProblemTy = T; 1785 } 1786 1787 if (DiagID) { 1788 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; 1789 Qs.removeRestrict(); 1790 } 1791 } 1792 1793 return Context.getQualifiedType(T, Qs); 1794 } 1795 1796 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 1797 unsigned CVRAU, const DeclSpec *DS) { 1798 if (T.isNull()) 1799 return QualType(); 1800 1801 // Ignore any attempt to form a cv-qualified reference. 1802 if (T->isReferenceType()) 1803 CVRAU &= 1804 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic); 1805 1806 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and 1807 // TQ_unaligned; 1808 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned); 1809 1810 // C11 6.7.3/5: 1811 // If the same qualifier appears more than once in the same 1812 // specifier-qualifier-list, either directly or via one or more typedefs, 1813 // the behavior is the same as if it appeared only once. 1814 // 1815 // It's not specified what happens when the _Atomic qualifier is applied to 1816 // a type specified with the _Atomic specifier, but we assume that this 1817 // should be treated as if the _Atomic qualifier appeared multiple times. 1818 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) { 1819 // C11 6.7.3/5: 1820 // If other qualifiers appear along with the _Atomic qualifier in a 1821 // specifier-qualifier-list, the resulting type is the so-qualified 1822 // atomic type. 1823 // 1824 // Don't need to worry about array types here, since _Atomic can't be 1825 // applied to such types. 1826 SplitQualType Split = T.getSplitUnqualifiedType(); 1827 T = BuildAtomicType(QualType(Split.Ty, 0), 1828 DS ? DS->getAtomicSpecLoc() : Loc); 1829 if (T.isNull()) 1830 return T; 1831 Split.Quals.addCVRQualifiers(CVR); 1832 return BuildQualifiedType(T, Loc, Split.Quals); 1833 } 1834 1835 Qualifiers Q = Qualifiers::fromCVRMask(CVR); 1836 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned); 1837 return BuildQualifiedType(T, Loc, Q, DS); 1838 } 1839 1840 /// Build a paren type including \p T. 1841 QualType Sema::BuildParenType(QualType T) { 1842 return Context.getParenType(T); 1843 } 1844 1845 /// Given that we're building a pointer or reference to the given 1846 static QualType inferARCLifetimeForPointee(Sema &S, QualType type, 1847 SourceLocation loc, 1848 bool isReference) { 1849 // Bail out if retention is unrequired or already specified. 1850 if (!type->isObjCLifetimeType() || 1851 type.getObjCLifetime() != Qualifiers::OCL_None) 1852 return type; 1853 1854 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; 1855 1856 // If the object type is const-qualified, we can safely use 1857 // __unsafe_unretained. This is safe (because there are no read 1858 // barriers), and it'll be safe to coerce anything but __weak* to 1859 // the resulting type. 1860 if (type.isConstQualified()) { 1861 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1862 1863 // Otherwise, check whether the static type does not require 1864 // retaining. This currently only triggers for Class (possibly 1865 // protocol-qualifed, and arrays thereof). 1866 } else if (type->isObjCARCImplicitlyUnretainedType()) { 1867 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1868 1869 // If we are in an unevaluated context, like sizeof, skip adding a 1870 // qualification. 1871 } else if (S.isUnevaluatedContext()) { 1872 return type; 1873 1874 // If that failed, give an error and recover using __strong. __strong 1875 // is the option most likely to prevent spurious second-order diagnostics, 1876 // like when binding a reference to a field. 1877 } else { 1878 // These types can show up in private ivars in system headers, so 1879 // we need this to not be an error in those cases. Instead we 1880 // want to delay. 1881 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 1882 S.DelayedDiagnostics.add( 1883 sema::DelayedDiagnostic::makeForbiddenType(loc, 1884 diag::err_arc_indirect_no_ownership, type, isReference)); 1885 } else { 1886 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; 1887 } 1888 implicitLifetime = Qualifiers::OCL_Strong; 1889 } 1890 assert(implicitLifetime && "didn't infer any lifetime!"); 1891 1892 Qualifiers qs; 1893 qs.addObjCLifetime(implicitLifetime); 1894 return S.Context.getQualifiedType(type, qs); 1895 } 1896 1897 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ 1898 std::string Quals = FnTy->getMethodQuals().getAsString(); 1899 1900 switch (FnTy->getRefQualifier()) { 1901 case RQ_None: 1902 break; 1903 1904 case RQ_LValue: 1905 if (!Quals.empty()) 1906 Quals += ' '; 1907 Quals += '&'; 1908 break; 1909 1910 case RQ_RValue: 1911 if (!Quals.empty()) 1912 Quals += ' '; 1913 Quals += "&&"; 1914 break; 1915 } 1916 1917 return Quals; 1918 } 1919 1920 namespace { 1921 /// Kinds of declarator that cannot contain a qualified function type. 1922 /// 1923 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: 1924 /// a function type with a cv-qualifier or a ref-qualifier can only appear 1925 /// at the topmost level of a type. 1926 /// 1927 /// Parens and member pointers are permitted. We don't diagnose array and 1928 /// function declarators, because they don't allow function types at all. 1929 /// 1930 /// The values of this enum are used in diagnostics. 1931 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference }; 1932 } // end anonymous namespace 1933 1934 /// Check whether the type T is a qualified function type, and if it is, 1935 /// diagnose that it cannot be contained within the given kind of declarator. 1936 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, 1937 QualifiedFunctionKind QFK) { 1938 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 1939 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); 1940 if (!FPT || (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) 1941 return false; 1942 1943 S.Diag(Loc, diag::err_compound_qualified_function_type) 1944 << QFK << isa<FunctionType>(T.IgnoreParens()) << T 1945 << getFunctionQualifiersAsString(FPT); 1946 return true; 1947 } 1948 1949 /// Build a pointer type. 1950 /// 1951 /// \param T The type to which we'll be building a pointer. 1952 /// 1953 /// \param Loc The location of the entity whose type involves this 1954 /// pointer type or, if there is no such entity, the location of the 1955 /// type that will have pointer type. 1956 /// 1957 /// \param Entity The name of the entity that involves the pointer 1958 /// type, if known. 1959 /// 1960 /// \returns A suitable pointer type, if there are no 1961 /// errors. Otherwise, returns a NULL type. 1962 QualType Sema::BuildPointerType(QualType T, 1963 SourceLocation Loc, DeclarationName Entity) { 1964 if (T->isReferenceType()) { 1965 // C++ 8.3.2p4: There shall be no ... pointers to references ... 1966 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 1967 << getPrintableNameForEntity(Entity) << T; 1968 return QualType(); 1969 } 1970 1971 if (T->isFunctionType() && getLangOpts().OpenCL) { 1972 Diag(Loc, diag::err_opencl_function_pointer); 1973 return QualType(); 1974 } 1975 1976 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer)) 1977 return QualType(); 1978 1979 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); 1980 1981 // In ARC, it is forbidden to build pointers to unqualified pointers. 1982 if (getLangOpts().ObjCAutoRefCount) 1983 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); 1984 1985 // Build the pointer type. 1986 return Context.getPointerType(T); 1987 } 1988 1989 /// Build a reference type. 1990 /// 1991 /// \param T The type to which we'll be building a reference. 1992 /// 1993 /// \param Loc The location of the entity whose type involves this 1994 /// reference type or, if there is no such entity, the location of the 1995 /// type that will have reference type. 1996 /// 1997 /// \param Entity The name of the entity that involves the reference 1998 /// type, if known. 1999 /// 2000 /// \returns A suitable reference type, if there are no 2001 /// errors. Otherwise, returns a NULL type. 2002 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, 2003 SourceLocation Loc, 2004 DeclarationName Entity) { 2005 assert(Context.getCanonicalType(T) != Context.OverloadTy && 2006 "Unresolved overloaded function type"); 2007 2008 // C++0x [dcl.ref]p6: 2009 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a 2010 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a 2011 // type T, an attempt to create the type "lvalue reference to cv TR" creates 2012 // the type "lvalue reference to T", while an attempt to create the type 2013 // "rvalue reference to cv TR" creates the type TR. 2014 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); 2015 2016 // C++ [dcl.ref]p4: There shall be no references to references. 2017 // 2018 // According to C++ DR 106, references to references are only 2019 // diagnosed when they are written directly (e.g., "int & &"), 2020 // but not when they happen via a typedef: 2021 // 2022 // typedef int& intref; 2023 // typedef intref& intref2; 2024 // 2025 // Parser::ParseDeclaratorInternal diagnoses the case where 2026 // references are written directly; here, we handle the 2027 // collapsing of references-to-references as described in C++0x. 2028 // DR 106 and 540 introduce reference-collapsing into C++98/03. 2029 2030 // C++ [dcl.ref]p1: 2031 // A declarator that specifies the type "reference to cv void" 2032 // is ill-formed. 2033 if (T->isVoidType()) { 2034 Diag(Loc, diag::err_reference_to_void); 2035 return QualType(); 2036 } 2037 2038 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference)) 2039 return QualType(); 2040 2041 // In ARC, it is forbidden to build references to unqualified pointers. 2042 if (getLangOpts().ObjCAutoRefCount) 2043 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); 2044 2045 // Handle restrict on references. 2046 if (LValueRef) 2047 return Context.getLValueReferenceType(T, SpelledAsLValue); 2048 return Context.getRValueReferenceType(T); 2049 } 2050 2051 /// Build a Read-only Pipe type. 2052 /// 2053 /// \param T The type to which we'll be building a Pipe. 2054 /// 2055 /// \param Loc We do not use it for now. 2056 /// 2057 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a 2058 /// NULL type. 2059 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) { 2060 return Context.getReadPipeType(T); 2061 } 2062 2063 /// Build a Write-only Pipe type. 2064 /// 2065 /// \param T The type to which we'll be building a Pipe. 2066 /// 2067 /// \param Loc We do not use it for now. 2068 /// 2069 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a 2070 /// NULL type. 2071 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) { 2072 return Context.getWritePipeType(T); 2073 } 2074 2075 /// Check whether the specified array size makes the array type a VLA. If so, 2076 /// return true, if not, return the size of the array in SizeVal. 2077 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) { 2078 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode 2079 // (like gnu99, but not c99) accept any evaluatable value as an extension. 2080 class VLADiagnoser : public Sema::VerifyICEDiagnoser { 2081 public: 2082 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {} 2083 2084 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 2085 } 2086 2087 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override { 2088 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR; 2089 } 2090 } Diagnoser; 2091 2092 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser, 2093 S.LangOpts.GNUMode || 2094 S.LangOpts.OpenCL).isInvalid(); 2095 } 2096 2097 /// Build an array type. 2098 /// 2099 /// \param T The type of each element in the array. 2100 /// 2101 /// \param ASM C99 array size modifier (e.g., '*', 'static'). 2102 /// 2103 /// \param ArraySize Expression describing the size of the array. 2104 /// 2105 /// \param Brackets The range from the opening '[' to the closing ']'. 2106 /// 2107 /// \param Entity The name of the entity that involves the array 2108 /// type, if known. 2109 /// 2110 /// \returns A suitable array type, if there are no errors. Otherwise, 2111 /// returns a NULL type. 2112 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 2113 Expr *ArraySize, unsigned Quals, 2114 SourceRange Brackets, DeclarationName Entity) { 2115 2116 SourceLocation Loc = Brackets.getBegin(); 2117 if (getLangOpts().CPlusPlus) { 2118 // C++ [dcl.array]p1: 2119 // T is called the array element type; this type shall not be a reference 2120 // type, the (possibly cv-qualified) type void, a function type or an 2121 // abstract class type. 2122 // 2123 // C++ [dcl.array]p3: 2124 // When several "array of" specifications are adjacent, [...] only the 2125 // first of the constant expressions that specify the bounds of the arrays 2126 // may be omitted. 2127 // 2128 // Note: function types are handled in the common path with C. 2129 if (T->isReferenceType()) { 2130 Diag(Loc, diag::err_illegal_decl_array_of_references) 2131 << getPrintableNameForEntity(Entity) << T; 2132 return QualType(); 2133 } 2134 2135 if (T->isVoidType() || T->isIncompleteArrayType()) { 2136 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; 2137 return QualType(); 2138 } 2139 2140 if (RequireNonAbstractType(Brackets.getBegin(), T, 2141 diag::err_array_of_abstract_type)) 2142 return QualType(); 2143 2144 // Mentioning a member pointer type for an array type causes us to lock in 2145 // an inheritance model, even if it's inside an unused typedef. 2146 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 2147 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) 2148 if (!MPTy->getClass()->isDependentType()) 2149 (void)isCompleteType(Loc, T); 2150 2151 } else { 2152 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 2153 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 2154 if (RequireCompleteType(Loc, T, 2155 diag::err_illegal_decl_array_incomplete_type)) 2156 return QualType(); 2157 } 2158 2159 if (T->isFunctionType()) { 2160 Diag(Loc, diag::err_illegal_decl_array_of_functions) 2161 << getPrintableNameForEntity(Entity) << T; 2162 return QualType(); 2163 } 2164 2165 if (const RecordType *EltTy = T->getAs<RecordType>()) { 2166 // If the element type is a struct or union that contains a variadic 2167 // array, accept it as a GNU extension: C99 6.7.2.1p2. 2168 if (EltTy->getDecl()->hasFlexibleArrayMember()) 2169 Diag(Loc, diag::ext_flexible_array_in_array) << T; 2170 } else if (T->isObjCObjectType()) { 2171 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 2172 return QualType(); 2173 } 2174 2175 // Do placeholder conversions on the array size expression. 2176 if (ArraySize && ArraySize->hasPlaceholderType()) { 2177 ExprResult Result = CheckPlaceholderExpr(ArraySize); 2178 if (Result.isInvalid()) return QualType(); 2179 ArraySize = Result.get(); 2180 } 2181 2182 // Do lvalue-to-rvalue conversions on the array size expression. 2183 if (ArraySize && !ArraySize->isRValue()) { 2184 ExprResult Result = DefaultLvalueConversion(ArraySize); 2185 if (Result.isInvalid()) 2186 return QualType(); 2187 2188 ArraySize = Result.get(); 2189 } 2190 2191 // C99 6.7.5.2p1: The size expression shall have integer type. 2192 // C++11 allows contextual conversions to such types. 2193 if (!getLangOpts().CPlusPlus11 && 2194 ArraySize && !ArraySize->isTypeDependent() && 2195 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 2196 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int) 2197 << ArraySize->getType() << ArraySize->getSourceRange(); 2198 return QualType(); 2199 } 2200 2201 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); 2202 if (!ArraySize) { 2203 if (ASM == ArrayType::Star) 2204 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets); 2205 else 2206 T = Context.getIncompleteArrayType(T, ASM, Quals); 2207 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { 2208 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 2209 } else if ((!T->isDependentType() && !T->isIncompleteType() && 2210 !T->isConstantSizeType()) || 2211 isArraySizeVLA(*this, ArraySize, ConstVal)) { 2212 // Even in C++11, don't allow contextual conversions in the array bound 2213 // of a VLA. 2214 if (getLangOpts().CPlusPlus11 && 2215 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 2216 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int) 2217 << ArraySize->getType() << ArraySize->getSourceRange(); 2218 return QualType(); 2219 } 2220 2221 // C99: an array with an element type that has a non-constant-size is a VLA. 2222 // C99: an array with a non-ICE size is a VLA. We accept any expression 2223 // that we can fold to a non-zero positive value as an extension. 2224 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 2225 } else { 2226 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 2227 // have a value greater than zero. 2228 if (ConstVal.isSigned() && ConstVal.isNegative()) { 2229 if (Entity) 2230 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size) 2231 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); 2232 else 2233 Diag(ArraySize->getBeginLoc(), diag::err_typecheck_negative_array_size) 2234 << ArraySize->getSourceRange(); 2235 return QualType(); 2236 } 2237 if (ConstVal == 0) { 2238 // GCC accepts zero sized static arrays. We allow them when 2239 // we're not in a SFINAE context. 2240 Diag(ArraySize->getBeginLoc(), isSFINAEContext() 2241 ? diag::err_typecheck_zero_array_size 2242 : diag::ext_typecheck_zero_array_size) 2243 << ArraySize->getSourceRange(); 2244 2245 if (ASM == ArrayType::Static) { 2246 Diag(ArraySize->getBeginLoc(), 2247 diag::warn_typecheck_zero_static_array_size) 2248 << ArraySize->getSourceRange(); 2249 ASM = ArrayType::Normal; 2250 } 2251 } else if (!T->isDependentType() && !T->isVariablyModifiedType() && 2252 !T->isIncompleteType() && !T->isUndeducedType()) { 2253 // Is the array too large? 2254 unsigned ActiveSizeBits 2255 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); 2256 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 2257 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large) 2258 << ConstVal.toString(10) << ArraySize->getSourceRange(); 2259 return QualType(); 2260 } 2261 } 2262 2263 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); 2264 } 2265 2266 // OpenCL v1.2 s6.9.d: variable length arrays are not supported. 2267 if (getLangOpts().OpenCL && T->isVariableArrayType()) { 2268 Diag(Loc, diag::err_opencl_vla); 2269 return QualType(); 2270 } 2271 2272 if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) { 2273 // CUDA device code and some other targets don't support VLAs. 2274 targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) 2275 ? diag::err_cuda_vla 2276 : diag::err_vla_unsupported) 2277 << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice) 2278 ? CurrentCUDATarget() 2279 : CFT_InvalidTarget); 2280 } 2281 2282 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 2283 if (!getLangOpts().C99) { 2284 if (T->isVariableArrayType()) { 2285 // Prohibit the use of VLAs during template argument deduction. 2286 if (isSFINAEContext()) { 2287 Diag(Loc, diag::err_vla_in_sfinae); 2288 return QualType(); 2289 } 2290 // Just extwarn about VLAs. 2291 else 2292 Diag(Loc, diag::ext_vla); 2293 } else if (ASM != ArrayType::Normal || Quals != 0) 2294 Diag(Loc, 2295 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx 2296 : diag::ext_c99_array_usage) << ASM; 2297 } 2298 2299 if (T->isVariableArrayType()) { 2300 // Warn about VLAs for -Wvla. 2301 Diag(Loc, diag::warn_vla_used); 2302 } 2303 2304 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported. 2305 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported. 2306 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported. 2307 if (getLangOpts().OpenCL) { 2308 const QualType ArrType = Context.getBaseElementType(T); 2309 if (ArrType->isBlockPointerType() || ArrType->isPipeType() || 2310 ArrType->isSamplerT() || ArrType->isImageType()) { 2311 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType; 2312 return QualType(); 2313 } 2314 } 2315 2316 return T; 2317 } 2318 2319 QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr, 2320 SourceLocation AttrLoc) { 2321 // The base type must be integer (not Boolean or enumeration) or float, and 2322 // can't already be a vector. 2323 if (!CurType->isDependentType() && 2324 (!CurType->isBuiltinType() || CurType->isBooleanType() || 2325 (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) { 2326 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType; 2327 return QualType(); 2328 } 2329 2330 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent()) 2331 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, 2332 VectorType::GenericVector); 2333 2334 llvm::APSInt VecSize(32); 2335 if (!SizeExpr->isIntegerConstantExpr(VecSize, Context)) { 2336 Diag(AttrLoc, diag::err_attribute_argument_type) 2337 << "vector_size" << AANT_ArgumentIntegerConstant 2338 << SizeExpr->getSourceRange(); 2339 return QualType(); 2340 } 2341 2342 if (CurType->isDependentType()) 2343 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, 2344 VectorType::GenericVector); 2345 2346 unsigned VectorSize = static_cast<unsigned>(VecSize.getZExtValue() * 8); 2347 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType)); 2348 2349 if (VectorSize == 0) { 2350 Diag(AttrLoc, diag::err_attribute_zero_size) << SizeExpr->getSourceRange(); 2351 return QualType(); 2352 } 2353 2354 // vecSize is specified in bytes - convert to bits. 2355 if (VectorSize % TypeSize) { 2356 Diag(AttrLoc, diag::err_attribute_invalid_size) 2357 << SizeExpr->getSourceRange(); 2358 return QualType(); 2359 } 2360 2361 if (VectorType::isVectorSizeTooLarge(VectorSize / TypeSize)) { 2362 Diag(AttrLoc, diag::err_attribute_size_too_large) 2363 << SizeExpr->getSourceRange(); 2364 return QualType(); 2365 } 2366 2367 return Context.getVectorType(CurType, VectorSize / TypeSize, 2368 VectorType::GenericVector); 2369 } 2370 2371 /// Build an ext-vector type. 2372 /// 2373 /// Run the required checks for the extended vector type. 2374 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, 2375 SourceLocation AttrLoc) { 2376 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined 2377 // in conjunction with complex types (pointers, arrays, functions, etc.). 2378 // 2379 // Additionally, OpenCL prohibits vectors of booleans (they're considered a 2380 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects 2381 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors 2382 // of bool aren't allowed. 2383 if ((!T->isDependentType() && !T->isIntegerType() && 2384 !T->isRealFloatingType()) || 2385 T->isBooleanType()) { 2386 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 2387 return QualType(); 2388 } 2389 2390 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { 2391 llvm::APSInt vecSize(32); 2392 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { 2393 Diag(AttrLoc, diag::err_attribute_argument_type) 2394 << "ext_vector_type" << AANT_ArgumentIntegerConstant 2395 << ArraySize->getSourceRange(); 2396 return QualType(); 2397 } 2398 2399 // Unlike gcc's vector_size attribute, the size is specified as the 2400 // number of elements, not the number of bytes. 2401 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 2402 2403 if (vectorSize == 0) { 2404 Diag(AttrLoc, diag::err_attribute_zero_size) 2405 << ArraySize->getSourceRange(); 2406 return QualType(); 2407 } 2408 2409 if (VectorType::isVectorSizeTooLarge(vectorSize)) { 2410 Diag(AttrLoc, diag::err_attribute_size_too_large) 2411 << ArraySize->getSourceRange(); 2412 return QualType(); 2413 } 2414 2415 return Context.getExtVectorType(T, vectorSize); 2416 } 2417 2418 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); 2419 } 2420 2421 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { 2422 if (T->isArrayType() || T->isFunctionType()) { 2423 Diag(Loc, diag::err_func_returning_array_function) 2424 << T->isFunctionType() << T; 2425 return true; 2426 } 2427 2428 // Functions cannot return half FP. 2429 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) { 2430 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << 2431 FixItHint::CreateInsertion(Loc, "*"); 2432 return true; 2433 } 2434 2435 // Methods cannot return interface types. All ObjC objects are 2436 // passed by reference. 2437 if (T->isObjCObjectType()) { 2438 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) 2439 << 0 << T << FixItHint::CreateInsertion(Loc, "*"); 2440 return true; 2441 } 2442 2443 return false; 2444 } 2445 2446 /// Check the extended parameter information. Most of the necessary 2447 /// checking should occur when applying the parameter attribute; the 2448 /// only other checks required are positional restrictions. 2449 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes, 2450 const FunctionProtoType::ExtProtoInfo &EPI, 2451 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) { 2452 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos"); 2453 2454 bool hasCheckedSwiftCall = false; 2455 auto checkForSwiftCC = [&](unsigned paramIndex) { 2456 // Only do this once. 2457 if (hasCheckedSwiftCall) return; 2458 hasCheckedSwiftCall = true; 2459 if (EPI.ExtInfo.getCC() == CC_Swift) return; 2460 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall) 2461 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI()); 2462 }; 2463 2464 for (size_t paramIndex = 0, numParams = paramTypes.size(); 2465 paramIndex != numParams; ++paramIndex) { 2466 switch (EPI.ExtParameterInfos[paramIndex].getABI()) { 2467 // Nothing interesting to check for orindary-ABI parameters. 2468 case ParameterABI::Ordinary: 2469 continue; 2470 2471 // swift_indirect_result parameters must be a prefix of the function 2472 // arguments. 2473 case ParameterABI::SwiftIndirectResult: 2474 checkForSwiftCC(paramIndex); 2475 if (paramIndex != 0 && 2476 EPI.ExtParameterInfos[paramIndex - 1].getABI() 2477 != ParameterABI::SwiftIndirectResult) { 2478 S.Diag(getParamLoc(paramIndex), 2479 diag::err_swift_indirect_result_not_first); 2480 } 2481 continue; 2482 2483 case ParameterABI::SwiftContext: 2484 checkForSwiftCC(paramIndex); 2485 continue; 2486 2487 // swift_error parameters must be preceded by a swift_context parameter. 2488 case ParameterABI::SwiftErrorResult: 2489 checkForSwiftCC(paramIndex); 2490 if (paramIndex == 0 || 2491 EPI.ExtParameterInfos[paramIndex - 1].getABI() != 2492 ParameterABI::SwiftContext) { 2493 S.Diag(getParamLoc(paramIndex), 2494 diag::err_swift_error_result_not_after_swift_context); 2495 } 2496 continue; 2497 } 2498 llvm_unreachable("bad ABI kind"); 2499 } 2500 } 2501 2502 QualType Sema::BuildFunctionType(QualType T, 2503 MutableArrayRef<QualType> ParamTypes, 2504 SourceLocation Loc, DeclarationName Entity, 2505 const FunctionProtoType::ExtProtoInfo &EPI) { 2506 bool Invalid = false; 2507 2508 Invalid |= CheckFunctionReturnType(T, Loc); 2509 2510 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { 2511 // FIXME: Loc is too inprecise here, should use proper locations for args. 2512 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); 2513 if (ParamType->isVoidType()) { 2514 Diag(Loc, diag::err_param_with_void_type); 2515 Invalid = true; 2516 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) { 2517 // Disallow half FP arguments. 2518 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << 2519 FixItHint::CreateInsertion(Loc, "*"); 2520 Invalid = true; 2521 } 2522 2523 ParamTypes[Idx] = ParamType; 2524 } 2525 2526 if (EPI.ExtParameterInfos) { 2527 checkExtParameterInfos(*this, ParamTypes, EPI, 2528 [=](unsigned i) { return Loc; }); 2529 } 2530 2531 if (EPI.ExtInfo.getProducesResult()) { 2532 // This is just a warning, so we can't fail to build if we see it. 2533 checkNSReturnsRetainedReturnType(Loc, T); 2534 } 2535 2536 if (Invalid) 2537 return QualType(); 2538 2539 return Context.getFunctionType(T, ParamTypes, EPI); 2540 } 2541 2542 /// Build a member pointer type \c T Class::*. 2543 /// 2544 /// \param T the type to which the member pointer refers. 2545 /// \param Class the class type into which the member pointer points. 2546 /// \param Loc the location where this type begins 2547 /// \param Entity the name of the entity that will have this member pointer type 2548 /// 2549 /// \returns a member pointer type, if successful, or a NULL type if there was 2550 /// an error. 2551 QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 2552 SourceLocation Loc, 2553 DeclarationName Entity) { 2554 // Verify that we're not building a pointer to pointer to function with 2555 // exception specification. 2556 if (CheckDistantExceptionSpec(T)) { 2557 Diag(Loc, diag::err_distant_exception_spec); 2558 return QualType(); 2559 } 2560 2561 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 2562 // with reference type, or "cv void." 2563 if (T->isReferenceType()) { 2564 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 2565 << getPrintableNameForEntity(Entity) << T; 2566 return QualType(); 2567 } 2568 2569 if (T->isVoidType()) { 2570 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 2571 << getPrintableNameForEntity(Entity); 2572 return QualType(); 2573 } 2574 2575 if (!Class->isDependentType() && !Class->isRecordType()) { 2576 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 2577 return QualType(); 2578 } 2579 2580 // Adjust the default free function calling convention to the default method 2581 // calling convention. 2582 bool IsCtorOrDtor = 2583 (Entity.getNameKind() == DeclarationName::CXXConstructorName) || 2584 (Entity.getNameKind() == DeclarationName::CXXDestructorName); 2585 if (T->isFunctionType()) 2586 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc); 2587 2588 return Context.getMemberPointerType(T, Class.getTypePtr()); 2589 } 2590 2591 /// Build a block pointer type. 2592 /// 2593 /// \param T The type to which we'll be building a block pointer. 2594 /// 2595 /// \param Loc The source location, used for diagnostics. 2596 /// 2597 /// \param Entity The name of the entity that involves the block pointer 2598 /// type, if known. 2599 /// 2600 /// \returns A suitable block pointer type, if there are no 2601 /// errors. Otherwise, returns a NULL type. 2602 QualType Sema::BuildBlockPointerType(QualType T, 2603 SourceLocation Loc, 2604 DeclarationName Entity) { 2605 if (!T->isFunctionType()) { 2606 Diag(Loc, diag::err_nonfunction_block_type); 2607 return QualType(); 2608 } 2609 2610 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) 2611 return QualType(); 2612 2613 return Context.getBlockPointerType(T); 2614 } 2615 2616 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 2617 QualType QT = Ty.get(); 2618 if (QT.isNull()) { 2619 if (TInfo) *TInfo = nullptr; 2620 return QualType(); 2621 } 2622 2623 TypeSourceInfo *DI = nullptr; 2624 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 2625 QT = LIT->getType(); 2626 DI = LIT->getTypeSourceInfo(); 2627 } 2628 2629 if (TInfo) *TInfo = DI; 2630 return QT; 2631 } 2632 2633 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 2634 Qualifiers::ObjCLifetime ownership, 2635 unsigned chunkIndex); 2636 2637 /// Given that this is the declaration of a parameter under ARC, 2638 /// attempt to infer attributes and such for pointer-to-whatever 2639 /// types. 2640 static void inferARCWriteback(TypeProcessingState &state, 2641 QualType &declSpecType) { 2642 Sema &S = state.getSema(); 2643 Declarator &declarator = state.getDeclarator(); 2644 2645 // TODO: should we care about decl qualifiers? 2646 2647 // Check whether the declarator has the expected form. We walk 2648 // from the inside out in order to make the block logic work. 2649 unsigned outermostPointerIndex = 0; 2650 bool isBlockPointer = false; 2651 unsigned numPointers = 0; 2652 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 2653 unsigned chunkIndex = i; 2654 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); 2655 switch (chunk.Kind) { 2656 case DeclaratorChunk::Paren: 2657 // Ignore parens. 2658 break; 2659 2660 case DeclaratorChunk::Reference: 2661 case DeclaratorChunk::Pointer: 2662 // Count the number of pointers. Treat references 2663 // interchangeably as pointers; if they're mis-ordered, normal 2664 // type building will discover that. 2665 outermostPointerIndex = chunkIndex; 2666 numPointers++; 2667 break; 2668 2669 case DeclaratorChunk::BlockPointer: 2670 // If we have a pointer to block pointer, that's an acceptable 2671 // indirect reference; anything else is not an application of 2672 // the rules. 2673 if (numPointers != 1) return; 2674 numPointers++; 2675 outermostPointerIndex = chunkIndex; 2676 isBlockPointer = true; 2677 2678 // We don't care about pointer structure in return values here. 2679 goto done; 2680 2681 case DeclaratorChunk::Array: // suppress if written (id[])? 2682 case DeclaratorChunk::Function: 2683 case DeclaratorChunk::MemberPointer: 2684 case DeclaratorChunk::Pipe: 2685 return; 2686 } 2687 } 2688 done: 2689 2690 // If we have *one* pointer, then we want to throw the qualifier on 2691 // the declaration-specifiers, which means that it needs to be a 2692 // retainable object type. 2693 if (numPointers == 1) { 2694 // If it's not a retainable object type, the rule doesn't apply. 2695 if (!declSpecType->isObjCRetainableType()) return; 2696 2697 // If it already has lifetime, don't do anything. 2698 if (declSpecType.getObjCLifetime()) return; 2699 2700 // Otherwise, modify the type in-place. 2701 Qualifiers qs; 2702 2703 if (declSpecType->isObjCARCImplicitlyUnretainedType()) 2704 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); 2705 else 2706 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); 2707 declSpecType = S.Context.getQualifiedType(declSpecType, qs); 2708 2709 // If we have *two* pointers, then we want to throw the qualifier on 2710 // the outermost pointer. 2711 } else if (numPointers == 2) { 2712 // If we don't have a block pointer, we need to check whether the 2713 // declaration-specifiers gave us something that will turn into a 2714 // retainable object pointer after we slap the first pointer on it. 2715 if (!isBlockPointer && !declSpecType->isObjCObjectType()) 2716 return; 2717 2718 // Look for an explicit lifetime attribute there. 2719 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); 2720 if (chunk.Kind != DeclaratorChunk::Pointer && 2721 chunk.Kind != DeclaratorChunk::BlockPointer) 2722 return; 2723 for (const ParsedAttr &AL : chunk.getAttrs()) 2724 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) 2725 return; 2726 2727 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, 2728 outermostPointerIndex); 2729 2730 // Any other number of pointers/references does not trigger the rule. 2731 } else return; 2732 2733 // TODO: mark whether we did this inference? 2734 } 2735 2736 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 2737 SourceLocation FallbackLoc, 2738 SourceLocation ConstQualLoc, 2739 SourceLocation VolatileQualLoc, 2740 SourceLocation RestrictQualLoc, 2741 SourceLocation AtomicQualLoc, 2742 SourceLocation UnalignedQualLoc) { 2743 if (!Quals) 2744 return; 2745 2746 struct Qual { 2747 const char *Name; 2748 unsigned Mask; 2749 SourceLocation Loc; 2750 } const QualKinds[5] = { 2751 { "const", DeclSpec::TQ_const, ConstQualLoc }, 2752 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc }, 2753 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc }, 2754 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc }, 2755 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc } 2756 }; 2757 2758 SmallString<32> QualStr; 2759 unsigned NumQuals = 0; 2760 SourceLocation Loc; 2761 FixItHint FixIts[5]; 2762 2763 // Build a string naming the redundant qualifiers. 2764 for (auto &E : QualKinds) { 2765 if (Quals & E.Mask) { 2766 if (!QualStr.empty()) QualStr += ' '; 2767 QualStr += E.Name; 2768 2769 // If we have a location for the qualifier, offer a fixit. 2770 SourceLocation QualLoc = E.Loc; 2771 if (QualLoc.isValid()) { 2772 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); 2773 if (Loc.isInvalid() || 2774 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) 2775 Loc = QualLoc; 2776 } 2777 2778 ++NumQuals; 2779 } 2780 } 2781 2782 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) 2783 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; 2784 } 2785 2786 // Diagnose pointless type qualifiers on the return type of a function. 2787 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, 2788 Declarator &D, 2789 unsigned FunctionChunkIndex) { 2790 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) { 2791 // FIXME: TypeSourceInfo doesn't preserve location information for 2792 // qualifiers. 2793 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2794 RetTy.getLocalCVRQualifiers(), 2795 D.getIdentifierLoc()); 2796 return; 2797 } 2798 2799 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, 2800 End = D.getNumTypeObjects(); 2801 OuterChunkIndex != End; ++OuterChunkIndex) { 2802 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); 2803 switch (OuterChunk.Kind) { 2804 case DeclaratorChunk::Paren: 2805 continue; 2806 2807 case DeclaratorChunk::Pointer: { 2808 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; 2809 S.diagnoseIgnoredQualifiers( 2810 diag::warn_qual_return_type, 2811 PTI.TypeQuals, 2812 SourceLocation(), 2813 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), 2814 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), 2815 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), 2816 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc), 2817 SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc)); 2818 return; 2819 } 2820 2821 case DeclaratorChunk::Function: 2822 case DeclaratorChunk::BlockPointer: 2823 case DeclaratorChunk::Reference: 2824 case DeclaratorChunk::Array: 2825 case DeclaratorChunk::MemberPointer: 2826 case DeclaratorChunk::Pipe: 2827 // FIXME: We can't currently provide an accurate source location and a 2828 // fix-it hint for these. 2829 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; 2830 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2831 RetTy.getCVRQualifiers() | AtomicQual, 2832 D.getIdentifierLoc()); 2833 return; 2834 } 2835 2836 llvm_unreachable("unknown declarator chunk kind"); 2837 } 2838 2839 // If the qualifiers come from a conversion function type, don't diagnose 2840 // them -- they're not necessarily redundant, since such a conversion 2841 // operator can be explicitly called as "x.operator const int()". 2842 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) 2843 return; 2844 2845 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers 2846 // which are present there. 2847 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2848 D.getDeclSpec().getTypeQualifiers(), 2849 D.getIdentifierLoc(), 2850 D.getDeclSpec().getConstSpecLoc(), 2851 D.getDeclSpec().getVolatileSpecLoc(), 2852 D.getDeclSpec().getRestrictSpecLoc(), 2853 D.getDeclSpec().getAtomicSpecLoc(), 2854 D.getDeclSpec().getUnalignedSpecLoc()); 2855 } 2856 2857 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, 2858 TypeSourceInfo *&ReturnTypeInfo) { 2859 Sema &SemaRef = state.getSema(); 2860 Declarator &D = state.getDeclarator(); 2861 QualType T; 2862 ReturnTypeInfo = nullptr; 2863 2864 // The TagDecl owned by the DeclSpec. 2865 TagDecl *OwnedTagDecl = nullptr; 2866 2867 switch (D.getName().getKind()) { 2868 case UnqualifiedIdKind::IK_ImplicitSelfParam: 2869 case UnqualifiedIdKind::IK_OperatorFunctionId: 2870 case UnqualifiedIdKind::IK_Identifier: 2871 case UnqualifiedIdKind::IK_LiteralOperatorId: 2872 case UnqualifiedIdKind::IK_TemplateId: 2873 T = ConvertDeclSpecToType(state); 2874 2875 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 2876 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2877 // Owned declaration is embedded in declarator. 2878 OwnedTagDecl->setEmbeddedInDeclarator(true); 2879 } 2880 break; 2881 2882 case UnqualifiedIdKind::IK_ConstructorName: 2883 case UnqualifiedIdKind::IK_ConstructorTemplateId: 2884 case UnqualifiedIdKind::IK_DestructorName: 2885 // Constructors and destructors don't have return types. Use 2886 // "void" instead. 2887 T = SemaRef.Context.VoidTy; 2888 processTypeAttrs(state, T, TAL_DeclSpec, 2889 D.getMutableDeclSpec().getAttributes()); 2890 break; 2891 2892 case UnqualifiedIdKind::IK_DeductionGuideName: 2893 // Deduction guides have a trailing return type and no type in their 2894 // decl-specifier sequence. Use a placeholder return type for now. 2895 T = SemaRef.Context.DependentTy; 2896 break; 2897 2898 case UnqualifiedIdKind::IK_ConversionFunctionId: 2899 // The result type of a conversion function is the type that it 2900 // converts to. 2901 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, 2902 &ReturnTypeInfo); 2903 break; 2904 } 2905 2906 if (!D.getAttributes().empty()) 2907 distributeTypeAttrsFromDeclarator(state, T); 2908 2909 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 2910 if (DeducedType *Deduced = T->getContainedDeducedType()) { 2911 AutoType *Auto = dyn_cast<AutoType>(Deduced); 2912 int Error = -1; 2913 2914 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or 2915 // class template argument deduction)? 2916 bool IsCXXAutoType = 2917 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType); 2918 bool IsDeducedReturnType = false; 2919 2920 switch (D.getContext()) { 2921 case DeclaratorContext::LambdaExprContext: 2922 // Declared return type of a lambda-declarator is implicit and is always 2923 // 'auto'. 2924 break; 2925 case DeclaratorContext::ObjCParameterContext: 2926 case DeclaratorContext::ObjCResultContext: 2927 case DeclaratorContext::PrototypeContext: 2928 Error = 0; 2929 break; 2930 case DeclaratorContext::LambdaExprParameterContext: 2931 // In C++14, generic lambdas allow 'auto' in their parameters. 2932 if (!SemaRef.getLangOpts().CPlusPlus14 || 2933 !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) 2934 Error = 16; 2935 else { 2936 // If auto is mentioned in a lambda parameter context, convert it to a 2937 // template parameter type. 2938 sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda(); 2939 assert(LSI && "No LambdaScopeInfo on the stack!"); 2940 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth; 2941 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size(); 2942 const bool IsParameterPack = D.hasEllipsis(); 2943 2944 // Create the TemplateTypeParmDecl here to retrieve the corresponding 2945 // template parameter type. Template parameters are temporarily added 2946 // to the TU until the associated TemplateDecl is created. 2947 TemplateTypeParmDecl *CorrespondingTemplateParam = 2948 TemplateTypeParmDecl::Create( 2949 SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(), 2950 /*KeyLoc*/ SourceLocation(), /*NameLoc*/ D.getBeginLoc(), 2951 TemplateParameterDepth, AutoParameterPosition, 2952 /*Identifier*/ nullptr, false, IsParameterPack); 2953 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam); 2954 // Replace the 'auto' in the function parameter with this invented 2955 // template type parameter. 2956 // FIXME: Retain some type sugar to indicate that this was written 2957 // as 'auto'. 2958 T = state.ReplaceAutoType( 2959 T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0)); 2960 } 2961 break; 2962 case DeclaratorContext::MemberContext: { 2963 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || 2964 D.isFunctionDeclarator()) 2965 break; 2966 bool Cxx = SemaRef.getLangOpts().CPlusPlus; 2967 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { 2968 case TTK_Enum: llvm_unreachable("unhandled tag kind"); 2969 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break; 2970 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break; 2971 case TTK_Class: Error = 5; /* Class member */ break; 2972 case TTK_Interface: Error = 6; /* Interface member */ break; 2973 } 2974 if (D.getDeclSpec().isFriendSpecified()) 2975 Error = 20; // Friend type 2976 break; 2977 } 2978 case DeclaratorContext::CXXCatchContext: 2979 case DeclaratorContext::ObjCCatchContext: 2980 Error = 7; // Exception declaration 2981 break; 2982 case DeclaratorContext::TemplateParamContext: 2983 if (isa<DeducedTemplateSpecializationType>(Deduced)) 2984 Error = 19; // Template parameter 2985 else if (!SemaRef.getLangOpts().CPlusPlus17) 2986 Error = 8; // Template parameter (until C++17) 2987 break; 2988 case DeclaratorContext::BlockLiteralContext: 2989 Error = 9; // Block literal 2990 break; 2991 case DeclaratorContext::TemplateArgContext: 2992 // Within a template argument list, a deduced template specialization 2993 // type will be reinterpreted as a template template argument. 2994 if (isa<DeducedTemplateSpecializationType>(Deduced) && 2995 !D.getNumTypeObjects() && 2996 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier) 2997 break; 2998 LLVM_FALLTHROUGH; 2999 case DeclaratorContext::TemplateTypeArgContext: 3000 Error = 10; // Template type argument 3001 break; 3002 case DeclaratorContext::AliasDeclContext: 3003 case DeclaratorContext::AliasTemplateContext: 3004 Error = 12; // Type alias 3005 break; 3006 case DeclaratorContext::TrailingReturnContext: 3007 case DeclaratorContext::TrailingReturnVarContext: 3008 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) 3009 Error = 13; // Function return type 3010 IsDeducedReturnType = true; 3011 break; 3012 case DeclaratorContext::ConversionIdContext: 3013 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) 3014 Error = 14; // conversion-type-id 3015 IsDeducedReturnType = true; 3016 break; 3017 case DeclaratorContext::FunctionalCastContext: 3018 if (isa<DeducedTemplateSpecializationType>(Deduced)) 3019 break; 3020 LLVM_FALLTHROUGH; 3021 case DeclaratorContext::TypeNameContext: 3022 Error = 15; // Generic 3023 break; 3024 case DeclaratorContext::FileContext: 3025 case DeclaratorContext::BlockContext: 3026 case DeclaratorContext::ForContext: 3027 case DeclaratorContext::InitStmtContext: 3028 case DeclaratorContext::ConditionContext: 3029 // FIXME: P0091R3 (erroneously) does not permit class template argument 3030 // deduction in conditions, for-init-statements, and other declarations 3031 // that are not simple-declarations. 3032 break; 3033 case DeclaratorContext::CXXNewContext: 3034 // FIXME: P0091R3 does not permit class template argument deduction here, 3035 // but we follow GCC and allow it anyway. 3036 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced)) 3037 Error = 17; // 'new' type 3038 break; 3039 case DeclaratorContext::KNRTypeListContext: 3040 Error = 18; // K&R function parameter 3041 break; 3042 } 3043 3044 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3045 Error = 11; 3046 3047 // In Objective-C it is an error to use 'auto' on a function declarator 3048 // (and everywhere for '__auto_type'). 3049 if (D.isFunctionDeclarator() && 3050 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType)) 3051 Error = 13; 3052 3053 bool HaveTrailing = false; 3054 3055 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator 3056 // contains a trailing return type. That is only legal at the outermost 3057 // level. Check all declarator chunks (outermost first) anyway, to give 3058 // better diagnostics. 3059 // We don't support '__auto_type' with trailing return types. 3060 // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'? 3061 if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType && 3062 D.hasTrailingReturnType()) { 3063 HaveTrailing = true; 3064 Error = -1; 3065 } 3066 3067 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); 3068 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) 3069 AutoRange = D.getName().getSourceRange(); 3070 3071 if (Error != -1) { 3072 unsigned Kind; 3073 if (Auto) { 3074 switch (Auto->getKeyword()) { 3075 case AutoTypeKeyword::Auto: Kind = 0; break; 3076 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break; 3077 case AutoTypeKeyword::GNUAutoType: Kind = 2; break; 3078 } 3079 } else { 3080 assert(isa<DeducedTemplateSpecializationType>(Deduced) && 3081 "unknown auto type"); 3082 Kind = 3; 3083 } 3084 3085 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced); 3086 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName(); 3087 3088 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) 3089 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN) 3090 << QualType(Deduced, 0) << AutoRange; 3091 if (auto *TD = TN.getAsTemplateDecl()) 3092 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here); 3093 3094 T = SemaRef.Context.IntTy; 3095 D.setInvalidType(true); 3096 } else if (!HaveTrailing && 3097 D.getContext() != DeclaratorContext::LambdaExprContext) { 3098 // If there was a trailing return type, we already got 3099 // warn_cxx98_compat_trailing_return_type in the parser. 3100 SemaRef.Diag(AutoRange.getBegin(), 3101 D.getContext() == 3102 DeclaratorContext::LambdaExprParameterContext 3103 ? diag::warn_cxx11_compat_generic_lambda 3104 : IsDeducedReturnType 3105 ? diag::warn_cxx11_compat_deduced_return_type 3106 : diag::warn_cxx98_compat_auto_type_specifier) 3107 << AutoRange; 3108 } 3109 } 3110 3111 if (SemaRef.getLangOpts().CPlusPlus && 3112 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 3113 // Check the contexts where C++ forbids the declaration of a new class 3114 // or enumeration in a type-specifier-seq. 3115 unsigned DiagID = 0; 3116 switch (D.getContext()) { 3117 case DeclaratorContext::TrailingReturnContext: 3118 case DeclaratorContext::TrailingReturnVarContext: 3119 // Class and enumeration definitions are syntactically not allowed in 3120 // trailing return types. 3121 llvm_unreachable("parser should not have allowed this"); 3122 break; 3123 case DeclaratorContext::FileContext: 3124 case DeclaratorContext::MemberContext: 3125 case DeclaratorContext::BlockContext: 3126 case DeclaratorContext::ForContext: 3127 case DeclaratorContext::InitStmtContext: 3128 case DeclaratorContext::BlockLiteralContext: 3129 case DeclaratorContext::LambdaExprContext: 3130 // C++11 [dcl.type]p3: 3131 // A type-specifier-seq shall not define a class or enumeration unless 3132 // it appears in the type-id of an alias-declaration (7.1.3) that is not 3133 // the declaration of a template-declaration. 3134 case DeclaratorContext::AliasDeclContext: 3135 break; 3136 case DeclaratorContext::AliasTemplateContext: 3137 DiagID = diag::err_type_defined_in_alias_template; 3138 break; 3139 case DeclaratorContext::TypeNameContext: 3140 case DeclaratorContext::FunctionalCastContext: 3141 case DeclaratorContext::ConversionIdContext: 3142 case DeclaratorContext::TemplateParamContext: 3143 case DeclaratorContext::CXXNewContext: 3144 case DeclaratorContext::CXXCatchContext: 3145 case DeclaratorContext::ObjCCatchContext: 3146 case DeclaratorContext::TemplateArgContext: 3147 case DeclaratorContext::TemplateTypeArgContext: 3148 DiagID = diag::err_type_defined_in_type_specifier; 3149 break; 3150 case DeclaratorContext::PrototypeContext: 3151 case DeclaratorContext::LambdaExprParameterContext: 3152 case DeclaratorContext::ObjCParameterContext: 3153 case DeclaratorContext::ObjCResultContext: 3154 case DeclaratorContext::KNRTypeListContext: 3155 // C++ [dcl.fct]p6: 3156 // Types shall not be defined in return or parameter types. 3157 DiagID = diag::err_type_defined_in_param_type; 3158 break; 3159 case DeclaratorContext::ConditionContext: 3160 // C++ 6.4p2: 3161 // The type-specifier-seq shall not contain typedef and shall not declare 3162 // a new class or enumeration. 3163 DiagID = diag::err_type_defined_in_condition; 3164 break; 3165 } 3166 3167 if (DiagID != 0) { 3168 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) 3169 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 3170 D.setInvalidType(true); 3171 } 3172 } 3173 3174 assert(!T.isNull() && "This function should not return a null type"); 3175 return T; 3176 } 3177 3178 /// Produce an appropriate diagnostic for an ambiguity between a function 3179 /// declarator and a C++ direct-initializer. 3180 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, 3181 DeclaratorChunk &DeclType, QualType RT) { 3182 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 3183 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity"); 3184 3185 // If the return type is void there is no ambiguity. 3186 if (RT->isVoidType()) 3187 return; 3188 3189 // An initializer for a non-class type can have at most one argument. 3190 if (!RT->isRecordType() && FTI.NumParams > 1) 3191 return; 3192 3193 // An initializer for a reference must have exactly one argument. 3194 if (RT->isReferenceType() && FTI.NumParams != 1) 3195 return; 3196 3197 // Only warn if this declarator is declaring a function at block scope, and 3198 // doesn't have a storage class (such as 'extern') specified. 3199 if (!D.isFunctionDeclarator() || 3200 D.getFunctionDefinitionKind() != FDK_Declaration || 3201 !S.CurContext->isFunctionOrMethod() || 3202 D.getDeclSpec().getStorageClassSpec() 3203 != DeclSpec::SCS_unspecified) 3204 return; 3205 3206 // Inside a condition, a direct initializer is not permitted. We allow one to 3207 // be parsed in order to give better diagnostics in condition parsing. 3208 if (D.getContext() == DeclaratorContext::ConditionContext) 3209 return; 3210 3211 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); 3212 3213 S.Diag(DeclType.Loc, 3214 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration 3215 : diag::warn_empty_parens_are_function_decl) 3216 << ParenRange; 3217 3218 // If the declaration looks like: 3219 // T var1, 3220 // f(); 3221 // and name lookup finds a function named 'f', then the ',' was 3222 // probably intended to be a ';'. 3223 if (!D.isFirstDeclarator() && D.getIdentifier()) { 3224 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); 3225 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); 3226 if (Comma.getFileID() != Name.getFileID() || 3227 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { 3228 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 3229 Sema::LookupOrdinaryName); 3230 if (S.LookupName(Result, S.getCurScope())) 3231 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) 3232 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") 3233 << D.getIdentifier(); 3234 Result.suppressDiagnostics(); 3235 } 3236 } 3237 3238 if (FTI.NumParams > 0) { 3239 // For a declaration with parameters, eg. "T var(T());", suggest adding 3240 // parens around the first parameter to turn the declaration into a 3241 // variable declaration. 3242 SourceRange Range = FTI.Params[0].Param->getSourceRange(); 3243 SourceLocation B = Range.getBegin(); 3244 SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); 3245 // FIXME: Maybe we should suggest adding braces instead of parens 3246 // in C++11 for classes that don't have an initializer_list constructor. 3247 S.Diag(B, diag::note_additional_parens_for_variable_declaration) 3248 << FixItHint::CreateInsertion(B, "(") 3249 << FixItHint::CreateInsertion(E, ")"); 3250 } else { 3251 // For a declaration without parameters, eg. "T var();", suggest replacing 3252 // the parens with an initializer to turn the declaration into a variable 3253 // declaration. 3254 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 3255 3256 // Empty parens mean value-initialization, and no parens mean 3257 // default initialization. These are equivalent if the default 3258 // constructor is user-provided or if zero-initialization is a 3259 // no-op. 3260 if (RD && RD->hasDefinition() && 3261 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) 3262 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) 3263 << FixItHint::CreateRemoval(ParenRange); 3264 else { 3265 std::string Init = 3266 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); 3267 if (Init.empty() && S.LangOpts.CPlusPlus11) 3268 Init = "{}"; 3269 if (!Init.empty()) 3270 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) 3271 << FixItHint::CreateReplacement(ParenRange, Init); 3272 } 3273 } 3274 } 3275 3276 /// Produce an appropriate diagnostic for a declarator with top-level 3277 /// parentheses. 3278 static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) { 3279 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1); 3280 assert(Paren.Kind == DeclaratorChunk::Paren && 3281 "do not have redundant top-level parentheses"); 3282 3283 // This is a syntactic check; we're not interested in cases that arise 3284 // during template instantiation. 3285 if (S.inTemplateInstantiation()) 3286 return; 3287 3288 // Check whether this could be intended to be a construction of a temporary 3289 // object in C++ via a function-style cast. 3290 bool CouldBeTemporaryObject = 3291 S.getLangOpts().CPlusPlus && D.isExpressionContext() && 3292 !D.isInvalidType() && D.getIdentifier() && 3293 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && 3294 (T->isRecordType() || T->isDependentType()) && 3295 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator(); 3296 3297 bool StartsWithDeclaratorId = true; 3298 for (auto &C : D.type_objects()) { 3299 switch (C.Kind) { 3300 case DeclaratorChunk::Paren: 3301 if (&C == &Paren) 3302 continue; 3303 LLVM_FALLTHROUGH; 3304 case DeclaratorChunk::Pointer: 3305 StartsWithDeclaratorId = false; 3306 continue; 3307 3308 case DeclaratorChunk::Array: 3309 if (!C.Arr.NumElts) 3310 CouldBeTemporaryObject = false; 3311 continue; 3312 3313 case DeclaratorChunk::Reference: 3314 // FIXME: Suppress the warning here if there is no initializer; we're 3315 // going to give an error anyway. 3316 // We assume that something like 'T (&x) = y;' is highly likely to not 3317 // be intended to be a temporary object. 3318 CouldBeTemporaryObject = false; 3319 StartsWithDeclaratorId = false; 3320 continue; 3321 3322 case DeclaratorChunk::Function: 3323 // In a new-type-id, function chunks require parentheses. 3324 if (D.getContext() == DeclaratorContext::CXXNewContext) 3325 return; 3326 // FIXME: "A(f())" deserves a vexing-parse warning, not just a 3327 // redundant-parens warning, but we don't know whether the function 3328 // chunk was syntactically valid as an expression here. 3329 CouldBeTemporaryObject = false; 3330 continue; 3331 3332 case DeclaratorChunk::BlockPointer: 3333 case DeclaratorChunk::MemberPointer: 3334 case DeclaratorChunk::Pipe: 3335 // These cannot appear in expressions. 3336 CouldBeTemporaryObject = false; 3337 StartsWithDeclaratorId = false; 3338 continue; 3339 } 3340 } 3341 3342 // FIXME: If there is an initializer, assume that this is not intended to be 3343 // a construction of a temporary object. 3344 3345 // Check whether the name has already been declared; if not, this is not a 3346 // function-style cast. 3347 if (CouldBeTemporaryObject) { 3348 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 3349 Sema::LookupOrdinaryName); 3350 if (!S.LookupName(Result, S.getCurScope())) 3351 CouldBeTemporaryObject = false; 3352 Result.suppressDiagnostics(); 3353 } 3354 3355 SourceRange ParenRange(Paren.Loc, Paren.EndLoc); 3356 3357 if (!CouldBeTemporaryObject) { 3358 // If we have A (::B), the parentheses affect the meaning of the program. 3359 // Suppress the warning in that case. Don't bother looking at the DeclSpec 3360 // here: even (e.g.) "int ::x" is visually ambiguous even though it's 3361 // formally unambiguous. 3362 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) { 3363 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS; 3364 NNS = NNS->getPrefix()) { 3365 if (NNS->getKind() == NestedNameSpecifier::Global) 3366 return; 3367 } 3368 } 3369 3370 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator) 3371 << ParenRange << FixItHint::CreateRemoval(Paren.Loc) 3372 << FixItHint::CreateRemoval(Paren.EndLoc); 3373 return; 3374 } 3375 3376 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration) 3377 << ParenRange << D.getIdentifier(); 3378 auto *RD = T->getAsCXXRecordDecl(); 3379 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor()) 3380 S.Diag(Paren.Loc, diag::note_raii_guard_add_name) 3381 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T 3382 << D.getIdentifier(); 3383 // FIXME: A cast to void is probably a better suggestion in cases where it's 3384 // valid (when there is no initializer and we're not in a condition). 3385 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses) 3386 << FixItHint::CreateInsertion(D.getBeginLoc(), "(") 3387 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")"); 3388 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration) 3389 << FixItHint::CreateRemoval(Paren.Loc) 3390 << FixItHint::CreateRemoval(Paren.EndLoc); 3391 } 3392 3393 /// Helper for figuring out the default CC for a function declarator type. If 3394 /// this is the outermost chunk, then we can determine the CC from the 3395 /// declarator context. If not, then this could be either a member function 3396 /// type or normal function type. 3397 static CallingConv getCCForDeclaratorChunk( 3398 Sema &S, Declarator &D, const ParsedAttributesView &AttrList, 3399 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) { 3400 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function); 3401 3402 // Check for an explicit CC attribute. 3403 for (const ParsedAttr &AL : AttrList) { 3404 switch (AL.getKind()) { 3405 CALLING_CONV_ATTRS_CASELIST : { 3406 // Ignore attributes that don't validate or can't apply to the 3407 // function type. We'll diagnose the failure to apply them in 3408 // handleFunctionTypeAttr. 3409 CallingConv CC; 3410 if (!S.CheckCallingConvAttr(AL, CC) && 3411 (!FTI.isVariadic || supportsVariadicCall(CC))) { 3412 return CC; 3413 } 3414 break; 3415 } 3416 3417 default: 3418 break; 3419 } 3420 } 3421 3422 bool IsCXXInstanceMethod = false; 3423 3424 if (S.getLangOpts().CPlusPlus) { 3425 // Look inwards through parentheses to see if this chunk will form a 3426 // member pointer type or if we're the declarator. Any type attributes 3427 // between here and there will override the CC we choose here. 3428 unsigned I = ChunkIndex; 3429 bool FoundNonParen = false; 3430 while (I && !FoundNonParen) { 3431 --I; 3432 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) 3433 FoundNonParen = true; 3434 } 3435 3436 if (FoundNonParen) { 3437 // If we're not the declarator, we're a regular function type unless we're 3438 // in a member pointer. 3439 IsCXXInstanceMethod = 3440 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; 3441 } else if (D.getContext() == DeclaratorContext::LambdaExprContext) { 3442 // This can only be a call operator for a lambda, which is an instance 3443 // method. 3444 IsCXXInstanceMethod = true; 3445 } else { 3446 // We're the innermost decl chunk, so must be a function declarator. 3447 assert(D.isFunctionDeclarator()); 3448 3449 // If we're inside a record, we're declaring a method, but it could be 3450 // explicitly or implicitly static. 3451 IsCXXInstanceMethod = 3452 D.isFirstDeclarationOfMember() && 3453 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 3454 !D.isStaticMember(); 3455 } 3456 } 3457 3458 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic, 3459 IsCXXInstanceMethod); 3460 3461 // Attribute AT_OpenCLKernel affects the calling convention for SPIR 3462 // and AMDGPU targets, hence it cannot be treated as a calling 3463 // convention attribute. This is the simplest place to infer 3464 // calling convention for OpenCL kernels. 3465 if (S.getLangOpts().OpenCL) { 3466 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { 3467 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) { 3468 CC = CC_OpenCLKernel; 3469 break; 3470 } 3471 } 3472 } 3473 3474 return CC; 3475 } 3476 3477 namespace { 3478 /// A simple notion of pointer kinds, which matches up with the various 3479 /// pointer declarators. 3480 enum class SimplePointerKind { 3481 Pointer, 3482 BlockPointer, 3483 MemberPointer, 3484 Array, 3485 }; 3486 } // end anonymous namespace 3487 3488 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { 3489 switch (nullability) { 3490 case NullabilityKind::NonNull: 3491 if (!Ident__Nonnull) 3492 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); 3493 return Ident__Nonnull; 3494 3495 case NullabilityKind::Nullable: 3496 if (!Ident__Nullable) 3497 Ident__Nullable = PP.getIdentifierInfo("_Nullable"); 3498 return Ident__Nullable; 3499 3500 case NullabilityKind::Unspecified: 3501 if (!Ident__Null_unspecified) 3502 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); 3503 return Ident__Null_unspecified; 3504 } 3505 llvm_unreachable("Unknown nullability kind."); 3506 } 3507 3508 /// Retrieve the identifier "NSError". 3509 IdentifierInfo *Sema::getNSErrorIdent() { 3510 if (!Ident_NSError) 3511 Ident_NSError = PP.getIdentifierInfo("NSError"); 3512 3513 return Ident_NSError; 3514 } 3515 3516 /// Check whether there is a nullability attribute of any kind in the given 3517 /// attribute list. 3518 static bool hasNullabilityAttr(const ParsedAttributesView &attrs) { 3519 for (const ParsedAttr &AL : attrs) { 3520 if (AL.getKind() == ParsedAttr::AT_TypeNonNull || 3521 AL.getKind() == ParsedAttr::AT_TypeNullable || 3522 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified) 3523 return true; 3524 } 3525 3526 return false; 3527 } 3528 3529 namespace { 3530 /// Describes the kind of a pointer a declarator describes. 3531 enum class PointerDeclaratorKind { 3532 // Not a pointer. 3533 NonPointer, 3534 // Single-level pointer. 3535 SingleLevelPointer, 3536 // Multi-level pointer (of any pointer kind). 3537 MultiLevelPointer, 3538 // CFFooRef* 3539 MaybePointerToCFRef, 3540 // CFErrorRef* 3541 CFErrorRefPointer, 3542 // NSError** 3543 NSErrorPointerPointer, 3544 }; 3545 3546 /// Describes a declarator chunk wrapping a pointer that marks inference as 3547 /// unexpected. 3548 // These values must be kept in sync with diagnostics. 3549 enum class PointerWrappingDeclaratorKind { 3550 /// Pointer is top-level. 3551 None = -1, 3552 /// Pointer is an array element. 3553 Array = 0, 3554 /// Pointer is the referent type of a C++ reference. 3555 Reference = 1 3556 }; 3557 } // end anonymous namespace 3558 3559 /// Classify the given declarator, whose type-specified is \c type, based on 3560 /// what kind of pointer it refers to. 3561 /// 3562 /// This is used to determine the default nullability. 3563 static PointerDeclaratorKind 3564 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, 3565 PointerWrappingDeclaratorKind &wrappingKind) { 3566 unsigned numNormalPointers = 0; 3567 3568 // For any dependent type, we consider it a non-pointer. 3569 if (type->isDependentType()) 3570 return PointerDeclaratorKind::NonPointer; 3571 3572 // Look through the declarator chunks to identify pointers. 3573 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { 3574 DeclaratorChunk &chunk = declarator.getTypeObject(i); 3575 switch (chunk.Kind) { 3576 case DeclaratorChunk::Array: 3577 if (numNormalPointers == 0) 3578 wrappingKind = PointerWrappingDeclaratorKind::Array; 3579 break; 3580 3581 case DeclaratorChunk::Function: 3582 case DeclaratorChunk::Pipe: 3583 break; 3584 3585 case DeclaratorChunk::BlockPointer: 3586 case DeclaratorChunk::MemberPointer: 3587 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3588 : PointerDeclaratorKind::SingleLevelPointer; 3589 3590 case DeclaratorChunk::Paren: 3591 break; 3592 3593 case DeclaratorChunk::Reference: 3594 if (numNormalPointers == 0) 3595 wrappingKind = PointerWrappingDeclaratorKind::Reference; 3596 break; 3597 3598 case DeclaratorChunk::Pointer: 3599 ++numNormalPointers; 3600 if (numNormalPointers > 2) 3601 return PointerDeclaratorKind::MultiLevelPointer; 3602 break; 3603 } 3604 } 3605 3606 // Then, dig into the type specifier itself. 3607 unsigned numTypeSpecifierPointers = 0; 3608 do { 3609 // Decompose normal pointers. 3610 if (auto ptrType = type->getAs<PointerType>()) { 3611 ++numNormalPointers; 3612 3613 if (numNormalPointers > 2) 3614 return PointerDeclaratorKind::MultiLevelPointer; 3615 3616 type = ptrType->getPointeeType(); 3617 ++numTypeSpecifierPointers; 3618 continue; 3619 } 3620 3621 // Decompose block pointers. 3622 if (type->getAs<BlockPointerType>()) { 3623 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3624 : PointerDeclaratorKind::SingleLevelPointer; 3625 } 3626 3627 // Decompose member pointers. 3628 if (type->getAs<MemberPointerType>()) { 3629 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3630 : PointerDeclaratorKind::SingleLevelPointer; 3631 } 3632 3633 // Look at Objective-C object pointers. 3634 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { 3635 ++numNormalPointers; 3636 ++numTypeSpecifierPointers; 3637 3638 // If this is NSError**, report that. 3639 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { 3640 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && 3641 numNormalPointers == 2 && numTypeSpecifierPointers < 2) { 3642 return PointerDeclaratorKind::NSErrorPointerPointer; 3643 } 3644 } 3645 3646 break; 3647 } 3648 3649 // Look at Objective-C class types. 3650 if (auto objcClass = type->getAs<ObjCInterfaceType>()) { 3651 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { 3652 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) 3653 return PointerDeclaratorKind::NSErrorPointerPointer; 3654 } 3655 3656 break; 3657 } 3658 3659 // If at this point we haven't seen a pointer, we won't see one. 3660 if (numNormalPointers == 0) 3661 return PointerDeclaratorKind::NonPointer; 3662 3663 if (auto recordType = type->getAs<RecordType>()) { 3664 RecordDecl *recordDecl = recordType->getDecl(); 3665 3666 bool isCFError = false; 3667 if (S.CFError) { 3668 // If we already know about CFError, test it directly. 3669 isCFError = (S.CFError == recordDecl); 3670 } else { 3671 // Check whether this is CFError, which we identify based on its bridge 3672 // to NSError. CFErrorRef used to be declared with "objc_bridge" but is 3673 // now declared with "objc_bridge_mutable", so look for either one of 3674 // the two attributes. 3675 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) { 3676 IdentifierInfo *bridgedType = nullptr; 3677 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) 3678 bridgedType = bridgeAttr->getBridgedType(); 3679 else if (auto bridgeAttr = 3680 recordDecl->getAttr<ObjCBridgeMutableAttr>()) 3681 bridgedType = bridgeAttr->getBridgedType(); 3682 3683 if (bridgedType == S.getNSErrorIdent()) { 3684 S.CFError = recordDecl; 3685 isCFError = true; 3686 } 3687 } 3688 } 3689 3690 // If this is CFErrorRef*, report it as such. 3691 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) { 3692 return PointerDeclaratorKind::CFErrorRefPointer; 3693 } 3694 break; 3695 } 3696 3697 break; 3698 } while (true); 3699 3700 switch (numNormalPointers) { 3701 case 0: 3702 return PointerDeclaratorKind::NonPointer; 3703 3704 case 1: 3705 return PointerDeclaratorKind::SingleLevelPointer; 3706 3707 case 2: 3708 return PointerDeclaratorKind::MaybePointerToCFRef; 3709 3710 default: 3711 return PointerDeclaratorKind::MultiLevelPointer; 3712 } 3713 } 3714 3715 static FileID getNullabilityCompletenessCheckFileID(Sema &S, 3716 SourceLocation loc) { 3717 // If we're anywhere in a function, method, or closure context, don't perform 3718 // completeness checks. 3719 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { 3720 if (ctx->isFunctionOrMethod()) 3721 return FileID(); 3722 3723 if (ctx->isFileContext()) 3724 break; 3725 } 3726 3727 // We only care about the expansion location. 3728 loc = S.SourceMgr.getExpansionLoc(loc); 3729 FileID file = S.SourceMgr.getFileID(loc); 3730 if (file.isInvalid()) 3731 return FileID(); 3732 3733 // Retrieve file information. 3734 bool invalid = false; 3735 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); 3736 if (invalid || !sloc.isFile()) 3737 return FileID(); 3738 3739 // We don't want to perform completeness checks on the main file or in 3740 // system headers. 3741 const SrcMgr::FileInfo &fileInfo = sloc.getFile(); 3742 if (fileInfo.getIncludeLoc().isInvalid()) 3743 return FileID(); 3744 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && 3745 S.Diags.getSuppressSystemWarnings()) { 3746 return FileID(); 3747 } 3748 3749 return file; 3750 } 3751 3752 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc, 3753 /// taking into account whitespace before and after. 3754 static void fixItNullability(Sema &S, DiagnosticBuilder &Diag, 3755 SourceLocation PointerLoc, 3756 NullabilityKind Nullability) { 3757 assert(PointerLoc.isValid()); 3758 if (PointerLoc.isMacroID()) 3759 return; 3760 3761 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc); 3762 if (!FixItLoc.isValid() || FixItLoc == PointerLoc) 3763 return; 3764 3765 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc); 3766 if (!NextChar) 3767 return; 3768 3769 SmallString<32> InsertionTextBuf{" "}; 3770 InsertionTextBuf += getNullabilitySpelling(Nullability); 3771 InsertionTextBuf += " "; 3772 StringRef InsertionText = InsertionTextBuf.str(); 3773 3774 if (isWhitespace(*NextChar)) { 3775 InsertionText = InsertionText.drop_back(); 3776 } else if (NextChar[-1] == '[') { 3777 if (NextChar[0] == ']') 3778 InsertionText = InsertionText.drop_back().drop_front(); 3779 else 3780 InsertionText = InsertionText.drop_front(); 3781 } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) && 3782 !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) { 3783 InsertionText = InsertionText.drop_back().drop_front(); 3784 } 3785 3786 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText); 3787 } 3788 3789 static void emitNullabilityConsistencyWarning(Sema &S, 3790 SimplePointerKind PointerKind, 3791 SourceLocation PointerLoc, 3792 SourceLocation PointerEndLoc) { 3793 assert(PointerLoc.isValid()); 3794 3795 if (PointerKind == SimplePointerKind::Array) { 3796 S.Diag(PointerLoc, diag::warn_nullability_missing_array); 3797 } else { 3798 S.Diag(PointerLoc, diag::warn_nullability_missing) 3799 << static_cast<unsigned>(PointerKind); 3800 } 3801 3802 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc; 3803 if (FixItLoc.isMacroID()) 3804 return; 3805 3806 auto addFixIt = [&](NullabilityKind Nullability) { 3807 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it); 3808 Diag << static_cast<unsigned>(Nullability); 3809 Diag << static_cast<unsigned>(PointerKind); 3810 fixItNullability(S, Diag, FixItLoc, Nullability); 3811 }; 3812 addFixIt(NullabilityKind::Nullable); 3813 addFixIt(NullabilityKind::NonNull); 3814 } 3815 3816 /// Complains about missing nullability if the file containing \p pointerLoc 3817 /// has other uses of nullability (either the keywords or the \c assume_nonnull 3818 /// pragma). 3819 /// 3820 /// If the file has \e not seen other uses of nullability, this particular 3821 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen(). 3822 static void 3823 checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, 3824 SourceLocation pointerLoc, 3825 SourceLocation pointerEndLoc = SourceLocation()) { 3826 // Determine which file we're performing consistency checking for. 3827 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); 3828 if (file.isInvalid()) 3829 return; 3830 3831 // If we haven't seen any type nullability in this file, we won't warn now 3832 // about anything. 3833 FileNullability &fileNullability = S.NullabilityMap[file]; 3834 if (!fileNullability.SawTypeNullability) { 3835 // If this is the first pointer declarator in the file, and the appropriate 3836 // warning is on, record it in case we need to diagnose it retroactively. 3837 diag::kind diagKind; 3838 if (pointerKind == SimplePointerKind::Array) 3839 diagKind = diag::warn_nullability_missing_array; 3840 else 3841 diagKind = diag::warn_nullability_missing; 3842 3843 if (fileNullability.PointerLoc.isInvalid() && 3844 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) { 3845 fileNullability.PointerLoc = pointerLoc; 3846 fileNullability.PointerEndLoc = pointerEndLoc; 3847 fileNullability.PointerKind = static_cast<unsigned>(pointerKind); 3848 } 3849 3850 return; 3851 } 3852 3853 // Complain about missing nullability. 3854 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc); 3855 } 3856 3857 /// Marks that a nullability feature has been used in the file containing 3858 /// \p loc. 3859 /// 3860 /// If this file already had pointer types in it that were missing nullability, 3861 /// the first such instance is retroactively diagnosed. 3862 /// 3863 /// \sa checkNullabilityConsistency 3864 static void recordNullabilitySeen(Sema &S, SourceLocation loc) { 3865 FileID file = getNullabilityCompletenessCheckFileID(S, loc); 3866 if (file.isInvalid()) 3867 return; 3868 3869 FileNullability &fileNullability = S.NullabilityMap[file]; 3870 if (fileNullability.SawTypeNullability) 3871 return; 3872 fileNullability.SawTypeNullability = true; 3873 3874 // If we haven't seen any type nullability before, now we have. Retroactively 3875 // diagnose the first unannotated pointer, if there was one. 3876 if (fileNullability.PointerLoc.isInvalid()) 3877 return; 3878 3879 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind); 3880 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc, 3881 fileNullability.PointerEndLoc); 3882 } 3883 3884 /// Returns true if any of the declarator chunks before \p endIndex include a 3885 /// level of indirection: array, pointer, reference, or pointer-to-member. 3886 /// 3887 /// Because declarator chunks are stored in outer-to-inner order, testing 3888 /// every chunk before \p endIndex is testing all chunks that embed the current 3889 /// chunk as part of their type. 3890 /// 3891 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the 3892 /// end index, in which case all chunks are tested. 3893 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) { 3894 unsigned i = endIndex; 3895 while (i != 0) { 3896 // Walk outwards along the declarator chunks. 3897 --i; 3898 const DeclaratorChunk &DC = D.getTypeObject(i); 3899 switch (DC.Kind) { 3900 case DeclaratorChunk::Paren: 3901 break; 3902 case DeclaratorChunk::Array: 3903 case DeclaratorChunk::Pointer: 3904 case DeclaratorChunk::Reference: 3905 case DeclaratorChunk::MemberPointer: 3906 return true; 3907 case DeclaratorChunk::Function: 3908 case DeclaratorChunk::BlockPointer: 3909 case DeclaratorChunk::Pipe: 3910 // These are invalid anyway, so just ignore. 3911 break; 3912 } 3913 } 3914 return false; 3915 } 3916 3917 static bool IsNoDerefableChunk(DeclaratorChunk Chunk) { 3918 return (Chunk.Kind == DeclaratorChunk::Pointer || 3919 Chunk.Kind == DeclaratorChunk::Array); 3920 } 3921 3922 template<typename AttrT> 3923 static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &Attr) { 3924 Attr.setUsedAsTypeAttr(); 3925 return ::new (Ctx) 3926 AttrT(Attr.getRange(), Ctx, Attr.getAttributeSpellingListIndex()); 3927 } 3928 3929 static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, 3930 NullabilityKind NK) { 3931 switch (NK) { 3932 case NullabilityKind::NonNull: 3933 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr); 3934 3935 case NullabilityKind::Nullable: 3936 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr); 3937 3938 case NullabilityKind::Unspecified: 3939 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr); 3940 } 3941 llvm_unreachable("unknown NullabilityKind"); 3942 } 3943 3944 // Diagnose whether this is a case with the multiple addr spaces. 3945 // Returns true if this is an invalid case. 3946 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified 3947 // by qualifiers for two or more different address spaces." 3948 static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld, 3949 LangAS ASNew, 3950 SourceLocation AttrLoc) { 3951 if (ASOld != LangAS::Default) { 3952 if (ASOld != ASNew) { 3953 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); 3954 return true; 3955 } 3956 // Emit a warning if they are identical; it's likely unintended. 3957 S.Diag(AttrLoc, 3958 diag::warn_attribute_address_multiple_identical_qualifiers); 3959 } 3960 return false; 3961 } 3962 3963 static TypeSourceInfo * 3964 GetTypeSourceInfoForDeclarator(TypeProcessingState &State, 3965 QualType T, TypeSourceInfo *ReturnTypeInfo); 3966 3967 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 3968 QualType declSpecType, 3969 TypeSourceInfo *TInfo) { 3970 // The TypeSourceInfo that this function returns will not be a null type. 3971 // If there is an error, this function will fill in a dummy type as fallback. 3972 QualType T = declSpecType; 3973 Declarator &D = state.getDeclarator(); 3974 Sema &S = state.getSema(); 3975 ASTContext &Context = S.Context; 3976 const LangOptions &LangOpts = S.getLangOpts(); 3977 3978 // The name we're declaring, if any. 3979 DeclarationName Name; 3980 if (D.getIdentifier()) 3981 Name = D.getIdentifier(); 3982 3983 // Does this declaration declare a typedef-name? 3984 bool IsTypedefName = 3985 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 3986 D.getContext() == DeclaratorContext::AliasDeclContext || 3987 D.getContext() == DeclaratorContext::AliasTemplateContext; 3988 3989 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 3990 bool IsQualifiedFunction = T->isFunctionProtoType() && 3991 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() || 3992 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 3993 3994 // If T is 'decltype(auto)', the only declarators we can have are parens 3995 // and at most one function declarator if this is a function declaration. 3996 // If T is a deduced class template specialization type, we can have no 3997 // declarator chunks at all. 3998 if (auto *DT = T->getAs<DeducedType>()) { 3999 const AutoType *AT = T->getAs<AutoType>(); 4000 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT); 4001 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) { 4002 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4003 unsigned Index = E - I - 1; 4004 DeclaratorChunk &DeclChunk = D.getTypeObject(Index); 4005 unsigned DiagId = IsClassTemplateDeduction 4006 ? diag::err_deduced_class_template_compound_type 4007 : diag::err_decltype_auto_compound_type; 4008 unsigned DiagKind = 0; 4009 switch (DeclChunk.Kind) { 4010 case DeclaratorChunk::Paren: 4011 // FIXME: Rejecting this is a little silly. 4012 if (IsClassTemplateDeduction) { 4013 DiagKind = 4; 4014 break; 4015 } 4016 continue; 4017 case DeclaratorChunk::Function: { 4018 if (IsClassTemplateDeduction) { 4019 DiagKind = 3; 4020 break; 4021 } 4022 unsigned FnIndex; 4023 if (D.isFunctionDeclarationContext() && 4024 D.isFunctionDeclarator(FnIndex) && FnIndex == Index) 4025 continue; 4026 DiagId = diag::err_decltype_auto_function_declarator_not_declaration; 4027 break; 4028 } 4029 case DeclaratorChunk::Pointer: 4030 case DeclaratorChunk::BlockPointer: 4031 case DeclaratorChunk::MemberPointer: 4032 DiagKind = 0; 4033 break; 4034 case DeclaratorChunk::Reference: 4035 DiagKind = 1; 4036 break; 4037 case DeclaratorChunk::Array: 4038 DiagKind = 2; 4039 break; 4040 case DeclaratorChunk::Pipe: 4041 break; 4042 } 4043 4044 S.Diag(DeclChunk.Loc, DiagId) << DiagKind; 4045 D.setInvalidType(true); 4046 break; 4047 } 4048 } 4049 } 4050 4051 // Determine whether we should infer _Nonnull on pointer types. 4052 Optional<NullabilityKind> inferNullability; 4053 bool inferNullabilityCS = false; 4054 bool inferNullabilityInnerOnly = false; 4055 bool inferNullabilityInnerOnlyComplete = false; 4056 4057 // Are we in an assume-nonnull region? 4058 bool inAssumeNonNullRegion = false; 4059 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc(); 4060 if (assumeNonNullLoc.isValid()) { 4061 inAssumeNonNullRegion = true; 4062 recordNullabilitySeen(S, assumeNonNullLoc); 4063 } 4064 4065 // Whether to complain about missing nullability specifiers or not. 4066 enum { 4067 /// Never complain. 4068 CAMN_No, 4069 /// Complain on the inner pointers (but not the outermost 4070 /// pointer). 4071 CAMN_InnerPointers, 4072 /// Complain about any pointers that don't have nullability 4073 /// specified or inferred. 4074 CAMN_Yes 4075 } complainAboutMissingNullability = CAMN_No; 4076 unsigned NumPointersRemaining = 0; 4077 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None; 4078 4079 if (IsTypedefName) { 4080 // For typedefs, we do not infer any nullability (the default), 4081 // and we only complain about missing nullability specifiers on 4082 // inner pointers. 4083 complainAboutMissingNullability = CAMN_InnerPointers; 4084 4085 if (T->canHaveNullability(/*ResultIfUnknown*/false) && 4086 !T->getNullability(S.Context)) { 4087 // Note that we allow but don't require nullability on dependent types. 4088 ++NumPointersRemaining; 4089 } 4090 4091 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { 4092 DeclaratorChunk &chunk = D.getTypeObject(i); 4093 switch (chunk.Kind) { 4094 case DeclaratorChunk::Array: 4095 case DeclaratorChunk::Function: 4096 case DeclaratorChunk::Pipe: 4097 break; 4098 4099 case DeclaratorChunk::BlockPointer: 4100 case DeclaratorChunk::MemberPointer: 4101 ++NumPointersRemaining; 4102 break; 4103 4104 case DeclaratorChunk::Paren: 4105 case DeclaratorChunk::Reference: 4106 continue; 4107 4108 case DeclaratorChunk::Pointer: 4109 ++NumPointersRemaining; 4110 continue; 4111 } 4112 } 4113 } else { 4114 bool isFunctionOrMethod = false; 4115 switch (auto context = state.getDeclarator().getContext()) { 4116 case DeclaratorContext::ObjCParameterContext: 4117 case DeclaratorContext::ObjCResultContext: 4118 case DeclaratorContext::PrototypeContext: 4119 case DeclaratorContext::TrailingReturnContext: 4120 case DeclaratorContext::TrailingReturnVarContext: 4121 isFunctionOrMethod = true; 4122 LLVM_FALLTHROUGH; 4123 4124 case DeclaratorContext::MemberContext: 4125 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { 4126 complainAboutMissingNullability = CAMN_No; 4127 break; 4128 } 4129 4130 // Weak properties are inferred to be nullable. 4131 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) { 4132 inferNullability = NullabilityKind::Nullable; 4133 break; 4134 } 4135 4136 LLVM_FALLTHROUGH; 4137 4138 case DeclaratorContext::FileContext: 4139 case DeclaratorContext::KNRTypeListContext: { 4140 complainAboutMissingNullability = CAMN_Yes; 4141 4142 // Nullability inference depends on the type and declarator. 4143 auto wrappingKind = PointerWrappingDeclaratorKind::None; 4144 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) { 4145 case PointerDeclaratorKind::NonPointer: 4146 case PointerDeclaratorKind::MultiLevelPointer: 4147 // Cannot infer nullability. 4148 break; 4149 4150 case PointerDeclaratorKind::SingleLevelPointer: 4151 // Infer _Nonnull if we are in an assumes-nonnull region. 4152 if (inAssumeNonNullRegion) { 4153 complainAboutInferringWithinChunk = wrappingKind; 4154 inferNullability = NullabilityKind::NonNull; 4155 inferNullabilityCS = 4156 (context == DeclaratorContext::ObjCParameterContext || 4157 context == DeclaratorContext::ObjCResultContext); 4158 } 4159 break; 4160 4161 case PointerDeclaratorKind::CFErrorRefPointer: 4162 case PointerDeclaratorKind::NSErrorPointerPointer: 4163 // Within a function or method signature, infer _Nullable at both 4164 // levels. 4165 if (isFunctionOrMethod && inAssumeNonNullRegion) 4166 inferNullability = NullabilityKind::Nullable; 4167 break; 4168 4169 case PointerDeclaratorKind::MaybePointerToCFRef: 4170 if (isFunctionOrMethod) { 4171 // On pointer-to-pointer parameters marked cf_returns_retained or 4172 // cf_returns_not_retained, if the outer pointer is explicit then 4173 // infer the inner pointer as _Nullable. 4174 auto hasCFReturnsAttr = 4175 [](const ParsedAttributesView &AttrList) -> bool { 4176 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) || 4177 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained); 4178 }; 4179 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { 4180 if (hasCFReturnsAttr(D.getAttributes()) || 4181 hasCFReturnsAttr(InnermostChunk->getAttrs()) || 4182 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) { 4183 inferNullability = NullabilityKind::Nullable; 4184 inferNullabilityInnerOnly = true; 4185 } 4186 } 4187 } 4188 break; 4189 } 4190 break; 4191 } 4192 4193 case DeclaratorContext::ConversionIdContext: 4194 complainAboutMissingNullability = CAMN_Yes; 4195 break; 4196 4197 case DeclaratorContext::AliasDeclContext: 4198 case DeclaratorContext::AliasTemplateContext: 4199 case DeclaratorContext::BlockContext: 4200 case DeclaratorContext::BlockLiteralContext: 4201 case DeclaratorContext::ConditionContext: 4202 case DeclaratorContext::CXXCatchContext: 4203 case DeclaratorContext::CXXNewContext: 4204 case DeclaratorContext::ForContext: 4205 case DeclaratorContext::InitStmtContext: 4206 case DeclaratorContext::LambdaExprContext: 4207 case DeclaratorContext::LambdaExprParameterContext: 4208 case DeclaratorContext::ObjCCatchContext: 4209 case DeclaratorContext::TemplateParamContext: 4210 case DeclaratorContext::TemplateArgContext: 4211 case DeclaratorContext::TemplateTypeArgContext: 4212 case DeclaratorContext::TypeNameContext: 4213 case DeclaratorContext::FunctionalCastContext: 4214 // Don't infer in these contexts. 4215 break; 4216 } 4217 } 4218 4219 // Local function that returns true if its argument looks like a va_list. 4220 auto isVaList = [&S](QualType T) -> bool { 4221 auto *typedefTy = T->getAs<TypedefType>(); 4222 if (!typedefTy) 4223 return false; 4224 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl(); 4225 do { 4226 if (typedefTy->getDecl() == vaListTypedef) 4227 return true; 4228 if (auto *name = typedefTy->getDecl()->getIdentifier()) 4229 if (name->isStr("va_list")) 4230 return true; 4231 typedefTy = typedefTy->desugar()->getAs<TypedefType>(); 4232 } while (typedefTy); 4233 return false; 4234 }; 4235 4236 // Local function that checks the nullability for a given pointer declarator. 4237 // Returns true if _Nonnull was inferred. 4238 auto inferPointerNullability = 4239 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc, 4240 SourceLocation pointerEndLoc, 4241 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * { 4242 // We've seen a pointer. 4243 if (NumPointersRemaining > 0) 4244 --NumPointersRemaining; 4245 4246 // If a nullability attribute is present, there's nothing to do. 4247 if (hasNullabilityAttr(attrs)) 4248 return nullptr; 4249 4250 // If we're supposed to infer nullability, do so now. 4251 if (inferNullability && !inferNullabilityInnerOnlyComplete) { 4252 ParsedAttr::Syntax syntax = inferNullabilityCS 4253 ? ParsedAttr::AS_ContextSensitiveKeyword 4254 : ParsedAttr::AS_Keyword; 4255 ParsedAttr *nullabilityAttr = Pool.create( 4256 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc), 4257 nullptr, SourceLocation(), nullptr, 0, syntax); 4258 4259 attrs.addAtEnd(nullabilityAttr); 4260 4261 if (inferNullabilityCS) { 4262 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() 4263 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); 4264 } 4265 4266 if (pointerLoc.isValid() && 4267 complainAboutInferringWithinChunk != 4268 PointerWrappingDeclaratorKind::None) { 4269 auto Diag = 4270 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type); 4271 Diag << static_cast<int>(complainAboutInferringWithinChunk); 4272 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull); 4273 } 4274 4275 if (inferNullabilityInnerOnly) 4276 inferNullabilityInnerOnlyComplete = true; 4277 return nullabilityAttr; 4278 } 4279 4280 // If we're supposed to complain about missing nullability, do so 4281 // now if it's truly missing. 4282 switch (complainAboutMissingNullability) { 4283 case CAMN_No: 4284 break; 4285 4286 case CAMN_InnerPointers: 4287 if (NumPointersRemaining == 0) 4288 break; 4289 LLVM_FALLTHROUGH; 4290 4291 case CAMN_Yes: 4292 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc); 4293 } 4294 return nullptr; 4295 }; 4296 4297 // If the type itself could have nullability but does not, infer pointer 4298 // nullability and perform consistency checking. 4299 if (S.CodeSynthesisContexts.empty()) { 4300 if (T->canHaveNullability(/*ResultIfUnknown*/false) && 4301 !T->getNullability(S.Context)) { 4302 if (isVaList(T)) { 4303 // Record that we've seen a pointer, but do nothing else. 4304 if (NumPointersRemaining > 0) 4305 --NumPointersRemaining; 4306 } else { 4307 SimplePointerKind pointerKind = SimplePointerKind::Pointer; 4308 if (T->isBlockPointerType()) 4309 pointerKind = SimplePointerKind::BlockPointer; 4310 else if (T->isMemberPointerType()) 4311 pointerKind = SimplePointerKind::MemberPointer; 4312 4313 if (auto *attr = inferPointerNullability( 4314 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), 4315 D.getDeclSpec().getEndLoc(), 4316 D.getMutableDeclSpec().getAttributes(), 4317 D.getMutableDeclSpec().getAttributePool())) { 4318 T = state.getAttributedType( 4319 createNullabilityAttr(Context, *attr, *inferNullability), T, T); 4320 } 4321 } 4322 } 4323 4324 if (complainAboutMissingNullability == CAMN_Yes && 4325 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) && 4326 D.isPrototypeContext() && 4327 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) { 4328 checkNullabilityConsistency(S, SimplePointerKind::Array, 4329 D.getDeclSpec().getTypeSpecTypeLoc()); 4330 } 4331 } 4332 4333 bool ExpectNoDerefChunk = 4334 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref); 4335 4336 // Walk the DeclTypeInfo, building the recursive type as we go. 4337 // DeclTypeInfos are ordered from the identifier out, which is 4338 // opposite of what we want :). 4339 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4340 unsigned chunkIndex = e - i - 1; 4341 state.setCurrentChunkIndex(chunkIndex); 4342 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 4343 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; 4344 switch (DeclType.Kind) { 4345 case DeclaratorChunk::Paren: 4346 if (i == 0) 4347 warnAboutRedundantParens(S, D, T); 4348 T = S.BuildParenType(T); 4349 break; 4350 case DeclaratorChunk::BlockPointer: 4351 // If blocks are disabled, emit an error. 4352 if (!LangOpts.Blocks) 4353 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL; 4354 4355 // Handle pointer nullability. 4356 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc, 4357 DeclType.EndLoc, DeclType.getAttrs(), 4358 state.getDeclarator().getAttributePool()); 4359 4360 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 4361 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) { 4362 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly 4363 // qualified with const. 4364 if (LangOpts.OpenCL) 4365 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const; 4366 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 4367 } 4368 break; 4369 case DeclaratorChunk::Pointer: 4370 // Verify that we're not building a pointer to pointer to function with 4371 // exception specification. 4372 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 4373 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 4374 D.setInvalidType(true); 4375 // Build the type anyway. 4376 } 4377 4378 // Handle pointer nullability 4379 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, 4380 DeclType.EndLoc, DeclType.getAttrs(), 4381 state.getDeclarator().getAttributePool()); 4382 4383 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) { 4384 T = Context.getObjCObjectPointerType(T); 4385 if (DeclType.Ptr.TypeQuals) 4386 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 4387 break; 4388 } 4389 4390 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. 4391 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. 4392 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed. 4393 if (LangOpts.OpenCL) { 4394 if (T->isImageType() || T->isSamplerT() || T->isPipeType() || 4395 T->isBlockPointerType()) { 4396 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T; 4397 D.setInvalidType(true); 4398 } 4399 } 4400 4401 T = S.BuildPointerType(T, DeclType.Loc, Name); 4402 if (DeclType.Ptr.TypeQuals) 4403 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 4404 break; 4405 case DeclaratorChunk::Reference: { 4406 // Verify that we're not building a reference to pointer to function with 4407 // exception specification. 4408 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 4409 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 4410 D.setInvalidType(true); 4411 // Build the type anyway. 4412 } 4413 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 4414 4415 if (DeclType.Ref.HasRestrict) 4416 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 4417 break; 4418 } 4419 case DeclaratorChunk::Array: { 4420 // Verify that we're not building an array of pointers to function with 4421 // exception specification. 4422 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 4423 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 4424 D.setInvalidType(true); 4425 // Build the type anyway. 4426 } 4427 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 4428 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 4429 ArrayType::ArraySizeModifier ASM; 4430 if (ATI.isStar) 4431 ASM = ArrayType::Star; 4432 else if (ATI.hasStatic) 4433 ASM = ArrayType::Static; 4434 else 4435 ASM = ArrayType::Normal; 4436 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 4437 // FIXME: This check isn't quite right: it allows star in prototypes 4438 // for function definitions, and disallows some edge cases detailed 4439 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 4440 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 4441 ASM = ArrayType::Normal; 4442 D.setInvalidType(true); 4443 } 4444 4445 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static 4446 // shall appear only in a declaration of a function parameter with an 4447 // array type, ... 4448 if (ASM == ArrayType::Static || ATI.TypeQuals) { 4449 if (!(D.isPrototypeContext() || 4450 D.getContext() == DeclaratorContext::KNRTypeListContext)) { 4451 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << 4452 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 4453 // Remove the 'static' and the type qualifiers. 4454 if (ASM == ArrayType::Static) 4455 ASM = ArrayType::Normal; 4456 ATI.TypeQuals = 0; 4457 D.setInvalidType(true); 4458 } 4459 4460 // C99 6.7.5.2p1: ... and then only in the outermost array type 4461 // derivation. 4462 if (hasOuterPointerLikeChunk(D, chunkIndex)) { 4463 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << 4464 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 4465 if (ASM == ArrayType::Static) 4466 ASM = ArrayType::Normal; 4467 ATI.TypeQuals = 0; 4468 D.setInvalidType(true); 4469 } 4470 } 4471 const AutoType *AT = T->getContainedAutoType(); 4472 // Allow arrays of auto if we are a generic lambda parameter. 4473 // i.e. [](auto (&array)[5]) { return array[0]; }; OK 4474 if (AT && 4475 D.getContext() != DeclaratorContext::LambdaExprParameterContext) { 4476 // We've already diagnosed this for decltype(auto). 4477 if (!AT->isDecltypeAuto()) 4478 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) 4479 << getPrintableNameForEntity(Name) << T; 4480 T = QualType(); 4481 break; 4482 } 4483 4484 // Array parameters can be marked nullable as well, although it's not 4485 // necessary if they're marked 'static'. 4486 if (complainAboutMissingNullability == CAMN_Yes && 4487 !hasNullabilityAttr(DeclType.getAttrs()) && 4488 ASM != ArrayType::Static && 4489 D.isPrototypeContext() && 4490 !hasOuterPointerLikeChunk(D, chunkIndex)) { 4491 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc); 4492 } 4493 4494 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 4495 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 4496 break; 4497 } 4498 case DeclaratorChunk::Function: { 4499 // If the function declarator has a prototype (i.e. it is not () and 4500 // does not have a K&R-style identifier list), then the arguments are part 4501 // of the type, otherwise the argument list is (). 4502 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 4503 IsQualifiedFunction = 4504 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier(); 4505 4506 // Check for auto functions and trailing return type and adjust the 4507 // return type accordingly. 4508 if (!D.isInvalidType()) { 4509 // trailing-return-type is only required if we're declaring a function, 4510 // and not, for instance, a pointer to a function. 4511 if (D.getDeclSpec().hasAutoTypeSpec() && 4512 !FTI.hasTrailingReturnType() && chunkIndex == 0) { 4513 if (!S.getLangOpts().CPlusPlus14) { 4514 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 4515 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto 4516 ? diag::err_auto_missing_trailing_return 4517 : diag::err_deduced_return_type); 4518 T = Context.IntTy; 4519 D.setInvalidType(true); 4520 } else { 4521 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 4522 diag::warn_cxx11_compat_deduced_return_type); 4523 } 4524 } else if (FTI.hasTrailingReturnType()) { 4525 // T must be exactly 'auto' at this point. See CWG issue 681. 4526 if (isa<ParenType>(T)) { 4527 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens) 4528 << T << D.getSourceRange(); 4529 D.setInvalidType(true); 4530 } else if (D.getName().getKind() == 4531 UnqualifiedIdKind::IK_DeductionGuideName) { 4532 if (T != Context.DependentTy) { 4533 S.Diag(D.getDeclSpec().getBeginLoc(), 4534 diag::err_deduction_guide_with_complex_decl) 4535 << D.getSourceRange(); 4536 D.setInvalidType(true); 4537 } 4538 } else if (D.getContext() != DeclaratorContext::LambdaExprContext && 4539 (T.hasQualifiers() || !isa<AutoType>(T) || 4540 cast<AutoType>(T)->getKeyword() != 4541 AutoTypeKeyword::Auto)) { 4542 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 4543 diag::err_trailing_return_without_auto) 4544 << T << D.getDeclSpec().getSourceRange(); 4545 D.setInvalidType(true); 4546 } 4547 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); 4548 if (T.isNull()) { 4549 // An error occurred parsing the trailing return type. 4550 T = Context.IntTy; 4551 D.setInvalidType(true); 4552 } 4553 } else { 4554 // This function type is not the type of the entity being declared, 4555 // so checking the 'auto' is not the responsibility of this chunk. 4556 } 4557 } 4558 4559 // C99 6.7.5.3p1: The return type may not be a function or array type. 4560 // For conversion functions, we'll diagnose this particular error later. 4561 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) && 4562 (D.getName().getKind() != 4563 UnqualifiedIdKind::IK_ConversionFunctionId)) { 4564 unsigned diagID = diag::err_func_returning_array_function; 4565 // Last processing chunk in block context means this function chunk 4566 // represents the block. 4567 if (chunkIndex == 0 && 4568 D.getContext() == DeclaratorContext::BlockLiteralContext) 4569 diagID = diag::err_block_returning_array_function; 4570 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 4571 T = Context.IntTy; 4572 D.setInvalidType(true); 4573 } 4574 4575 // Do not allow returning half FP value. 4576 // FIXME: This really should be in BuildFunctionType. 4577 if (T->isHalfType()) { 4578 if (S.getLangOpts().OpenCL) { 4579 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 4580 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) 4581 << T << 0 /*pointer hint*/; 4582 D.setInvalidType(true); 4583 } 4584 } else if (!S.getLangOpts().HalfArgsAndReturns) { 4585 S.Diag(D.getIdentifierLoc(), 4586 diag::err_parameters_retval_cannot_have_fp16_type) << 1; 4587 D.setInvalidType(true); 4588 } 4589 } 4590 4591 if (LangOpts.OpenCL) { 4592 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a 4593 // function. 4594 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() || 4595 T->isPipeType()) { 4596 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) 4597 << T << 1 /*hint off*/; 4598 D.setInvalidType(true); 4599 } 4600 // OpenCL doesn't support variadic functions and blocks 4601 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf. 4602 // We also allow here any toolchain reserved identifiers. 4603 if (FTI.isVariadic && 4604 !(D.getIdentifier() && 4605 ((D.getIdentifier()->getName() == "printf" && 4606 (LangOpts.OpenCLCPlusPlus || LangOpts.OpenCLVersion >= 120)) || 4607 D.getIdentifier()->getName().startswith("__")))) { 4608 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function); 4609 D.setInvalidType(true); 4610 } 4611 } 4612 4613 // Methods cannot return interface types. All ObjC objects are 4614 // passed by reference. 4615 if (T->isObjCObjectType()) { 4616 SourceLocation DiagLoc, FixitLoc; 4617 if (TInfo) { 4618 DiagLoc = TInfo->getTypeLoc().getBeginLoc(); 4619 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc()); 4620 } else { 4621 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 4622 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc()); 4623 } 4624 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) 4625 << 0 << T 4626 << FixItHint::CreateInsertion(FixitLoc, "*"); 4627 4628 T = Context.getObjCObjectPointerType(T); 4629 if (TInfo) { 4630 TypeLocBuilder TLB; 4631 TLB.pushFullCopy(TInfo->getTypeLoc()); 4632 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); 4633 TLoc.setStarLoc(FixitLoc); 4634 TInfo = TLB.getTypeSourceInfo(Context, T); 4635 } 4636 4637 D.setInvalidType(true); 4638 } 4639 4640 // cv-qualifiers on return types are pointless except when the type is a 4641 // class type in C++. 4642 if ((T.getCVRQualifiers() || T->isAtomicType()) && 4643 !(S.getLangOpts().CPlusPlus && 4644 (T->isDependentType() || T->isRecordType()))) { 4645 if (T->isVoidType() && !S.getLangOpts().CPlusPlus && 4646 D.getFunctionDefinitionKind() == FDK_Definition) { 4647 // [6.9.1/3] qualified void return is invalid on a C 4648 // function definition. Apparently ok on declarations and 4649 // in C++ though (!) 4650 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; 4651 } else 4652 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); 4653 } 4654 4655 // Objective-C ARC ownership qualifiers are ignored on the function 4656 // return type (by type canonicalization). Complain if this attribute 4657 // was written here. 4658 if (T.getQualifiers().hasObjCLifetime()) { 4659 SourceLocation AttrLoc; 4660 if (chunkIndex + 1 < D.getNumTypeObjects()) { 4661 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 4662 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) { 4663 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { 4664 AttrLoc = AL.getLoc(); 4665 break; 4666 } 4667 } 4668 } 4669 if (AttrLoc.isInvalid()) { 4670 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { 4671 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { 4672 AttrLoc = AL.getLoc(); 4673 break; 4674 } 4675 } 4676 } 4677 4678 if (AttrLoc.isValid()) { 4679 // The ownership attributes are almost always written via 4680 // the predefined 4681 // __strong/__weak/__autoreleasing/__unsafe_unretained. 4682 if (AttrLoc.isMacroID()) 4683 AttrLoc = 4684 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin(); 4685 4686 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 4687 << T.getQualifiers().getObjCLifetime(); 4688 } 4689 } 4690 4691 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { 4692 // C++ [dcl.fct]p6: 4693 // Types shall not be defined in return or parameter types. 4694 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 4695 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 4696 << Context.getTypeDeclType(Tag); 4697 } 4698 4699 // Exception specs are not allowed in typedefs. Complain, but add it 4700 // anyway. 4701 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17) 4702 S.Diag(FTI.getExceptionSpecLocBeg(), 4703 diag::err_exception_spec_in_typedef) 4704 << (D.getContext() == DeclaratorContext::AliasDeclContext || 4705 D.getContext() == DeclaratorContext::AliasTemplateContext); 4706 4707 // If we see "T var();" or "T var(T());" at block scope, it is probably 4708 // an attempt to initialize a variable, not a function declaration. 4709 if (FTI.isAmbiguous) 4710 warnAboutAmbiguousFunction(S, D, DeclType, T); 4711 4712 FunctionType::ExtInfo EI( 4713 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex)); 4714 4715 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus 4716 && !LangOpts.OpenCL) { 4717 // Simple void foo(), where the incoming T is the result type. 4718 T = Context.getFunctionNoProtoType(T, EI); 4719 } else { 4720 // We allow a zero-parameter variadic function in C if the 4721 // function is marked with the "overloadable" attribute. Scan 4722 // for this attribute now. 4723 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) 4724 if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable)) 4725 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); 4726 4727 if (FTI.NumParams && FTI.Params[0].Param == nullptr) { 4728 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 4729 // definition. 4730 S.Diag(FTI.Params[0].IdentLoc, 4731 diag::err_ident_list_in_fn_declaration); 4732 D.setInvalidType(true); 4733 // Recover by creating a K&R-style function type. 4734 T = Context.getFunctionNoProtoType(T, EI); 4735 break; 4736 } 4737 4738 FunctionProtoType::ExtProtoInfo EPI; 4739 EPI.ExtInfo = EI; 4740 EPI.Variadic = FTI.isVariadic; 4741 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 4742 EPI.TypeQuals.addCVRUQualifiers( 4743 FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers() 4744 : 0); 4745 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 4746 : FTI.RefQualifierIsLValueRef? RQ_LValue 4747 : RQ_RValue; 4748 4749 // Otherwise, we have a function with a parameter list that is 4750 // potentially variadic. 4751 SmallVector<QualType, 16> ParamTys; 4752 ParamTys.reserve(FTI.NumParams); 4753 4754 SmallVector<FunctionProtoType::ExtParameterInfo, 16> 4755 ExtParameterInfos(FTI.NumParams); 4756 bool HasAnyInterestingExtParameterInfos = false; 4757 4758 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 4759 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 4760 QualType ParamTy = Param->getType(); 4761 assert(!ParamTy.isNull() && "Couldn't parse type?"); 4762 4763 // Look for 'void'. void is allowed only as a single parameter to a 4764 // function with no other parameters (C99 6.7.5.3p10). We record 4765 // int(void) as a FunctionProtoType with an empty parameter list. 4766 if (ParamTy->isVoidType()) { 4767 // If this is something like 'float(int, void)', reject it. 'void' 4768 // is an incomplete type (C99 6.2.5p19) and function decls cannot 4769 // have parameters of incomplete type. 4770 if (FTI.NumParams != 1 || FTI.isVariadic) { 4771 S.Diag(DeclType.Loc, diag::err_void_only_param); 4772 ParamTy = Context.IntTy; 4773 Param->setType(ParamTy); 4774 } else if (FTI.Params[i].Ident) { 4775 // Reject, but continue to parse 'int(void abc)'. 4776 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); 4777 ParamTy = Context.IntTy; 4778 Param->setType(ParamTy); 4779 } else { 4780 // Reject, but continue to parse 'float(const void)'. 4781 if (ParamTy.hasQualifiers()) 4782 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 4783 4784 // Do not add 'void' to the list. 4785 break; 4786 } 4787 } else if (ParamTy->isHalfType()) { 4788 // Disallow half FP parameters. 4789 // FIXME: This really should be in BuildFunctionType. 4790 if (S.getLangOpts().OpenCL) { 4791 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 4792 S.Diag(Param->getLocation(), 4793 diag::err_opencl_half_param) << ParamTy; 4794 D.setInvalidType(); 4795 Param->setInvalidDecl(); 4796 } 4797 } else if (!S.getLangOpts().HalfArgsAndReturns) { 4798 S.Diag(Param->getLocation(), 4799 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 4800 D.setInvalidType(); 4801 } 4802 } else if (!FTI.hasPrototype) { 4803 if (ParamTy->isPromotableIntegerType()) { 4804 ParamTy = Context.getPromotedIntegerType(ParamTy); 4805 Param->setKNRPromoted(true); 4806 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { 4807 if (BTy->getKind() == BuiltinType::Float) { 4808 ParamTy = Context.DoubleTy; 4809 Param->setKNRPromoted(true); 4810 } 4811 } 4812 } 4813 4814 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { 4815 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); 4816 HasAnyInterestingExtParameterInfos = true; 4817 } 4818 4819 if (auto attr = Param->getAttr<ParameterABIAttr>()) { 4820 ExtParameterInfos[i] = 4821 ExtParameterInfos[i].withABI(attr->getABI()); 4822 HasAnyInterestingExtParameterInfos = true; 4823 } 4824 4825 if (Param->hasAttr<PassObjectSizeAttr>()) { 4826 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); 4827 HasAnyInterestingExtParameterInfos = true; 4828 } 4829 4830 if (Param->hasAttr<NoEscapeAttr>()) { 4831 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true); 4832 HasAnyInterestingExtParameterInfos = true; 4833 } 4834 4835 ParamTys.push_back(ParamTy); 4836 } 4837 4838 if (HasAnyInterestingExtParameterInfos) { 4839 EPI.ExtParameterInfos = ExtParameterInfos.data(); 4840 checkExtParameterInfos(S, ParamTys, EPI, 4841 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); 4842 } 4843 4844 SmallVector<QualType, 4> Exceptions; 4845 SmallVector<ParsedType, 2> DynamicExceptions; 4846 SmallVector<SourceRange, 2> DynamicExceptionRanges; 4847 Expr *NoexceptExpr = nullptr; 4848 4849 if (FTI.getExceptionSpecType() == EST_Dynamic) { 4850 // FIXME: It's rather inefficient to have to split into two vectors 4851 // here. 4852 unsigned N = FTI.getNumExceptions(); 4853 DynamicExceptions.reserve(N); 4854 DynamicExceptionRanges.reserve(N); 4855 for (unsigned I = 0; I != N; ++I) { 4856 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 4857 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 4858 } 4859 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) { 4860 NoexceptExpr = FTI.NoexceptExpr; 4861 } 4862 4863 S.checkExceptionSpecification(D.isFunctionDeclarationContext(), 4864 FTI.getExceptionSpecType(), 4865 DynamicExceptions, 4866 DynamicExceptionRanges, 4867 NoexceptExpr, 4868 Exceptions, 4869 EPI.ExceptionSpec); 4870 4871 // FIXME: Set address space from attrs for C++ mode here. 4872 // OpenCLCPlusPlus: A class member function has an address space. 4873 auto IsClassMember = [&]() { 4874 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() && 4875 state.getDeclarator() 4876 .getCXXScopeSpec() 4877 .getScopeRep() 4878 ->getKind() == NestedNameSpecifier::TypeSpec) || 4879 state.getDeclarator().getContext() == 4880 DeclaratorContext::MemberContext; 4881 }; 4882 4883 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) { 4884 LangAS ASIdx = LangAS::Default; 4885 // Take address space attr if any and mark as invalid to avoid adding 4886 // them later while creating QualType. 4887 if (FTI.MethodQualifiers) 4888 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) { 4889 LangAS ASIdxNew = attr.asOpenCLLangAS(); 4890 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew, 4891 attr.getLoc())) 4892 D.setInvalidType(true); 4893 else 4894 ASIdx = ASIdxNew; 4895 } 4896 // If a class member function's address space is not set, set it to 4897 // __generic. 4898 LangAS AS = 4899 (ASIdx == LangAS::Default ? LangAS::opencl_generic : ASIdx); 4900 EPI.TypeQuals.addAddressSpace(AS); 4901 } 4902 T = Context.getFunctionType(T, ParamTys, EPI); 4903 } 4904 break; 4905 } 4906 case DeclaratorChunk::MemberPointer: { 4907 // The scope spec must refer to a class, or be dependent. 4908 CXXScopeSpec &SS = DeclType.Mem.Scope(); 4909 QualType ClsType; 4910 4911 // Handle pointer nullability. 4912 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc, 4913 DeclType.EndLoc, DeclType.getAttrs(), 4914 state.getDeclarator().getAttributePool()); 4915 4916 if (SS.isInvalid()) { 4917 // Avoid emitting extra errors if we already errored on the scope. 4918 D.setInvalidType(true); 4919 } else if (S.isDependentScopeSpecifier(SS) || 4920 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 4921 NestedNameSpecifier *NNS = SS.getScopeRep(); 4922 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 4923 switch (NNS->getKind()) { 4924 case NestedNameSpecifier::Identifier: 4925 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 4926 NNS->getAsIdentifier()); 4927 break; 4928 4929 case NestedNameSpecifier::Namespace: 4930 case NestedNameSpecifier::NamespaceAlias: 4931 case NestedNameSpecifier::Global: 4932 case NestedNameSpecifier::Super: 4933 llvm_unreachable("Nested-name-specifier must name a type"); 4934 4935 case NestedNameSpecifier::TypeSpec: 4936 case NestedNameSpecifier::TypeSpecWithTemplate: 4937 ClsType = QualType(NNS->getAsType(), 0); 4938 // Note: if the NNS has a prefix and ClsType is a nondependent 4939 // TemplateSpecializationType, then the NNS prefix is NOT included 4940 // in ClsType; hence we wrap ClsType into an ElaboratedType. 4941 // NOTE: in particular, no wrap occurs if ClsType already is an 4942 // Elaborated, DependentName, or DependentTemplateSpecialization. 4943 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 4944 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 4945 break; 4946 } 4947 } else { 4948 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 4949 diag::err_illegal_decl_mempointer_in_nonclass) 4950 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 4951 << DeclType.Mem.Scope().getRange(); 4952 D.setInvalidType(true); 4953 } 4954 4955 if (!ClsType.isNull()) 4956 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, 4957 D.getIdentifier()); 4958 if (T.isNull()) { 4959 T = Context.IntTy; 4960 D.setInvalidType(true); 4961 } else if (DeclType.Mem.TypeQuals) { 4962 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 4963 } 4964 break; 4965 } 4966 4967 case DeclaratorChunk::Pipe: { 4968 T = S.BuildReadPipeType(T, DeclType.Loc); 4969 processTypeAttrs(state, T, TAL_DeclSpec, 4970 D.getMutableDeclSpec().getAttributes()); 4971 break; 4972 } 4973 } 4974 4975 if (T.isNull()) { 4976 D.setInvalidType(true); 4977 T = Context.IntTy; 4978 } 4979 4980 // See if there are any attributes on this declarator chunk. 4981 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs()); 4982 4983 if (DeclType.Kind != DeclaratorChunk::Paren) { 4984 if (ExpectNoDerefChunk) { 4985 if (!IsNoDerefableChunk(DeclType)) 4986 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array); 4987 ExpectNoDerefChunk = false; 4988 } 4989 4990 ExpectNoDerefChunk = state.didParseNoDeref(); 4991 } 4992 } 4993 4994 if (ExpectNoDerefChunk) 4995 S.Diag(state.getDeclarator().getBeginLoc(), 4996 diag::warn_noderef_on_non_pointer_or_array); 4997 4998 // GNU warning -Wstrict-prototypes 4999 // Warn if a function declaration is without a prototype. 5000 // This warning is issued for all kinds of unprototyped function 5001 // declarations (i.e. function type typedef, function pointer etc.) 5002 // C99 6.7.5.3p14: 5003 // The empty list in a function declarator that is not part of a definition 5004 // of that function specifies that no information about the number or types 5005 // of the parameters is supplied. 5006 if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) { 5007 bool IsBlock = false; 5008 for (const DeclaratorChunk &DeclType : D.type_objects()) { 5009 switch (DeclType.Kind) { 5010 case DeclaratorChunk::BlockPointer: 5011 IsBlock = true; 5012 break; 5013 case DeclaratorChunk::Function: { 5014 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 5015 if (FTI.NumParams == 0 && !FTI.isVariadic) 5016 S.Diag(DeclType.Loc, diag::warn_strict_prototypes) 5017 << IsBlock 5018 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); 5019 IsBlock = false; 5020 break; 5021 } 5022 default: 5023 break; 5024 } 5025 } 5026 } 5027 5028 assert(!T.isNull() && "T must not be null after this point"); 5029 5030 if (LangOpts.CPlusPlus && T->isFunctionType()) { 5031 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 5032 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 5033 5034 // C++ 8.3.5p4: 5035 // A cv-qualifier-seq shall only be part of the function type 5036 // for a nonstatic member function, the function type to which a pointer 5037 // to member refers, or the top-level function type of a function typedef 5038 // declaration. 5039 // 5040 // Core issue 547 also allows cv-qualifiers on function types that are 5041 // top-level template type arguments. 5042 enum { NonMember, Member, DeductionGuide } Kind = NonMember; 5043 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) 5044 Kind = DeductionGuide; 5045 else if (!D.getCXXScopeSpec().isSet()) { 5046 if ((D.getContext() == DeclaratorContext::MemberContext || 5047 D.getContext() == DeclaratorContext::LambdaExprContext) && 5048 !D.getDeclSpec().isFriendSpecified()) 5049 Kind = Member; 5050 } else { 5051 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 5052 if (!DC || DC->isRecord()) 5053 Kind = Member; 5054 } 5055 5056 // C++11 [dcl.fct]p6 (w/DR1417): 5057 // An attempt to specify a function type with a cv-qualifier-seq or a 5058 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 5059 // - the function type for a non-static member function, 5060 // - the function type to which a pointer to member refers, 5061 // - the top-level function type of a function typedef declaration or 5062 // alias-declaration, 5063 // - the type-id in the default argument of a type-parameter, or 5064 // - the type-id of a template-argument for a type-parameter 5065 // 5066 // FIXME: Checking this here is insufficient. We accept-invalid on: 5067 // 5068 // template<typename T> struct S { void f(T); }; 5069 // S<int() const> s; 5070 // 5071 // ... for instance. 5072 if (IsQualifiedFunction && 5073 !(Kind == Member && 5074 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 5075 !IsTypedefName && 5076 D.getContext() != DeclaratorContext::TemplateArgContext && 5077 D.getContext() != DeclaratorContext::TemplateTypeArgContext) { 5078 SourceLocation Loc = D.getBeginLoc(); 5079 SourceRange RemovalRange; 5080 unsigned I; 5081 if (D.isFunctionDeclarator(I)) { 5082 SmallVector<SourceLocation, 4> RemovalLocs; 5083 const DeclaratorChunk &Chunk = D.getTypeObject(I); 5084 assert(Chunk.Kind == DeclaratorChunk::Function); 5085 5086 if (Chunk.Fun.hasRefQualifier()) 5087 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 5088 5089 if (Chunk.Fun.hasMethodTypeQualifiers()) 5090 Chunk.Fun.MethodQualifiers->forEachQualifier( 5091 [&](DeclSpec::TQ TypeQual, StringRef QualName, 5092 SourceLocation SL) { RemovalLocs.push_back(SL); }); 5093 5094 if (!RemovalLocs.empty()) { 5095 llvm::sort(RemovalLocs, 5096 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 5097 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 5098 Loc = RemovalLocs.front(); 5099 } 5100 } 5101 5102 S.Diag(Loc, diag::err_invalid_qualified_function_type) 5103 << Kind << D.isFunctionDeclarator() << T 5104 << getFunctionQualifiersAsString(FnTy) 5105 << FixItHint::CreateRemoval(RemovalRange); 5106 5107 // Strip the cv-qualifiers and ref-qualifiers from the type. 5108 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 5109 EPI.TypeQuals.removeCVRQualifiers(); 5110 EPI.RefQualifier = RQ_None; 5111 5112 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), 5113 EPI); 5114 // Rebuild any parens around the identifier in the function type. 5115 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5116 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 5117 break; 5118 T = S.BuildParenType(T); 5119 } 5120 } 5121 } 5122 5123 // Apply any undistributed attributes from the declarator. 5124 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); 5125 5126 // Diagnose any ignored type attributes. 5127 state.diagnoseIgnoredTypeAttrs(T); 5128 5129 // C++0x [dcl.constexpr]p9: 5130 // A constexpr specifier used in an object declaration declares the object 5131 // as const. 5132 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 5133 T.addConst(); 5134 } 5135 5136 // If there was an ellipsis in the declarator, the declaration declares a 5137 // parameter pack whose type may be a pack expansion type. 5138 if (D.hasEllipsis()) { 5139 // C++0x [dcl.fct]p13: 5140 // A declarator-id or abstract-declarator containing an ellipsis shall 5141 // only be used in a parameter-declaration. Such a parameter-declaration 5142 // is a parameter pack (14.5.3). [...] 5143 switch (D.getContext()) { 5144 case DeclaratorContext::PrototypeContext: 5145 case DeclaratorContext::LambdaExprParameterContext: 5146 // C++0x [dcl.fct]p13: 5147 // [...] When it is part of a parameter-declaration-clause, the 5148 // parameter pack is a function parameter pack (14.5.3). The type T 5149 // of the declarator-id of the function parameter pack shall contain 5150 // a template parameter pack; each template parameter pack in T is 5151 // expanded by the function parameter pack. 5152 // 5153 // We represent function parameter packs as function parameters whose 5154 // type is a pack expansion. 5155 if (!T->containsUnexpandedParameterPack()) { 5156 S.Diag(D.getEllipsisLoc(), 5157 diag::err_function_parameter_pack_without_parameter_packs) 5158 << T << D.getSourceRange(); 5159 D.setEllipsisLoc(SourceLocation()); 5160 } else { 5161 T = Context.getPackExpansionType(T, None); 5162 } 5163 break; 5164 case DeclaratorContext::TemplateParamContext: 5165 // C++0x [temp.param]p15: 5166 // If a template-parameter is a [...] is a parameter-declaration that 5167 // declares a parameter pack (8.3.5), then the template-parameter is a 5168 // template parameter pack (14.5.3). 5169 // 5170 // Note: core issue 778 clarifies that, if there are any unexpanded 5171 // parameter packs in the type of the non-type template parameter, then 5172 // it expands those parameter packs. 5173 if (T->containsUnexpandedParameterPack()) 5174 T = Context.getPackExpansionType(T, None); 5175 else 5176 S.Diag(D.getEllipsisLoc(), 5177 LangOpts.CPlusPlus11 5178 ? diag::warn_cxx98_compat_variadic_templates 5179 : diag::ext_variadic_templates); 5180 break; 5181 5182 case DeclaratorContext::FileContext: 5183 case DeclaratorContext::KNRTypeListContext: 5184 case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic 5185 // here? 5186 case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic 5187 // here? 5188 case DeclaratorContext::TypeNameContext: 5189 case DeclaratorContext::FunctionalCastContext: 5190 case DeclaratorContext::CXXNewContext: 5191 case DeclaratorContext::AliasDeclContext: 5192 case DeclaratorContext::AliasTemplateContext: 5193 case DeclaratorContext::MemberContext: 5194 case DeclaratorContext::BlockContext: 5195 case DeclaratorContext::ForContext: 5196 case DeclaratorContext::InitStmtContext: 5197 case DeclaratorContext::ConditionContext: 5198 case DeclaratorContext::CXXCatchContext: 5199 case DeclaratorContext::ObjCCatchContext: 5200 case DeclaratorContext::BlockLiteralContext: 5201 case DeclaratorContext::LambdaExprContext: 5202 case DeclaratorContext::ConversionIdContext: 5203 case DeclaratorContext::TrailingReturnContext: 5204 case DeclaratorContext::TrailingReturnVarContext: 5205 case DeclaratorContext::TemplateArgContext: 5206 case DeclaratorContext::TemplateTypeArgContext: 5207 // FIXME: We may want to allow parameter packs in block-literal contexts 5208 // in the future. 5209 S.Diag(D.getEllipsisLoc(), 5210 diag::err_ellipsis_in_declarator_not_parameter); 5211 D.setEllipsisLoc(SourceLocation()); 5212 break; 5213 } 5214 } 5215 5216 assert(!T.isNull() && "T must not be null at the end of this function"); 5217 if (D.isInvalidType()) 5218 return Context.getTrivialTypeSourceInfo(T); 5219 5220 return GetTypeSourceInfoForDeclarator(state, T, TInfo); 5221 } 5222 5223 /// GetTypeForDeclarator - Convert the type for the specified 5224 /// declarator to Type instances. 5225 /// 5226 /// The result of this call will never be null, but the associated 5227 /// type may be a null type if there's an unrecoverable error. 5228 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 5229 // Determine the type of the declarator. Not all forms of declarator 5230 // have a type. 5231 5232 TypeProcessingState state(*this, D); 5233 5234 TypeSourceInfo *ReturnTypeInfo = nullptr; 5235 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 5236 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 5237 inferARCWriteback(state, T); 5238 5239 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 5240 } 5241 5242 static void transferARCOwnershipToDeclSpec(Sema &S, 5243 QualType &declSpecTy, 5244 Qualifiers::ObjCLifetime ownership) { 5245 if (declSpecTy->isObjCRetainableType() && 5246 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 5247 Qualifiers qs; 5248 qs.addObjCLifetime(ownership); 5249 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 5250 } 5251 } 5252 5253 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 5254 Qualifiers::ObjCLifetime ownership, 5255 unsigned chunkIndex) { 5256 Sema &S = state.getSema(); 5257 Declarator &D = state.getDeclarator(); 5258 5259 // Look for an explicit lifetime attribute. 5260 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 5261 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership)) 5262 return; 5263 5264 const char *attrStr = nullptr; 5265 switch (ownership) { 5266 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 5267 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 5268 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 5269 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 5270 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 5271 } 5272 5273 IdentifierLoc *Arg = new (S.Context) IdentifierLoc; 5274 Arg->Ident = &S.Context.Idents.get(attrStr); 5275 Arg->Loc = SourceLocation(); 5276 5277 ArgsUnion Args(Arg); 5278 5279 // If there wasn't one, add one (with an invalid source location 5280 // so that we don't make an AttributedType for it). 5281 ParsedAttr *attr = D.getAttributePool().create( 5282 &S.Context.Idents.get("objc_ownership"), SourceLocation(), 5283 /*scope*/ nullptr, SourceLocation(), 5284 /*args*/ &Args, 1, ParsedAttr::AS_GNU); 5285 chunk.getAttrs().addAtEnd(attr); 5286 // TODO: mark whether we did this inference? 5287 } 5288 5289 /// Used for transferring ownership in casts resulting in l-values. 5290 static void transferARCOwnership(TypeProcessingState &state, 5291 QualType &declSpecTy, 5292 Qualifiers::ObjCLifetime ownership) { 5293 Sema &S = state.getSema(); 5294 Declarator &D = state.getDeclarator(); 5295 5296 int inner = -1; 5297 bool hasIndirection = false; 5298 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5299 DeclaratorChunk &chunk = D.getTypeObject(i); 5300 switch (chunk.Kind) { 5301 case DeclaratorChunk::Paren: 5302 // Ignore parens. 5303 break; 5304 5305 case DeclaratorChunk::Array: 5306 case DeclaratorChunk::Reference: 5307 case DeclaratorChunk::Pointer: 5308 if (inner != -1) 5309 hasIndirection = true; 5310 inner = i; 5311 break; 5312 5313 case DeclaratorChunk::BlockPointer: 5314 if (inner != -1) 5315 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 5316 return; 5317 5318 case DeclaratorChunk::Function: 5319 case DeclaratorChunk::MemberPointer: 5320 case DeclaratorChunk::Pipe: 5321 return; 5322 } 5323 } 5324 5325 if (inner == -1) 5326 return; 5327 5328 DeclaratorChunk &chunk = D.getTypeObject(inner); 5329 if (chunk.Kind == DeclaratorChunk::Pointer) { 5330 if (declSpecTy->isObjCRetainableType()) 5331 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 5332 if (declSpecTy->isObjCObjectType() && hasIndirection) 5333 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 5334 } else { 5335 assert(chunk.Kind == DeclaratorChunk::Array || 5336 chunk.Kind == DeclaratorChunk::Reference); 5337 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 5338 } 5339 } 5340 5341 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 5342 TypeProcessingState state(*this, D); 5343 5344 TypeSourceInfo *ReturnTypeInfo = nullptr; 5345 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 5346 5347 if (getLangOpts().ObjC) { 5348 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 5349 if (ownership != Qualifiers::OCL_None) 5350 transferARCOwnership(state, declSpecTy, ownership); 5351 } 5352 5353 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 5354 } 5355 5356 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 5357 TypeProcessingState &State) { 5358 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr())); 5359 } 5360 5361 namespace { 5362 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 5363 ASTContext &Context; 5364 TypeProcessingState &State; 5365 const DeclSpec &DS; 5366 5367 public: 5368 TypeSpecLocFiller(ASTContext &Context, TypeProcessingState &State, 5369 const DeclSpec &DS) 5370 : Context(Context), State(State), DS(DS) {} 5371 5372 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 5373 Visit(TL.getModifiedLoc()); 5374 fillAttributedTypeLoc(TL, State); 5375 } 5376 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 5377 Visit(TL.getUnqualifiedLoc()); 5378 } 5379 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 5380 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5381 } 5382 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 5383 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5384 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 5385 // addition field. What we have is good enough for dispay of location 5386 // of 'fixit' on interface name. 5387 TL.setNameEndLoc(DS.getEndLoc()); 5388 } 5389 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 5390 TypeSourceInfo *RepTInfo = nullptr; 5391 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5392 TL.copy(RepTInfo->getTypeLoc()); 5393 } 5394 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 5395 TypeSourceInfo *RepTInfo = nullptr; 5396 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5397 TL.copy(RepTInfo->getTypeLoc()); 5398 } 5399 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 5400 TypeSourceInfo *TInfo = nullptr; 5401 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5402 5403 // If we got no declarator info from previous Sema routines, 5404 // just fill with the typespec loc. 5405 if (!TInfo) { 5406 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 5407 return; 5408 } 5409 5410 TypeLoc OldTL = TInfo->getTypeLoc(); 5411 if (TInfo->getType()->getAs<ElaboratedType>()) { 5412 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 5413 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 5414 .castAs<TemplateSpecializationTypeLoc>(); 5415 TL.copy(NamedTL); 5416 } else { 5417 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 5418 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 5419 } 5420 5421 } 5422 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 5423 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 5424 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 5425 TL.setParensRange(DS.getTypeofParensRange()); 5426 } 5427 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 5428 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 5429 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 5430 TL.setParensRange(DS.getTypeofParensRange()); 5431 assert(DS.getRepAsType()); 5432 TypeSourceInfo *TInfo = nullptr; 5433 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5434 TL.setUnderlyingTInfo(TInfo); 5435 } 5436 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 5437 // FIXME: This holds only because we only have one unary transform. 5438 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 5439 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 5440 TL.setParensRange(DS.getTypeofParensRange()); 5441 assert(DS.getRepAsType()); 5442 TypeSourceInfo *TInfo = nullptr; 5443 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5444 TL.setUnderlyingTInfo(TInfo); 5445 } 5446 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 5447 // By default, use the source location of the type specifier. 5448 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 5449 if (TL.needsExtraLocalData()) { 5450 // Set info for the written builtin specifiers. 5451 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 5452 // Try to have a meaningful source location. 5453 if (TL.getWrittenSignSpec() != TSS_unspecified) 5454 TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); 5455 if (TL.getWrittenWidthSpec() != TSW_unspecified) 5456 TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); 5457 } 5458 } 5459 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 5460 ElaboratedTypeKeyword Keyword 5461 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 5462 if (DS.getTypeSpecType() == TST_typename) { 5463 TypeSourceInfo *TInfo = nullptr; 5464 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5465 if (TInfo) { 5466 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 5467 return; 5468 } 5469 } 5470 TL.setElaboratedKeywordLoc(Keyword != ETK_None 5471 ? DS.getTypeSpecTypeLoc() 5472 : SourceLocation()); 5473 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 5474 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 5475 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 5476 } 5477 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 5478 assert(DS.getTypeSpecType() == TST_typename); 5479 TypeSourceInfo *TInfo = nullptr; 5480 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5481 assert(TInfo); 5482 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 5483 } 5484 void VisitDependentTemplateSpecializationTypeLoc( 5485 DependentTemplateSpecializationTypeLoc TL) { 5486 assert(DS.getTypeSpecType() == TST_typename); 5487 TypeSourceInfo *TInfo = nullptr; 5488 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5489 assert(TInfo); 5490 TL.copy( 5491 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 5492 } 5493 void VisitTagTypeLoc(TagTypeLoc TL) { 5494 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 5495 } 5496 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 5497 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 5498 // or an _Atomic qualifier. 5499 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 5500 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 5501 TL.setParensRange(DS.getTypeofParensRange()); 5502 5503 TypeSourceInfo *TInfo = nullptr; 5504 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5505 assert(TInfo); 5506 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 5507 } else { 5508 TL.setKWLoc(DS.getAtomicSpecLoc()); 5509 // No parens, to indicate this was spelled as an _Atomic qualifier. 5510 TL.setParensRange(SourceRange()); 5511 Visit(TL.getValueLoc()); 5512 } 5513 } 5514 5515 void VisitPipeTypeLoc(PipeTypeLoc TL) { 5516 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 5517 5518 TypeSourceInfo *TInfo = nullptr; 5519 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5520 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 5521 } 5522 5523 void VisitTypeLoc(TypeLoc TL) { 5524 // FIXME: add other typespec types and change this to an assert. 5525 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 5526 } 5527 }; 5528 5529 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 5530 ASTContext &Context; 5531 TypeProcessingState &State; 5532 const DeclaratorChunk &Chunk; 5533 5534 public: 5535 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State, 5536 const DeclaratorChunk &Chunk) 5537 : Context(Context), State(State), Chunk(Chunk) {} 5538 5539 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 5540 llvm_unreachable("qualified type locs not expected here!"); 5541 } 5542 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 5543 llvm_unreachable("decayed type locs not expected here!"); 5544 } 5545 5546 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 5547 fillAttributedTypeLoc(TL, State); 5548 } 5549 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 5550 // nothing 5551 } 5552 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 5553 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 5554 TL.setCaretLoc(Chunk.Loc); 5555 } 5556 void VisitPointerTypeLoc(PointerTypeLoc TL) { 5557 assert(Chunk.Kind == DeclaratorChunk::Pointer); 5558 TL.setStarLoc(Chunk.Loc); 5559 } 5560 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 5561 assert(Chunk.Kind == DeclaratorChunk::Pointer); 5562 TL.setStarLoc(Chunk.Loc); 5563 } 5564 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 5565 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 5566 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 5567 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 5568 5569 const Type* ClsTy = TL.getClass(); 5570 QualType ClsQT = QualType(ClsTy, 0); 5571 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 5572 // Now copy source location info into the type loc component. 5573 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 5574 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 5575 case NestedNameSpecifier::Identifier: 5576 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 5577 { 5578 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 5579 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 5580 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 5581 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 5582 } 5583 break; 5584 5585 case NestedNameSpecifier::TypeSpec: 5586 case NestedNameSpecifier::TypeSpecWithTemplate: 5587 if (isa<ElaboratedType>(ClsTy)) { 5588 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 5589 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 5590 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 5591 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 5592 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 5593 } else { 5594 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 5595 } 5596 break; 5597 5598 case NestedNameSpecifier::Namespace: 5599 case NestedNameSpecifier::NamespaceAlias: 5600 case NestedNameSpecifier::Global: 5601 case NestedNameSpecifier::Super: 5602 llvm_unreachable("Nested-name-specifier must name a type"); 5603 } 5604 5605 // Finally fill in MemberPointerLocInfo fields. 5606 TL.setStarLoc(Chunk.Loc); 5607 TL.setClassTInfo(ClsTInfo); 5608 } 5609 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 5610 assert(Chunk.Kind == DeclaratorChunk::Reference); 5611 // 'Amp' is misleading: this might have been originally 5612 /// spelled with AmpAmp. 5613 TL.setAmpLoc(Chunk.Loc); 5614 } 5615 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 5616 assert(Chunk.Kind == DeclaratorChunk::Reference); 5617 assert(!Chunk.Ref.LValueRef); 5618 TL.setAmpAmpLoc(Chunk.Loc); 5619 } 5620 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 5621 assert(Chunk.Kind == DeclaratorChunk::Array); 5622 TL.setLBracketLoc(Chunk.Loc); 5623 TL.setRBracketLoc(Chunk.EndLoc); 5624 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 5625 } 5626 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 5627 assert(Chunk.Kind == DeclaratorChunk::Function); 5628 TL.setLocalRangeBegin(Chunk.Loc); 5629 TL.setLocalRangeEnd(Chunk.EndLoc); 5630 5631 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 5632 TL.setLParenLoc(FTI.getLParenLoc()); 5633 TL.setRParenLoc(FTI.getRParenLoc()); 5634 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { 5635 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 5636 TL.setParam(tpi++, Param); 5637 } 5638 TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); 5639 } 5640 void VisitParenTypeLoc(ParenTypeLoc TL) { 5641 assert(Chunk.Kind == DeclaratorChunk::Paren); 5642 TL.setLParenLoc(Chunk.Loc); 5643 TL.setRParenLoc(Chunk.EndLoc); 5644 } 5645 void VisitPipeTypeLoc(PipeTypeLoc TL) { 5646 assert(Chunk.Kind == DeclaratorChunk::Pipe); 5647 TL.setKWLoc(Chunk.Loc); 5648 } 5649 5650 void VisitTypeLoc(TypeLoc TL) { 5651 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 5652 } 5653 }; 5654 } // end anonymous namespace 5655 5656 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 5657 SourceLocation Loc; 5658 switch (Chunk.Kind) { 5659 case DeclaratorChunk::Function: 5660 case DeclaratorChunk::Array: 5661 case DeclaratorChunk::Paren: 5662 case DeclaratorChunk::Pipe: 5663 llvm_unreachable("cannot be _Atomic qualified"); 5664 5665 case DeclaratorChunk::Pointer: 5666 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); 5667 break; 5668 5669 case DeclaratorChunk::BlockPointer: 5670 case DeclaratorChunk::Reference: 5671 case DeclaratorChunk::MemberPointer: 5672 // FIXME: Provide a source location for the _Atomic keyword. 5673 break; 5674 } 5675 5676 ATL.setKWLoc(Loc); 5677 ATL.setParensRange(SourceRange()); 5678 } 5679 5680 static void 5681 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, 5682 const ParsedAttributesView &Attrs) { 5683 for (const ParsedAttr &AL : Attrs) { 5684 if (AL.getKind() == ParsedAttr::AT_AddressSpace) { 5685 DASTL.setAttrNameLoc(AL.getLoc()); 5686 DASTL.setAttrExprOperand(AL.getArgAsExpr(0)); 5687 DASTL.setAttrOperandParensRange(SourceRange()); 5688 return; 5689 } 5690 } 5691 5692 llvm_unreachable( 5693 "no address_space attribute found at the expected location!"); 5694 } 5695 5696 /// Create and instantiate a TypeSourceInfo with type source information. 5697 /// 5698 /// \param T QualType referring to the type as written in source code. 5699 /// 5700 /// \param ReturnTypeInfo For declarators whose return type does not show 5701 /// up in the normal place in the declaration specifiers (such as a C++ 5702 /// conversion function), this pointer will refer to a type source information 5703 /// for that return type. 5704 static TypeSourceInfo * 5705 GetTypeSourceInfoForDeclarator(TypeProcessingState &State, 5706 QualType T, TypeSourceInfo *ReturnTypeInfo) { 5707 Sema &S = State.getSema(); 5708 Declarator &D = State.getDeclarator(); 5709 5710 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T); 5711 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 5712 5713 // Handle parameter packs whose type is a pack expansion. 5714 if (isa<PackExpansionType>(T)) { 5715 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 5716 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 5717 } 5718 5719 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5720 // An AtomicTypeLoc might be produced by an atomic qualifier in this 5721 // declarator chunk. 5722 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 5723 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 5724 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 5725 } 5726 5727 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 5728 fillAttributedTypeLoc(TL, State); 5729 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 5730 } 5731 5732 while (DependentAddressSpaceTypeLoc TL = 5733 CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { 5734 fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs()); 5735 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc(); 5736 } 5737 5738 // FIXME: Ordering here? 5739 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) 5740 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 5741 5742 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL); 5743 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 5744 } 5745 5746 // If we have different source information for the return type, use 5747 // that. This really only applies to C++ conversion functions. 5748 if (ReturnTypeInfo) { 5749 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 5750 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 5751 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 5752 } else { 5753 TypeSpecLocFiller(S.Context, State, D.getDeclSpec()).Visit(CurrTL); 5754 } 5755 5756 return TInfo; 5757 } 5758 5759 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo. 5760 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 5761 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 5762 // and Sema during declaration parsing. Try deallocating/caching them when 5763 // it's appropriate, instead of allocating them and keeping them around. 5764 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 5765 TypeAlignment); 5766 new (LocT) LocInfoType(T, TInfo); 5767 assert(LocT->getTypeClass() != T->getTypeClass() && 5768 "LocInfoType's TypeClass conflicts with an existing Type class"); 5769 return ParsedType::make(QualType(LocT, 0)); 5770 } 5771 5772 void LocInfoType::getAsStringInternal(std::string &Str, 5773 const PrintingPolicy &Policy) const { 5774 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 5775 " was used directly instead of getting the QualType through" 5776 " GetTypeFromParser"); 5777 } 5778 5779 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 5780 // C99 6.7.6: Type names have no identifier. This is already validated by 5781 // the parser. 5782 assert(D.getIdentifier() == nullptr && 5783 "Type name should have no identifier!"); 5784 5785 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5786 QualType T = TInfo->getType(); 5787 if (D.isInvalidType()) 5788 return true; 5789 5790 // Make sure there are no unused decl attributes on the declarator. 5791 // We don't want to do this for ObjC parameters because we're going 5792 // to apply them to the actual parameter declaration. 5793 // Likewise, we don't want to do this for alias declarations, because 5794 // we are actually going to build a declaration from this eventually. 5795 if (D.getContext() != DeclaratorContext::ObjCParameterContext && 5796 D.getContext() != DeclaratorContext::AliasDeclContext && 5797 D.getContext() != DeclaratorContext::AliasTemplateContext) 5798 checkUnusedDeclAttributes(D); 5799 5800 if (getLangOpts().CPlusPlus) { 5801 // Check that there are no default arguments (C++ only). 5802 CheckExtraCXXDefaultArguments(D); 5803 } 5804 5805 return CreateParsedType(T, TInfo); 5806 } 5807 5808 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 5809 QualType T = Context.getObjCInstanceType(); 5810 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 5811 return CreateParsedType(T, TInfo); 5812 } 5813 5814 //===----------------------------------------------------------------------===// 5815 // Type Attribute Processing 5816 //===----------------------------------------------------------------------===// 5817 5818 /// Build an AddressSpace index from a constant expression and diagnose any 5819 /// errors related to invalid address_spaces. Returns true on successfully 5820 /// building an AddressSpace index. 5821 static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, 5822 const Expr *AddrSpace, 5823 SourceLocation AttrLoc) { 5824 if (!AddrSpace->isValueDependent()) { 5825 llvm::APSInt addrSpace(32); 5826 if (!AddrSpace->isIntegerConstantExpr(addrSpace, S.Context)) { 5827 S.Diag(AttrLoc, diag::err_attribute_argument_type) 5828 << "'address_space'" << AANT_ArgumentIntegerConstant 5829 << AddrSpace->getSourceRange(); 5830 return false; 5831 } 5832 5833 // Bounds checking. 5834 if (addrSpace.isSigned()) { 5835 if (addrSpace.isNegative()) { 5836 S.Diag(AttrLoc, diag::err_attribute_address_space_negative) 5837 << AddrSpace->getSourceRange(); 5838 return false; 5839 } 5840 addrSpace.setIsSigned(false); 5841 } 5842 5843 llvm::APSInt max(addrSpace.getBitWidth()); 5844 max = 5845 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; 5846 if (addrSpace > max) { 5847 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high) 5848 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); 5849 return false; 5850 } 5851 5852 ASIdx = 5853 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue())); 5854 return true; 5855 } 5856 5857 // Default value for DependentAddressSpaceTypes 5858 ASIdx = LangAS::Default; 5859 return true; 5860 } 5861 5862 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression 5863 /// is uninstantiated. If instantiated it will apply the appropriate address 5864 /// space to the type. This function allows dependent template variables to be 5865 /// used in conjunction with the address_space attribute 5866 QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, 5867 SourceLocation AttrLoc) { 5868 if (!AddrSpace->isValueDependent()) { 5869 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx, 5870 AttrLoc)) 5871 return QualType(); 5872 5873 return Context.getAddrSpaceQualType(T, ASIdx); 5874 } 5875 5876 // A check with similar intentions as checking if a type already has an 5877 // address space except for on a dependent types, basically if the 5878 // current type is already a DependentAddressSpaceType then its already 5879 // lined up to have another address space on it and we can't have 5880 // multiple address spaces on the one pointer indirection 5881 if (T->getAs<DependentAddressSpaceType>()) { 5882 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); 5883 return QualType(); 5884 } 5885 5886 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc); 5887 } 5888 5889 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, 5890 SourceLocation AttrLoc) { 5891 LangAS ASIdx; 5892 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc)) 5893 return QualType(); 5894 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc); 5895 } 5896 5897 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 5898 /// specified type. The attribute contains 1 argument, the id of the address 5899 /// space for the type. 5900 static void HandleAddressSpaceTypeAttribute(QualType &Type, 5901 const ParsedAttr &Attr, 5902 TypeProcessingState &State) { 5903 Sema &S = State.getSema(); 5904 5905 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 5906 // qualified by an address-space qualifier." 5907 if (Type->isFunctionType()) { 5908 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 5909 Attr.setInvalid(); 5910 return; 5911 } 5912 5913 LangAS ASIdx; 5914 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) { 5915 5916 // Check the attribute arguments. 5917 if (Attr.getNumArgs() != 1) { 5918 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 5919 << 1; 5920 Attr.setInvalid(); 5921 return; 5922 } 5923 5924 Expr *ASArgExpr; 5925 if (Attr.isArgIdent(0)) { 5926 // Special case where the argument is a template id. 5927 CXXScopeSpec SS; 5928 SourceLocation TemplateKWLoc; 5929 UnqualifiedId id; 5930 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); 5931 5932 ExprResult AddrSpace = S.ActOnIdExpression( 5933 S.getCurScope(), SS, TemplateKWLoc, id, /*HasTrailingLParen=*/false, 5934 /*IsAddressOfOperand=*/false); 5935 if (AddrSpace.isInvalid()) 5936 return; 5937 5938 ASArgExpr = static_cast<Expr *>(AddrSpace.get()); 5939 } else { 5940 ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 5941 } 5942 5943 LangAS ASIdx; 5944 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) { 5945 Attr.setInvalid(); 5946 return; 5947 } 5948 5949 ASTContext &Ctx = S.Context; 5950 auto *ASAttr = ::new (Ctx) AddressSpaceAttr( 5951 Attr.getRange(), Ctx, Attr.getAttributeSpellingListIndex(), 5952 static_cast<unsigned>(ASIdx)); 5953 5954 // If the expression is not value dependent (not templated), then we can 5955 // apply the address space qualifiers just to the equivalent type. 5956 // Otherwise, we make an AttributedType with the modified and equivalent 5957 // type the same, and wrap it in a DependentAddressSpaceType. When this 5958 // dependent type is resolved, the qualifier is added to the equivalent type 5959 // later. 5960 QualType T; 5961 if (!ASArgExpr->isValueDependent()) { 5962 QualType EquivType = 5963 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc()); 5964 if (EquivType.isNull()) { 5965 Attr.setInvalid(); 5966 return; 5967 } 5968 T = State.getAttributedType(ASAttr, Type, EquivType); 5969 } else { 5970 T = State.getAttributedType(ASAttr, Type, Type); 5971 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc()); 5972 } 5973 5974 if (!T.isNull()) 5975 Type = T; 5976 else 5977 Attr.setInvalid(); 5978 } else { 5979 // The keyword-based type attributes imply which address space to use. 5980 ASIdx = Attr.asOpenCLLangAS(); 5981 if (ASIdx == LangAS::Default) 5982 llvm_unreachable("Invalid address space"); 5983 5984 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx, 5985 Attr.getLoc())) { 5986 Attr.setInvalid(); 5987 return; 5988 } 5989 5990 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 5991 } 5992 } 5993 5994 /// Does this type have a "direct" ownership qualifier? That is, 5995 /// is it written like "__strong id", as opposed to something like 5996 /// "typeof(foo)", where that happens to be strong? 5997 static bool hasDirectOwnershipQualifier(QualType type) { 5998 // Fast path: no qualifier at all. 5999 assert(type.getQualifiers().hasObjCLifetime()); 6000 6001 while (true) { 6002 // __strong id 6003 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 6004 if (attr->getAttrKind() == attr::ObjCOwnership) 6005 return true; 6006 6007 type = attr->getModifiedType(); 6008 6009 // X *__strong (...) 6010 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 6011 type = paren->getInnerType(); 6012 6013 // That's it for things we want to complain about. In particular, 6014 // we do not want to look through typedefs, typeof(expr), 6015 // typeof(type), or any other way that the type is somehow 6016 // abstracted. 6017 } else { 6018 6019 return false; 6020 } 6021 } 6022 } 6023 6024 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 6025 /// attribute on the specified type. 6026 /// 6027 /// Returns 'true' if the attribute was handled. 6028 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 6029 ParsedAttr &attr, QualType &type) { 6030 bool NonObjCPointer = false; 6031 6032 if (!type->isDependentType() && !type->isUndeducedType()) { 6033 if (const PointerType *ptr = type->getAs<PointerType>()) { 6034 QualType pointee = ptr->getPointeeType(); 6035 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 6036 return false; 6037 // It is important not to lose the source info that there was an attribute 6038 // applied to non-objc pointer. We will create an attributed type but 6039 // its type will be the same as the original type. 6040 NonObjCPointer = true; 6041 } else if (!type->isObjCRetainableType()) { 6042 return false; 6043 } 6044 6045 // Don't accept an ownership attribute in the declspec if it would 6046 // just be the return type of a block pointer. 6047 if (state.isProcessingDeclSpec()) { 6048 Declarator &D = state.getDeclarator(); 6049 if (maybeMovePastReturnType(D, D.getNumTypeObjects(), 6050 /*onlyBlockPointers=*/true)) 6051 return false; 6052 } 6053 } 6054 6055 Sema &S = state.getSema(); 6056 SourceLocation AttrLoc = attr.getLoc(); 6057 if (AttrLoc.isMacroID()) 6058 AttrLoc = 6059 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin(); 6060 6061 if (!attr.isArgIdent(0)) { 6062 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr 6063 << AANT_ArgumentString; 6064 attr.setInvalid(); 6065 return true; 6066 } 6067 6068 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 6069 Qualifiers::ObjCLifetime lifetime; 6070 if (II->isStr("none")) 6071 lifetime = Qualifiers::OCL_ExplicitNone; 6072 else if (II->isStr("strong")) 6073 lifetime = Qualifiers::OCL_Strong; 6074 else if (II->isStr("weak")) 6075 lifetime = Qualifiers::OCL_Weak; 6076 else if (II->isStr("autoreleasing")) 6077 lifetime = Qualifiers::OCL_Autoreleasing; 6078 else { 6079 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 6080 << attr.getName() << II; 6081 attr.setInvalid(); 6082 return true; 6083 } 6084 6085 // Just ignore lifetime attributes other than __weak and __unsafe_unretained 6086 // outside of ARC mode. 6087 if (!S.getLangOpts().ObjCAutoRefCount && 6088 lifetime != Qualifiers::OCL_Weak && 6089 lifetime != Qualifiers::OCL_ExplicitNone) { 6090 return true; 6091 } 6092 6093 SplitQualType underlyingType = type.split(); 6094 6095 // Check for redundant/conflicting ownership qualifiers. 6096 if (Qualifiers::ObjCLifetime previousLifetime 6097 = type.getQualifiers().getObjCLifetime()) { 6098 // If it's written directly, that's an error. 6099 if (hasDirectOwnershipQualifier(type)) { 6100 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 6101 << type; 6102 return true; 6103 } 6104 6105 // Otherwise, if the qualifiers actually conflict, pull sugar off 6106 // and remove the ObjCLifetime qualifiers. 6107 if (previousLifetime != lifetime) { 6108 // It's possible to have multiple local ObjCLifetime qualifiers. We 6109 // can't stop after we reach a type that is directly qualified. 6110 const Type *prevTy = nullptr; 6111 while (!prevTy || prevTy != underlyingType.Ty) { 6112 prevTy = underlyingType.Ty; 6113 underlyingType = underlyingType.getSingleStepDesugaredType(); 6114 } 6115 underlyingType.Quals.removeObjCLifetime(); 6116 } 6117 } 6118 6119 underlyingType.Quals.addObjCLifetime(lifetime); 6120 6121 if (NonObjCPointer) { 6122 StringRef name = attr.getName()->getName(); 6123 switch (lifetime) { 6124 case Qualifiers::OCL_None: 6125 case Qualifiers::OCL_ExplicitNone: 6126 break; 6127 case Qualifiers::OCL_Strong: name = "__strong"; break; 6128 case Qualifiers::OCL_Weak: name = "__weak"; break; 6129 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 6130 } 6131 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 6132 << TDS_ObjCObjOrBlock << type; 6133 } 6134 6135 // Don't actually add the __unsafe_unretained qualifier in non-ARC files, 6136 // because having both 'T' and '__unsafe_unretained T' exist in the type 6137 // system causes unfortunate widespread consistency problems. (For example, 6138 // they're not considered compatible types, and we mangle them identicially 6139 // as template arguments.) These problems are all individually fixable, 6140 // but it's easier to just not add the qualifier and instead sniff it out 6141 // in specific places using isObjCInertUnsafeUnretainedType(). 6142 // 6143 // Doing this does means we miss some trivial consistency checks that 6144 // would've triggered in ARC, but that's better than trying to solve all 6145 // the coexistence problems with __unsafe_unretained. 6146 if (!S.getLangOpts().ObjCAutoRefCount && 6147 lifetime == Qualifiers::OCL_ExplicitNone) { 6148 type = state.getAttributedType( 6149 createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr), 6150 type, type); 6151 return true; 6152 } 6153 6154 QualType origType = type; 6155 if (!NonObjCPointer) 6156 type = S.Context.getQualifiedType(underlyingType); 6157 6158 // If we have a valid source location for the attribute, use an 6159 // AttributedType instead. 6160 if (AttrLoc.isValid()) { 6161 type = state.getAttributedType(::new (S.Context) ObjCOwnershipAttr( 6162 attr.getRange(), S.Context, II, 6163 attr.getAttributeSpellingListIndex()), 6164 origType, type); 6165 } 6166 6167 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, 6168 unsigned diagnostic, QualType type) { 6169 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 6170 S.DelayedDiagnostics.add( 6171 sema::DelayedDiagnostic::makeForbiddenType( 6172 S.getSourceManager().getExpansionLoc(loc), 6173 diagnostic, type, /*ignored*/ 0)); 6174 } else { 6175 S.Diag(loc, diagnostic); 6176 } 6177 }; 6178 6179 // Sometimes, __weak isn't allowed. 6180 if (lifetime == Qualifiers::OCL_Weak && 6181 !S.getLangOpts().ObjCWeak && !NonObjCPointer) { 6182 6183 // Use a specialized diagnostic if the runtime just doesn't support them. 6184 unsigned diagnostic = 6185 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled 6186 : diag::err_arc_weak_no_runtime); 6187 6188 // In any case, delay the diagnostic until we know what we're parsing. 6189 diagnoseOrDelay(S, AttrLoc, diagnostic, type); 6190 6191 attr.setInvalid(); 6192 return true; 6193 } 6194 6195 // Forbid __weak for class objects marked as 6196 // objc_arc_weak_reference_unavailable 6197 if (lifetime == Qualifiers::OCL_Weak) { 6198 if (const ObjCObjectPointerType *ObjT = 6199 type->getAs<ObjCObjectPointerType>()) { 6200 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 6201 if (Class->isArcWeakrefUnavailable()) { 6202 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 6203 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 6204 diag::note_class_declared); 6205 } 6206 } 6207 } 6208 } 6209 6210 return true; 6211 } 6212 6213 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 6214 /// attribute on the specified type. Returns true to indicate that 6215 /// the attribute was handled, false to indicate that the type does 6216 /// not permit the attribute. 6217 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 6218 QualType &type) { 6219 Sema &S = state.getSema(); 6220 6221 // Delay if this isn't some kind of pointer. 6222 if (!type->isPointerType() && 6223 !type->isObjCObjectPointerType() && 6224 !type->isBlockPointerType()) 6225 return false; 6226 6227 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 6228 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 6229 attr.setInvalid(); 6230 return true; 6231 } 6232 6233 // Check the attribute arguments. 6234 if (!attr.isArgIdent(0)) { 6235 S.Diag(attr.getLoc(), diag::err_attribute_argument_type) 6236 << attr << AANT_ArgumentString; 6237 attr.setInvalid(); 6238 return true; 6239 } 6240 Qualifiers::GC GCAttr; 6241 if (attr.getNumArgs() > 1) { 6242 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr 6243 << 1; 6244 attr.setInvalid(); 6245 return true; 6246 } 6247 6248 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 6249 if (II->isStr("weak")) 6250 GCAttr = Qualifiers::Weak; 6251 else if (II->isStr("strong")) 6252 GCAttr = Qualifiers::Strong; 6253 else { 6254 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 6255 << attr.getName() << II; 6256 attr.setInvalid(); 6257 return true; 6258 } 6259 6260 QualType origType = type; 6261 type = S.Context.getObjCGCQualType(origType, GCAttr); 6262 6263 // Make an attributed type to preserve the source information. 6264 if (attr.getLoc().isValid()) 6265 type = state.getAttributedType( 6266 ::new (S.Context) ObjCGCAttr(attr.getRange(), S.Context, II, 6267 attr.getAttributeSpellingListIndex()), 6268 origType, type); 6269 6270 return true; 6271 } 6272 6273 namespace { 6274 /// A helper class to unwrap a type down to a function for the 6275 /// purposes of applying attributes there. 6276 /// 6277 /// Use: 6278 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 6279 /// if (unwrapped.isFunctionType()) { 6280 /// const FunctionType *fn = unwrapped.get(); 6281 /// // change fn somehow 6282 /// T = unwrapped.wrap(fn); 6283 /// } 6284 struct FunctionTypeUnwrapper { 6285 enum WrapKind { 6286 Desugar, 6287 Attributed, 6288 Parens, 6289 Pointer, 6290 BlockPointer, 6291 Reference, 6292 MemberPointer 6293 }; 6294 6295 QualType Original; 6296 const FunctionType *Fn; 6297 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 6298 6299 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 6300 while (true) { 6301 const Type *Ty = T.getTypePtr(); 6302 if (isa<FunctionType>(Ty)) { 6303 Fn = cast<FunctionType>(Ty); 6304 return; 6305 } else if (isa<ParenType>(Ty)) { 6306 T = cast<ParenType>(Ty)->getInnerType(); 6307 Stack.push_back(Parens); 6308 } else if (isa<PointerType>(Ty)) { 6309 T = cast<PointerType>(Ty)->getPointeeType(); 6310 Stack.push_back(Pointer); 6311 } else if (isa<BlockPointerType>(Ty)) { 6312 T = cast<BlockPointerType>(Ty)->getPointeeType(); 6313 Stack.push_back(BlockPointer); 6314 } else if (isa<MemberPointerType>(Ty)) { 6315 T = cast<MemberPointerType>(Ty)->getPointeeType(); 6316 Stack.push_back(MemberPointer); 6317 } else if (isa<ReferenceType>(Ty)) { 6318 T = cast<ReferenceType>(Ty)->getPointeeType(); 6319 Stack.push_back(Reference); 6320 } else if (isa<AttributedType>(Ty)) { 6321 T = cast<AttributedType>(Ty)->getEquivalentType(); 6322 Stack.push_back(Attributed); 6323 } else { 6324 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 6325 if (Ty == DTy) { 6326 Fn = nullptr; 6327 return; 6328 } 6329 6330 T = QualType(DTy, 0); 6331 Stack.push_back(Desugar); 6332 } 6333 } 6334 } 6335 6336 bool isFunctionType() const { return (Fn != nullptr); } 6337 const FunctionType *get() const { return Fn; } 6338 6339 QualType wrap(Sema &S, const FunctionType *New) { 6340 // If T wasn't modified from the unwrapped type, do nothing. 6341 if (New == get()) return Original; 6342 6343 Fn = New; 6344 return wrap(S.Context, Original, 0); 6345 } 6346 6347 private: 6348 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 6349 if (I == Stack.size()) 6350 return C.getQualifiedType(Fn, Old.getQualifiers()); 6351 6352 // Build up the inner type, applying the qualifiers from the old 6353 // type to the new type. 6354 SplitQualType SplitOld = Old.split(); 6355 6356 // As a special case, tail-recurse if there are no qualifiers. 6357 if (SplitOld.Quals.empty()) 6358 return wrap(C, SplitOld.Ty, I); 6359 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 6360 } 6361 6362 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 6363 if (I == Stack.size()) return QualType(Fn, 0); 6364 6365 switch (static_cast<WrapKind>(Stack[I++])) { 6366 case Desugar: 6367 // This is the point at which we potentially lose source 6368 // information. 6369 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 6370 6371 case Attributed: 6372 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); 6373 6374 case Parens: { 6375 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 6376 return C.getParenType(New); 6377 } 6378 6379 case Pointer: { 6380 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 6381 return C.getPointerType(New); 6382 } 6383 6384 case BlockPointer: { 6385 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 6386 return C.getBlockPointerType(New); 6387 } 6388 6389 case MemberPointer: { 6390 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 6391 QualType New = wrap(C, OldMPT->getPointeeType(), I); 6392 return C.getMemberPointerType(New, OldMPT->getClass()); 6393 } 6394 6395 case Reference: { 6396 const ReferenceType *OldRef = cast<ReferenceType>(Old); 6397 QualType New = wrap(C, OldRef->getPointeeType(), I); 6398 if (isa<LValueReferenceType>(OldRef)) 6399 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 6400 else 6401 return C.getRValueReferenceType(New); 6402 } 6403 } 6404 6405 llvm_unreachable("unknown wrapping kind"); 6406 } 6407 }; 6408 } // end anonymous namespace 6409 6410 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 6411 ParsedAttr &PAttr, QualType &Type) { 6412 Sema &S = State.getSema(); 6413 6414 Attr *A; 6415 switch (PAttr.getKind()) { 6416 default: llvm_unreachable("Unknown attribute kind"); 6417 case ParsedAttr::AT_Ptr32: 6418 A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr); 6419 break; 6420 case ParsedAttr::AT_Ptr64: 6421 A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr); 6422 break; 6423 case ParsedAttr::AT_SPtr: 6424 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr); 6425 break; 6426 case ParsedAttr::AT_UPtr: 6427 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr); 6428 break; 6429 } 6430 6431 attr::Kind NewAttrKind = A->getKind(); 6432 QualType Desugared = Type; 6433 const AttributedType *AT = dyn_cast<AttributedType>(Type); 6434 while (AT) { 6435 attr::Kind CurAttrKind = AT->getAttrKind(); 6436 6437 // You cannot specify duplicate type attributes, so if the attribute has 6438 // already been applied, flag it. 6439 if (NewAttrKind == CurAttrKind) { 6440 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) 6441 << PAttr.getName(); 6442 return true; 6443 } 6444 6445 // You cannot have both __sptr and __uptr on the same type, nor can you 6446 // have __ptr32 and __ptr64. 6447 if ((CurAttrKind == attr::Ptr32 && NewAttrKind == attr::Ptr64) || 6448 (CurAttrKind == attr::Ptr64 && NewAttrKind == attr::Ptr32)) { 6449 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) 6450 << "'__ptr32'" << "'__ptr64'"; 6451 return true; 6452 } else if ((CurAttrKind == attr::SPtr && NewAttrKind == attr::UPtr) || 6453 (CurAttrKind == attr::UPtr && NewAttrKind == attr::SPtr)) { 6454 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) 6455 << "'__sptr'" << "'__uptr'"; 6456 return true; 6457 } 6458 6459 Desugared = AT->getEquivalentType(); 6460 AT = dyn_cast<AttributedType>(Desugared); 6461 } 6462 6463 // Pointer type qualifiers can only operate on pointer types, but not 6464 // pointer-to-member types. 6465 // 6466 // FIXME: Should we really be disallowing this attribute if there is any 6467 // type sugar between it and the pointer (other than attributes)? Eg, this 6468 // disallows the attribute on a parenthesized pointer. 6469 // And if so, should we really allow *any* type attribute? 6470 if (!isa<PointerType>(Desugared)) { 6471 if (Type->isMemberPointerType()) 6472 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr; 6473 else 6474 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0; 6475 return true; 6476 } 6477 6478 Type = State.getAttributedType(A, Type, Type); 6479 return false; 6480 } 6481 6482 /// Map a nullability attribute kind to a nullability kind. 6483 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) { 6484 switch (kind) { 6485 case ParsedAttr::AT_TypeNonNull: 6486 return NullabilityKind::NonNull; 6487 6488 case ParsedAttr::AT_TypeNullable: 6489 return NullabilityKind::Nullable; 6490 6491 case ParsedAttr::AT_TypeNullUnspecified: 6492 return NullabilityKind::Unspecified; 6493 6494 default: 6495 llvm_unreachable("not a nullability attribute kind"); 6496 } 6497 } 6498 6499 /// Applies a nullability type specifier to the given type, if possible. 6500 /// 6501 /// \param state The type processing state. 6502 /// 6503 /// \param type The type to which the nullability specifier will be 6504 /// added. On success, this type will be updated appropriately. 6505 /// 6506 /// \param attr The attribute as written on the type. 6507 /// 6508 /// \param allowOnArrayType Whether to accept nullability specifiers on an 6509 /// array type (e.g., because it will decay to a pointer). 6510 /// 6511 /// \returns true if a problem has been diagnosed, false on success. 6512 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state, 6513 QualType &type, 6514 ParsedAttr &attr, 6515 bool allowOnArrayType) { 6516 Sema &S = state.getSema(); 6517 6518 NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind()); 6519 SourceLocation nullabilityLoc = attr.getLoc(); 6520 bool isContextSensitive = attr.isContextSensitiveKeywordAttribute(); 6521 6522 recordNullabilitySeen(S, nullabilityLoc); 6523 6524 // Check for existing nullability attributes on the type. 6525 QualType desugared = type; 6526 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { 6527 // Check whether there is already a null 6528 if (auto existingNullability = attributed->getImmediateNullability()) { 6529 // Duplicated nullability. 6530 if (nullability == *existingNullability) { 6531 S.Diag(nullabilityLoc, diag::warn_nullability_duplicate) 6532 << DiagNullabilityKind(nullability, isContextSensitive) 6533 << FixItHint::CreateRemoval(nullabilityLoc); 6534 6535 break; 6536 } 6537 6538 // Conflicting nullability. 6539 S.Diag(nullabilityLoc, diag::err_nullability_conflicting) 6540 << DiagNullabilityKind(nullability, isContextSensitive) 6541 << DiagNullabilityKind(*existingNullability, false); 6542 return true; 6543 } 6544 6545 desugared = attributed->getModifiedType(); 6546 } 6547 6548 // If there is already a different nullability specifier, complain. 6549 // This (unlike the code above) looks through typedefs that might 6550 // have nullability specifiers on them, which means we cannot 6551 // provide a useful Fix-It. 6552 if (auto existingNullability = desugared->getNullability(S.Context)) { 6553 if (nullability != *existingNullability) { 6554 S.Diag(nullabilityLoc, diag::err_nullability_conflicting) 6555 << DiagNullabilityKind(nullability, isContextSensitive) 6556 << DiagNullabilityKind(*existingNullability, false); 6557 6558 // Try to find the typedef with the existing nullability specifier. 6559 if (auto typedefType = desugared->getAs<TypedefType>()) { 6560 TypedefNameDecl *typedefDecl = typedefType->getDecl(); 6561 QualType underlyingType = typedefDecl->getUnderlyingType(); 6562 if (auto typedefNullability 6563 = AttributedType::stripOuterNullability(underlyingType)) { 6564 if (*typedefNullability == *existingNullability) { 6565 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here) 6566 << DiagNullabilityKind(*existingNullability, false); 6567 } 6568 } 6569 } 6570 6571 return true; 6572 } 6573 } 6574 6575 // If this definitely isn't a pointer type, reject the specifier. 6576 if (!desugared->canHaveNullability() && 6577 !(allowOnArrayType && desugared->isArrayType())) { 6578 S.Diag(nullabilityLoc, diag::err_nullability_nonpointer) 6579 << DiagNullabilityKind(nullability, isContextSensitive) << type; 6580 return true; 6581 } 6582 6583 // For the context-sensitive keywords/Objective-C property 6584 // attributes, require that the type be a single-level pointer. 6585 if (isContextSensitive) { 6586 // Make sure that the pointee isn't itself a pointer type. 6587 const Type *pointeeType; 6588 if (desugared->isArrayType()) 6589 pointeeType = desugared->getArrayElementTypeNoTypeQual(); 6590 else 6591 pointeeType = desugared->getPointeeType().getTypePtr(); 6592 6593 if (pointeeType->isAnyPointerType() || 6594 pointeeType->isObjCObjectPointerType() || 6595 pointeeType->isMemberPointerType()) { 6596 S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) 6597 << DiagNullabilityKind(nullability, true) 6598 << type; 6599 S.Diag(nullabilityLoc, diag::note_nullability_type_specifier) 6600 << DiagNullabilityKind(nullability, false) 6601 << type 6602 << FixItHint::CreateReplacement(nullabilityLoc, 6603 getNullabilitySpelling(nullability)); 6604 return true; 6605 } 6606 } 6607 6608 // Form the attributed type. 6609 type = state.getAttributedType( 6610 createNullabilityAttr(S.Context, attr, nullability), type, type); 6611 return false; 6612 } 6613 6614 /// Check the application of the Objective-C '__kindof' qualifier to 6615 /// the given type. 6616 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, 6617 ParsedAttr &attr) { 6618 Sema &S = state.getSema(); 6619 6620 if (isa<ObjCTypeParamType>(type)) { 6621 // Build the attributed type to record where __kindof occurred. 6622 type = state.getAttributedType( 6623 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type); 6624 return false; 6625 } 6626 6627 // Find out if it's an Objective-C object or object pointer type; 6628 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); 6629 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() 6630 : type->getAs<ObjCObjectType>(); 6631 6632 // If not, we can't apply __kindof. 6633 if (!objType) { 6634 // FIXME: Handle dependent types that aren't yet object types. 6635 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject) 6636 << type; 6637 return true; 6638 } 6639 6640 // Rebuild the "equivalent" type, which pushes __kindof down into 6641 // the object type. 6642 // There is no need to apply kindof on an unqualified id type. 6643 QualType equivType = S.Context.getObjCObjectType( 6644 objType->getBaseType(), objType->getTypeArgsAsWritten(), 6645 objType->getProtocols(), 6646 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); 6647 6648 // If we started with an object pointer type, rebuild it. 6649 if (ptrType) { 6650 equivType = S.Context.getObjCObjectPointerType(equivType); 6651 if (auto nullability = type->getNullability(S.Context)) { 6652 // We create a nullability attribute from the __kindof attribute. 6653 // Make sure that will make sense. 6654 assert(attr.getAttributeSpellingListIndex() == 0 && 6655 "multiple spellings for __kindof?"); 6656 Attr *A = createNullabilityAttr(S.Context, attr, *nullability); 6657 A->setImplicit(true); 6658 equivType = state.getAttributedType(A, equivType, equivType); 6659 } 6660 } 6661 6662 // Build the attributed type to record where __kindof occurred. 6663 type = state.getAttributedType( 6664 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType); 6665 return false; 6666 } 6667 6668 /// Distribute a nullability type attribute that cannot be applied to 6669 /// the type specifier to a pointer, block pointer, or member pointer 6670 /// declarator, complaining if necessary. 6671 /// 6672 /// \returns true if the nullability annotation was distributed, false 6673 /// otherwise. 6674 static bool distributeNullabilityTypeAttr(TypeProcessingState &state, 6675 QualType type, ParsedAttr &attr) { 6676 Declarator &declarator = state.getDeclarator(); 6677 6678 /// Attempt to move the attribute to the specified chunk. 6679 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { 6680 // If there is already a nullability attribute there, don't add 6681 // one. 6682 if (hasNullabilityAttr(chunk.getAttrs())) 6683 return false; 6684 6685 // Complain about the nullability qualifier being in the wrong 6686 // place. 6687 enum { 6688 PK_Pointer, 6689 PK_BlockPointer, 6690 PK_MemberPointer, 6691 PK_FunctionPointer, 6692 PK_MemberFunctionPointer, 6693 } pointerKind 6694 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer 6695 : PK_Pointer) 6696 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer 6697 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; 6698 6699 auto diag = state.getSema().Diag(attr.getLoc(), 6700 diag::warn_nullability_declspec) 6701 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), 6702 attr.isContextSensitiveKeywordAttribute()) 6703 << type 6704 << static_cast<unsigned>(pointerKind); 6705 6706 // FIXME: MemberPointer chunks don't carry the location of the *. 6707 if (chunk.Kind != DeclaratorChunk::MemberPointer) { 6708 diag << FixItHint::CreateRemoval(attr.getLoc()) 6709 << FixItHint::CreateInsertion( 6710 state.getSema().getPreprocessor() 6711 .getLocForEndOfToken(chunk.Loc), 6712 " " + attr.getName()->getName().str() + " "); 6713 } 6714 6715 moveAttrFromListToList(attr, state.getCurrentAttributes(), 6716 chunk.getAttrs()); 6717 return true; 6718 }; 6719 6720 // Move it to the outermost pointer, member pointer, or block 6721 // pointer declarator. 6722 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 6723 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 6724 switch (chunk.Kind) { 6725 case DeclaratorChunk::Pointer: 6726 case DeclaratorChunk::BlockPointer: 6727 case DeclaratorChunk::MemberPointer: 6728 return moveToChunk(chunk, false); 6729 6730 case DeclaratorChunk::Paren: 6731 case DeclaratorChunk::Array: 6732 continue; 6733 6734 case DeclaratorChunk::Function: 6735 // Try to move past the return type to a function/block/member 6736 // function pointer. 6737 if (DeclaratorChunk *dest = maybeMovePastReturnType( 6738 declarator, i, 6739 /*onlyBlockPointers=*/false)) { 6740 return moveToChunk(*dest, true); 6741 } 6742 6743 return false; 6744 6745 // Don't walk through these. 6746 case DeclaratorChunk::Reference: 6747 case DeclaratorChunk::Pipe: 6748 return false; 6749 } 6750 } 6751 6752 return false; 6753 } 6754 6755 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { 6756 assert(!Attr.isInvalid()); 6757 switch (Attr.getKind()) { 6758 default: 6759 llvm_unreachable("not a calling convention attribute"); 6760 case ParsedAttr::AT_CDecl: 6761 return createSimpleAttr<CDeclAttr>(Ctx, Attr); 6762 case ParsedAttr::AT_FastCall: 6763 return createSimpleAttr<FastCallAttr>(Ctx, Attr); 6764 case ParsedAttr::AT_StdCall: 6765 return createSimpleAttr<StdCallAttr>(Ctx, Attr); 6766 case ParsedAttr::AT_ThisCall: 6767 return createSimpleAttr<ThisCallAttr>(Ctx, Attr); 6768 case ParsedAttr::AT_RegCall: 6769 return createSimpleAttr<RegCallAttr>(Ctx, Attr); 6770 case ParsedAttr::AT_Pascal: 6771 return createSimpleAttr<PascalAttr>(Ctx, Attr); 6772 case ParsedAttr::AT_SwiftCall: 6773 return createSimpleAttr<SwiftCallAttr>(Ctx, Attr); 6774 case ParsedAttr::AT_VectorCall: 6775 return createSimpleAttr<VectorCallAttr>(Ctx, Attr); 6776 case ParsedAttr::AT_AArch64VectorPcs: 6777 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr); 6778 case ParsedAttr::AT_Pcs: { 6779 // The attribute may have had a fixit applied where we treated an 6780 // identifier as a string literal. The contents of the string are valid, 6781 // but the form may not be. 6782 StringRef Str; 6783 if (Attr.isArgExpr(0)) 6784 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); 6785 else 6786 Str = Attr.getArgAsIdent(0)->Ident->getName(); 6787 PcsAttr::PCSType Type; 6788 if (!PcsAttr::ConvertStrToPCSType(Str, Type)) 6789 llvm_unreachable("already validated the attribute"); 6790 return ::new (Ctx) PcsAttr(Attr.getRange(), Ctx, Type, 6791 Attr.getAttributeSpellingListIndex()); 6792 } 6793 case ParsedAttr::AT_IntelOclBicc: 6794 return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr); 6795 case ParsedAttr::AT_MSABI: 6796 return createSimpleAttr<MSABIAttr>(Ctx, Attr); 6797 case ParsedAttr::AT_SysVABI: 6798 return createSimpleAttr<SysVABIAttr>(Ctx, Attr); 6799 case ParsedAttr::AT_PreserveMost: 6800 return createSimpleAttr<PreserveMostAttr>(Ctx, Attr); 6801 case ParsedAttr::AT_PreserveAll: 6802 return createSimpleAttr<PreserveAllAttr>(Ctx, Attr); 6803 } 6804 llvm_unreachable("unexpected attribute kind!"); 6805 } 6806 6807 /// Process an individual function attribute. Returns true to 6808 /// indicate that the attribute was handled, false if it wasn't. 6809 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, 6810 QualType &type) { 6811 Sema &S = state.getSema(); 6812 6813 FunctionTypeUnwrapper unwrapped(S, type); 6814 6815 if (attr.getKind() == ParsedAttr::AT_NoReturn) { 6816 if (S.CheckAttrNoArgs(attr)) 6817 return true; 6818 6819 // Delay if this is not a function type. 6820 if (!unwrapped.isFunctionType()) 6821 return false; 6822 6823 // Otherwise we can process right away. 6824 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 6825 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6826 return true; 6827 } 6828 6829 // ns_returns_retained is not always a type attribute, but if we got 6830 // here, we're treating it as one right now. 6831 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) { 6832 if (attr.getNumArgs()) return true; 6833 6834 // Delay if this is not a function type. 6835 if (!unwrapped.isFunctionType()) 6836 return false; 6837 6838 // Check whether the return type is reasonable. 6839 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(), 6840 unwrapped.get()->getReturnType())) 6841 return true; 6842 6843 // Only actually change the underlying type in ARC builds. 6844 QualType origType = type; 6845 if (state.getSema().getLangOpts().ObjCAutoRefCount) { 6846 FunctionType::ExtInfo EI 6847 = unwrapped.get()->getExtInfo().withProducesResult(true); 6848 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6849 } 6850 type = state.getAttributedType( 6851 createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr), 6852 origType, type); 6853 return true; 6854 } 6855 6856 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) { 6857 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) 6858 return true; 6859 6860 // Delay if this is not a function type. 6861 if (!unwrapped.isFunctionType()) 6862 return false; 6863 6864 FunctionType::ExtInfo EI = 6865 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); 6866 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6867 return true; 6868 } 6869 6870 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) { 6871 if (!S.getLangOpts().CFProtectionBranch) { 6872 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored); 6873 attr.setInvalid(); 6874 return true; 6875 } 6876 6877 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) 6878 return true; 6879 6880 // If this is not a function type, warning will be asserted by subject 6881 // check. 6882 if (!unwrapped.isFunctionType()) 6883 return true; 6884 6885 FunctionType::ExtInfo EI = 6886 unwrapped.get()->getExtInfo().withNoCfCheck(true); 6887 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6888 return true; 6889 } 6890 6891 if (attr.getKind() == ParsedAttr::AT_Regparm) { 6892 unsigned value; 6893 if (S.CheckRegparmAttr(attr, value)) 6894 return true; 6895 6896 // Delay if this is not a function type. 6897 if (!unwrapped.isFunctionType()) 6898 return false; 6899 6900 // Diagnose regparm with fastcall. 6901 const FunctionType *fn = unwrapped.get(); 6902 CallingConv CC = fn->getCallConv(); 6903 if (CC == CC_X86FastCall) { 6904 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6905 << FunctionType::getNameForCallConv(CC) 6906 << "regparm"; 6907 attr.setInvalid(); 6908 return true; 6909 } 6910 6911 FunctionType::ExtInfo EI = 6912 unwrapped.get()->getExtInfo().withRegParm(value); 6913 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6914 return true; 6915 } 6916 6917 // Delay if the type didn't work out to a function. 6918 if (!unwrapped.isFunctionType()) return false; 6919 6920 // Otherwise, a calling convention. 6921 CallingConv CC; 6922 if (S.CheckCallingConvAttr(attr, CC)) 6923 return true; 6924 6925 const FunctionType *fn = unwrapped.get(); 6926 CallingConv CCOld = fn->getCallConv(); 6927 Attr *CCAttr = getCCTypeAttr(S.Context, attr); 6928 6929 if (CCOld != CC) { 6930 // Error out on when there's already an attribute on the type 6931 // and the CCs don't match. 6932 if (S.getCallingConvAttributedType(type)) { 6933 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6934 << FunctionType::getNameForCallConv(CC) 6935 << FunctionType::getNameForCallConv(CCOld); 6936 attr.setInvalid(); 6937 return true; 6938 } 6939 } 6940 6941 // Diagnose use of variadic functions with calling conventions that 6942 // don't support them (e.g. because they're callee-cleanup). 6943 // We delay warning about this on unprototyped function declarations 6944 // until after redeclaration checking, just in case we pick up a 6945 // prototype that way. And apparently we also "delay" warning about 6946 // unprototyped function types in general, despite not necessarily having 6947 // much ability to diagnose it later. 6948 if (!supportsVariadicCall(CC)) { 6949 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); 6950 if (FnP && FnP->isVariadic()) { 6951 // stdcall and fastcall are ignored with a warning for GCC and MS 6952 // compatibility. 6953 if (CC == CC_X86StdCall || CC == CC_X86FastCall) 6954 return S.Diag(attr.getLoc(), diag::warn_cconv_ignored) 6955 << FunctionType::getNameForCallConv(CC) 6956 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction; 6957 6958 attr.setInvalid(); 6959 return S.Diag(attr.getLoc(), diag::err_cconv_varargs) 6960 << FunctionType::getNameForCallConv(CC); 6961 } 6962 } 6963 6964 // Also diagnose fastcall with regparm. 6965 if (CC == CC_X86FastCall && fn->getHasRegParm()) { 6966 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6967 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); 6968 attr.setInvalid(); 6969 return true; 6970 } 6971 6972 // Modify the CC from the wrapped function type, wrap it all back, and then 6973 // wrap the whole thing in an AttributedType as written. The modified type 6974 // might have a different CC if we ignored the attribute. 6975 QualType Equivalent; 6976 if (CCOld == CC) { 6977 Equivalent = type; 6978 } else { 6979 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 6980 Equivalent = 6981 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6982 } 6983 type = state.getAttributedType(CCAttr, type, Equivalent); 6984 return true; 6985 } 6986 6987 bool Sema::hasExplicitCallingConv(QualType &T) { 6988 QualType R = T.IgnoreParens(); 6989 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) { 6990 if (AT->isCallingConv()) 6991 return true; 6992 R = AT->getModifiedType().IgnoreParens(); 6993 } 6994 return false; 6995 } 6996 6997 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 6998 SourceLocation Loc) { 6999 FunctionTypeUnwrapper Unwrapped(*this, T); 7000 const FunctionType *FT = Unwrapped.get(); 7001 bool IsVariadic = (isa<FunctionProtoType>(FT) && 7002 cast<FunctionProtoType>(FT)->isVariadic()); 7003 CallingConv CurCC = FT->getCallConv(); 7004 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); 7005 7006 if (CurCC == ToCC) 7007 return; 7008 7009 // MS compiler ignores explicit calling convention attributes on structors. We 7010 // should do the same. 7011 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { 7012 // Issue a warning on ignored calling convention -- except of __stdcall. 7013 // Again, this is what MS compiler does. 7014 if (CurCC != CC_X86StdCall) 7015 Diag(Loc, diag::warn_cconv_ignored) 7016 << FunctionType::getNameForCallConv(CurCC) 7017 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor; 7018 // Default adjustment. 7019 } else { 7020 // Only adjust types with the default convention. For example, on Windows 7021 // we should adjust a __cdecl type to __thiscall for instance methods, and a 7022 // __thiscall type to __cdecl for static methods. 7023 CallingConv DefaultCC = 7024 Context.getDefaultCallingConvention(IsVariadic, IsStatic); 7025 7026 if (CurCC != DefaultCC || DefaultCC == ToCC) 7027 return; 7028 7029 if (hasExplicitCallingConv(T)) 7030 return; 7031 } 7032 7033 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); 7034 QualType Wrapped = Unwrapped.wrap(*this, FT); 7035 T = Context.getAdjustedType(T, Wrapped); 7036 } 7037 7038 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 7039 /// and float scalars, although arrays, pointers, and function return values are 7040 /// allowed in conjunction with this construct. Aggregates with this attribute 7041 /// are invalid, even if they are of the same size as a corresponding scalar. 7042 /// The raw attribute should contain precisely 1 argument, the vector size for 7043 /// the variable, measured in bytes. If curType and rawAttr are well formed, 7044 /// this routine will return a new vector type. 7045 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, 7046 Sema &S) { 7047 // Check the attribute arguments. 7048 if (Attr.getNumArgs() != 1) { 7049 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 7050 << 1; 7051 Attr.setInvalid(); 7052 return; 7053 } 7054 7055 Expr *SizeExpr; 7056 // Special case where the argument is a template id. 7057 if (Attr.isArgIdent(0)) { 7058 CXXScopeSpec SS; 7059 SourceLocation TemplateKWLoc; 7060 UnqualifiedId Id; 7061 Id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); 7062 7063 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 7064 Id, /*HasTrailingLParen=*/false, 7065 /*IsAddressOfOperand=*/false); 7066 7067 if (Size.isInvalid()) 7068 return; 7069 SizeExpr = Size.get(); 7070 } else { 7071 SizeExpr = Attr.getArgAsExpr(0); 7072 } 7073 7074 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc()); 7075 if (!T.isNull()) 7076 CurType = T; 7077 else 7078 Attr.setInvalid(); 7079 } 7080 7081 /// Process the OpenCL-like ext_vector_type attribute when it occurs on 7082 /// a type. 7083 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, 7084 Sema &S) { 7085 // check the attribute arguments. 7086 if (Attr.getNumArgs() != 1) { 7087 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 7088 << 1; 7089 return; 7090 } 7091 7092 Expr *sizeExpr; 7093 7094 // Special case where the argument is a template id. 7095 if (Attr.isArgIdent(0)) { 7096 CXXScopeSpec SS; 7097 SourceLocation TemplateKWLoc; 7098 UnqualifiedId id; 7099 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); 7100 7101 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 7102 id, /*HasTrailingLParen=*/false, 7103 /*IsAddressOfOperand=*/false); 7104 if (Size.isInvalid()) 7105 return; 7106 7107 sizeExpr = Size.get(); 7108 } else { 7109 sizeExpr = Attr.getArgAsExpr(0); 7110 } 7111 7112 // Create the vector type. 7113 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 7114 if (!T.isNull()) 7115 CurType = T; 7116 } 7117 7118 static bool isPermittedNeonBaseType(QualType &Ty, 7119 VectorType::VectorKind VecKind, Sema &S) { 7120 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 7121 if (!BTy) 7122 return false; 7123 7124 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 7125 7126 // Signed poly is mathematically wrong, but has been baked into some ABIs by 7127 // now. 7128 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || 7129 Triple.getArch() == llvm::Triple::aarch64_be; 7130 if (VecKind == VectorType::NeonPolyVector) { 7131 if (IsPolyUnsigned) { 7132 // AArch64 polynomial vectors are unsigned and support poly64. 7133 return BTy->getKind() == BuiltinType::UChar || 7134 BTy->getKind() == BuiltinType::UShort || 7135 BTy->getKind() == BuiltinType::ULong || 7136 BTy->getKind() == BuiltinType::ULongLong; 7137 } else { 7138 // AArch32 polynomial vector are signed. 7139 return BTy->getKind() == BuiltinType::SChar || 7140 BTy->getKind() == BuiltinType::Short; 7141 } 7142 } 7143 7144 // Non-polynomial vector types: the usual suspects are allowed, as well as 7145 // float64_t on AArch64. 7146 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 || 7147 Triple.getArch() == llvm::Triple::aarch64_be; 7148 7149 if (Is64Bit && BTy->getKind() == BuiltinType::Double) 7150 return true; 7151 7152 return BTy->getKind() == BuiltinType::SChar || 7153 BTy->getKind() == BuiltinType::UChar || 7154 BTy->getKind() == BuiltinType::Short || 7155 BTy->getKind() == BuiltinType::UShort || 7156 BTy->getKind() == BuiltinType::Int || 7157 BTy->getKind() == BuiltinType::UInt || 7158 BTy->getKind() == BuiltinType::Long || 7159 BTy->getKind() == BuiltinType::ULong || 7160 BTy->getKind() == BuiltinType::LongLong || 7161 BTy->getKind() == BuiltinType::ULongLong || 7162 BTy->getKind() == BuiltinType::Float || 7163 BTy->getKind() == BuiltinType::Half; 7164 } 7165 7166 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 7167 /// "neon_polyvector_type" attributes are used to create vector types that 7168 /// are mangled according to ARM's ABI. Otherwise, these types are identical 7169 /// to those created with the "vector_size" attribute. Unlike "vector_size" 7170 /// the argument to these Neon attributes is the number of vector elements, 7171 /// not the vector size in bytes. The vector width and element type must 7172 /// match one of the standard Neon vector types. 7173 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, 7174 Sema &S, VectorType::VectorKind VecKind) { 7175 // Target must have NEON 7176 if (!S.Context.getTargetInfo().hasFeature("neon")) { 7177 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr; 7178 Attr.setInvalid(); 7179 return; 7180 } 7181 // Check the attribute arguments. 7182 if (Attr.getNumArgs() != 1) { 7183 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr 7184 << 1; 7185 Attr.setInvalid(); 7186 return; 7187 } 7188 // The number of elements must be an ICE. 7189 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 7190 llvm::APSInt numEltsInt(32); 7191 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 7192 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 7193 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 7194 << Attr << AANT_ArgumentIntegerConstant 7195 << numEltsExpr->getSourceRange(); 7196 Attr.setInvalid(); 7197 return; 7198 } 7199 // Only certain element types are supported for Neon vectors. 7200 if (!isPermittedNeonBaseType(CurType, VecKind, S)) { 7201 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 7202 Attr.setInvalid(); 7203 return; 7204 } 7205 7206 // The total size of the vector must be 64 or 128 bits. 7207 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 7208 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 7209 unsigned vecSize = typeSize * numElts; 7210 if (vecSize != 64 && vecSize != 128) { 7211 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 7212 Attr.setInvalid(); 7213 return; 7214 } 7215 7216 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 7217 } 7218 7219 /// Handle OpenCL Access Qualifier Attribute. 7220 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, 7221 Sema &S) { 7222 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. 7223 if (!(CurType->isImageType() || CurType->isPipeType())) { 7224 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); 7225 Attr.setInvalid(); 7226 return; 7227 } 7228 7229 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { 7230 QualType BaseTy = TypedefTy->desugar(); 7231 7232 std::string PrevAccessQual; 7233 if (BaseTy->isPipeType()) { 7234 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) { 7235 OpenCLAccessAttr *Attr = 7236 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>(); 7237 PrevAccessQual = Attr->getSpelling(); 7238 } else { 7239 PrevAccessQual = "read_only"; 7240 } 7241 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) { 7242 7243 switch (ImgType->getKind()) { 7244 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7245 case BuiltinType::Id: \ 7246 PrevAccessQual = #Access; \ 7247 break; 7248 #include "clang/Basic/OpenCLImageTypes.def" 7249 default: 7250 llvm_unreachable("Unable to find corresponding image type."); 7251 } 7252 } else { 7253 llvm_unreachable("unexpected type"); 7254 } 7255 StringRef AttrName = Attr.getName()->getName(); 7256 if (PrevAccessQual == AttrName.ltrim("_")) { 7257 // Duplicated qualifiers 7258 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec) 7259 << AttrName << Attr.getRange(); 7260 } else { 7261 // Contradicting qualifiers 7262 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); 7263 } 7264 7265 S.Diag(TypedefTy->getDecl()->getBeginLoc(), 7266 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; 7267 } else if (CurType->isPipeType()) { 7268 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { 7269 QualType ElemType = CurType->getAs<PipeType>()->getElementType(); 7270 CurType = S.Context.getWritePipeType(ElemType); 7271 } 7272 } 7273 } 7274 7275 static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State, 7276 QualType &T, TypeAttrLocation TAL) { 7277 Declarator &D = State.getDeclarator(); 7278 7279 // Handle the cases where address space should not be deduced. 7280 // 7281 // The pointee type of a pointer type is always deduced since a pointer always 7282 // points to some memory location which should has an address space. 7283 // 7284 // There are situations that at the point of certain declarations, the address 7285 // space may be unknown and better to be left as default. For example, when 7286 // defining a typedef or struct type, they are not associated with any 7287 // specific address space. Later on, they may be used with any address space 7288 // to declare a variable. 7289 // 7290 // The return value of a function is r-value, therefore should not have 7291 // address space. 7292 // 7293 // The void type does not occupy memory, therefore should not have address 7294 // space, except when it is used as a pointee type. 7295 // 7296 // Since LLVM assumes function type is in default address space, it should not 7297 // have address space. 7298 auto ChunkIndex = State.getCurrentChunkIndex(); 7299 bool IsPointee = 7300 ChunkIndex > 0 && 7301 (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer || 7302 D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer || 7303 D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Reference); 7304 bool IsFuncReturnType = 7305 ChunkIndex > 0 && 7306 D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function; 7307 bool IsFuncType = 7308 ChunkIndex < D.getNumTypeObjects() && 7309 D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function; 7310 if ( // Do not deduce addr space for function return type and function type, 7311 // otherwise it will fail some sema check. 7312 IsFuncReturnType || IsFuncType || 7313 // Do not deduce addr space for member types of struct, except the pointee 7314 // type of a pointer member type. 7315 (D.getContext() == DeclaratorContext::MemberContext && !IsPointee) || 7316 // Do not deduce addr space for types used to define a typedef and the 7317 // typedef itself, except the pointee type of a pointer type which is used 7318 // to define the typedef. 7319 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef && 7320 !IsPointee) || 7321 // Do not deduce addr space of the void type, e.g. in f(void), otherwise 7322 // it will fail some sema check. 7323 (T->isVoidType() && !IsPointee) || 7324 // Do not deduce addr spaces for dependent types because they might end 7325 // up instantiating to a type with an explicit address space qualifier. 7326 T->isDependentType() || 7327 // Do not deduce addr space of decltype because it will be taken from 7328 // its argument. 7329 T->isDecltypeType()) 7330 return; 7331 7332 LangAS ImpAddr = LangAS::Default; 7333 // Put OpenCL automatic variable in private address space. 7334 // OpenCL v1.2 s6.5: 7335 // The default address space name for arguments to a function in a 7336 // program, or local variables of a function is __private. All function 7337 // arguments shall be in the __private address space. 7338 if (State.getSema().getLangOpts().OpenCLVersion <= 120 && 7339 !State.getSema().getLangOpts().OpenCLCPlusPlus) { 7340 ImpAddr = LangAS::opencl_private; 7341 } else { 7342 // If address space is not set, OpenCL 2.0 defines non private default 7343 // address spaces for some cases: 7344 // OpenCL 2.0, section 6.5: 7345 // The address space for a variable at program scope or a static variable 7346 // inside a function can either be __global or __constant, but defaults to 7347 // __global if not specified. 7348 // (...) 7349 // Pointers that are declared without pointing to a named address space 7350 // point to the generic address space. 7351 if (IsPointee) { 7352 ImpAddr = LangAS::opencl_generic; 7353 } else { 7354 if (D.getContext() == DeclaratorContext::TemplateArgContext) { 7355 // Do not deduce address space for non-pointee type in template arg. 7356 } else if (D.getContext() == DeclaratorContext::FileContext) { 7357 ImpAddr = LangAS::opencl_global; 7358 } else { 7359 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || 7360 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) { 7361 ImpAddr = LangAS::opencl_global; 7362 } else { 7363 ImpAddr = LangAS::opencl_private; 7364 } 7365 } 7366 } 7367 } 7368 T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr); 7369 } 7370 7371 static void HandleLifetimeBoundAttr(TypeProcessingState &State, 7372 QualType &CurType, 7373 ParsedAttr &Attr) { 7374 if (State.getDeclarator().isDeclarationOfFunction()) { 7375 CurType = State.getAttributedType( 7376 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr), 7377 CurType, CurType); 7378 } else { 7379 Attr.diagnoseAppertainsTo(State.getSema(), nullptr); 7380 } 7381 } 7382 7383 7384 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 7385 TypeAttrLocation TAL, 7386 ParsedAttributesView &attrs) { 7387 // Scan through and apply attributes to this type where it makes sense. Some 7388 // attributes (such as __address_space__, __vector_size__, etc) apply to the 7389 // type, but others can be present in the type specifiers even though they 7390 // apply to the decl. Here we apply type attributes and ignore the rest. 7391 7392 // This loop modifies the list pretty frequently, but we still need to make 7393 // sure we visit every element once. Copy the attributes list, and iterate 7394 // over that. 7395 ParsedAttributesView AttrsCopy{attrs}; 7396 7397 state.setParsedNoDeref(false); 7398 7399 for (ParsedAttr &attr : AttrsCopy) { 7400 7401 // Skip attributes that were marked to be invalid. 7402 if (attr.isInvalid()) 7403 continue; 7404 7405 if (attr.isCXX11Attribute()) { 7406 // [[gnu::...]] attributes are treated as declaration attributes, so may 7407 // not appertain to a DeclaratorChunk. If we handle them as type 7408 // attributes, accept them in that position and diagnose the GCC 7409 // incompatibility. 7410 if (attr.isGNUScope()) { 7411 bool IsTypeAttr = attr.isTypeAttr(); 7412 if (TAL == TAL_DeclChunk) { 7413 state.getSema().Diag(attr.getLoc(), 7414 IsTypeAttr 7415 ? diag::warn_gcc_ignores_type_attr 7416 : diag::warn_cxx11_gnu_attribute_on_type) 7417 << attr.getName(); 7418 if (!IsTypeAttr) 7419 continue; 7420 } 7421 } else if (TAL != TAL_DeclChunk && 7422 attr.getKind() != ParsedAttr::AT_AddressSpace) { 7423 // Otherwise, only consider type processing for a C++11 attribute if 7424 // it's actually been applied to a type. 7425 // We also allow C++11 address_space attributes to pass through. 7426 continue; 7427 } 7428 } 7429 7430 // If this is an attribute we can handle, do so now, 7431 // otherwise, add it to the FnAttrs list for rechaining. 7432 switch (attr.getKind()) { 7433 default: 7434 // A C++11 attribute on a declarator chunk must appertain to a type. 7435 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { 7436 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 7437 << attr; 7438 attr.setUsedAsTypeAttr(); 7439 } 7440 break; 7441 7442 case ParsedAttr::UnknownAttribute: 7443 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 7444 state.getSema().Diag(attr.getLoc(), 7445 diag::warn_unknown_attribute_ignored) 7446 << attr.getName(); 7447 break; 7448 7449 case ParsedAttr::IgnoredAttribute: 7450 break; 7451 7452 case ParsedAttr::AT_MayAlias: 7453 // FIXME: This attribute needs to actually be handled, but if we ignore 7454 // it it breaks large amounts of Linux software. 7455 attr.setUsedAsTypeAttr(); 7456 break; 7457 case ParsedAttr::AT_OpenCLPrivateAddressSpace: 7458 case ParsedAttr::AT_OpenCLGlobalAddressSpace: 7459 case ParsedAttr::AT_OpenCLLocalAddressSpace: 7460 case ParsedAttr::AT_OpenCLConstantAddressSpace: 7461 case ParsedAttr::AT_OpenCLGenericAddressSpace: 7462 case ParsedAttr::AT_AddressSpace: 7463 HandleAddressSpaceTypeAttribute(type, attr, state); 7464 attr.setUsedAsTypeAttr(); 7465 break; 7466 OBJC_POINTER_TYPE_ATTRS_CASELIST: 7467 if (!handleObjCPointerTypeAttr(state, attr, type)) 7468 distributeObjCPointerTypeAttr(state, attr, type); 7469 attr.setUsedAsTypeAttr(); 7470 break; 7471 case ParsedAttr::AT_VectorSize: 7472 HandleVectorSizeAttr(type, attr, state.getSema()); 7473 attr.setUsedAsTypeAttr(); 7474 break; 7475 case ParsedAttr::AT_ExtVectorType: 7476 HandleExtVectorTypeAttr(type, attr, state.getSema()); 7477 attr.setUsedAsTypeAttr(); 7478 break; 7479 case ParsedAttr::AT_NeonVectorType: 7480 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 7481 VectorType::NeonVector); 7482 attr.setUsedAsTypeAttr(); 7483 break; 7484 case ParsedAttr::AT_NeonPolyVectorType: 7485 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 7486 VectorType::NeonPolyVector); 7487 attr.setUsedAsTypeAttr(); 7488 break; 7489 case ParsedAttr::AT_OpenCLAccess: 7490 HandleOpenCLAccessAttr(type, attr, state.getSema()); 7491 attr.setUsedAsTypeAttr(); 7492 break; 7493 case ParsedAttr::AT_LifetimeBound: 7494 if (TAL == TAL_DeclChunk) 7495 HandleLifetimeBoundAttr(state, type, attr); 7496 break; 7497 7498 case ParsedAttr::AT_NoDeref: { 7499 ASTContext &Ctx = state.getSema().Context; 7500 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr), 7501 type, type); 7502 attr.setUsedAsTypeAttr(); 7503 state.setParsedNoDeref(true); 7504 break; 7505 } 7506 7507 MS_TYPE_ATTRS_CASELIST: 7508 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 7509 attr.setUsedAsTypeAttr(); 7510 break; 7511 7512 7513 NULLABILITY_TYPE_ATTRS_CASELIST: 7514 // Either add nullability here or try to distribute it. We 7515 // don't want to distribute the nullability specifier past any 7516 // dependent type, because that complicates the user model. 7517 if (type->canHaveNullability() || type->isDependentType() || 7518 type->isArrayType() || 7519 !distributeNullabilityTypeAttr(state, type, attr)) { 7520 unsigned endIndex; 7521 if (TAL == TAL_DeclChunk) 7522 endIndex = state.getCurrentChunkIndex(); 7523 else 7524 endIndex = state.getDeclarator().getNumTypeObjects(); 7525 bool allowOnArrayType = 7526 state.getDeclarator().isPrototypeContext() && 7527 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); 7528 if (checkNullabilityTypeSpecifier( 7529 state, 7530 type, 7531 attr, 7532 allowOnArrayType)) { 7533 attr.setInvalid(); 7534 } 7535 7536 attr.setUsedAsTypeAttr(); 7537 } 7538 break; 7539 7540 case ParsedAttr::AT_ObjCKindOf: 7541 // '__kindof' must be part of the decl-specifiers. 7542 switch (TAL) { 7543 case TAL_DeclSpec: 7544 break; 7545 7546 case TAL_DeclChunk: 7547 case TAL_DeclName: 7548 state.getSema().Diag(attr.getLoc(), 7549 diag::err_objc_kindof_wrong_position) 7550 << FixItHint::CreateRemoval(attr.getLoc()) 7551 << FixItHint::CreateInsertion( 7552 state.getDeclarator().getDeclSpec().getBeginLoc(), 7553 "__kindof "); 7554 break; 7555 } 7556 7557 // Apply it regardless. 7558 if (checkObjCKindOfType(state, type, attr)) 7559 attr.setInvalid(); 7560 break; 7561 7562 FUNCTION_TYPE_ATTRS_CASELIST: 7563 attr.setUsedAsTypeAttr(); 7564 7565 // Never process function type attributes as part of the 7566 // declaration-specifiers. 7567 if (TAL == TAL_DeclSpec) 7568 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 7569 7570 // Otherwise, handle the possible delays. 7571 else if (!handleFunctionTypeAttr(state, attr, type)) 7572 distributeFunctionTypeAttr(state, attr, type); 7573 break; 7574 } 7575 } 7576 7577 if (!state.getSema().getLangOpts().OpenCL || 7578 type.getAddressSpace() != LangAS::Default) 7579 return; 7580 7581 deduceOpenCLImplicitAddrSpace(state, type, TAL); 7582 } 7583 7584 void Sema::completeExprArrayBound(Expr *E) { 7585 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 7586 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 7587 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { 7588 auto *Def = Var->getDefinition(); 7589 if (!Def) { 7590 SourceLocation PointOfInstantiation = E->getExprLoc(); 7591 InstantiateVariableDefinition(PointOfInstantiation, Var); 7592 Def = Var->getDefinition(); 7593 7594 // If we don't already have a point of instantiation, and we managed 7595 // to instantiate a definition, this is the point of instantiation. 7596 // Otherwise, we don't request an end-of-TU instantiation, so this is 7597 // not a point of instantiation. 7598 // FIXME: Is this really the right behavior? 7599 if (Var->getPointOfInstantiation().isInvalid() && Def) { 7600 assert(Var->getTemplateSpecializationKind() == 7601 TSK_ImplicitInstantiation && 7602 "explicit instantiation with no point of instantiation"); 7603 Var->setTemplateSpecializationKind( 7604 Var->getTemplateSpecializationKind(), PointOfInstantiation); 7605 } 7606 } 7607 7608 // Update the type to the definition's type both here and within the 7609 // expression. 7610 if (Def) { 7611 DRE->setDecl(Def); 7612 QualType T = Def->getType(); 7613 DRE->setType(T); 7614 // FIXME: Update the type on all intervening expressions. 7615 E->setType(T); 7616 } 7617 7618 // We still go on to try to complete the type independently, as it 7619 // may also require instantiations or diagnostics if it remains 7620 // incomplete. 7621 } 7622 } 7623 } 7624 } 7625 7626 /// Ensure that the type of the given expression is complete. 7627 /// 7628 /// This routine checks whether the expression \p E has a complete type. If the 7629 /// expression refers to an instantiable construct, that instantiation is 7630 /// performed as needed to complete its type. Furthermore 7631 /// Sema::RequireCompleteType is called for the expression's type (or in the 7632 /// case of a reference type, the referred-to type). 7633 /// 7634 /// \param E The expression whose type is required to be complete. 7635 /// \param Diagnoser The object that will emit a diagnostic if the type is 7636 /// incomplete. 7637 /// 7638 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 7639 /// otherwise. 7640 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) { 7641 QualType T = E->getType(); 7642 7643 // Incomplete array types may be completed by the initializer attached to 7644 // their definitions. For static data members of class templates and for 7645 // variable templates, we need to instantiate the definition to get this 7646 // initializer and complete the type. 7647 if (T->isIncompleteArrayType()) { 7648 completeExprArrayBound(E); 7649 T = E->getType(); 7650 } 7651 7652 // FIXME: Are there other cases which require instantiating something other 7653 // than the type to complete the type of an expression? 7654 7655 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 7656 } 7657 7658 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 7659 BoundTypeDiagnoser<> Diagnoser(DiagID); 7660 return RequireCompleteExprType(E, Diagnoser); 7661 } 7662 7663 /// Ensure that the type T is a complete type. 7664 /// 7665 /// This routine checks whether the type @p T is complete in any 7666 /// context where a complete type is required. If @p T is a complete 7667 /// type, returns false. If @p T is a class template specialization, 7668 /// this routine then attempts to perform class template 7669 /// instantiation. If instantiation fails, or if @p T is incomplete 7670 /// and cannot be completed, issues the diagnostic @p diag (giving it 7671 /// the type @p T) and returns true. 7672 /// 7673 /// @param Loc The location in the source that the incomplete type 7674 /// diagnostic should refer to. 7675 /// 7676 /// @param T The type that this routine is examining for completeness. 7677 /// 7678 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 7679 /// @c false otherwise. 7680 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 7681 TypeDiagnoser &Diagnoser) { 7682 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser)) 7683 return true; 7684 if (const TagType *Tag = T->getAs<TagType>()) { 7685 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 7686 Tag->getDecl()->setCompleteDefinitionRequired(); 7687 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 7688 } 7689 } 7690 return false; 7691 } 7692 7693 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { 7694 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; 7695 if (!Suggested) 7696 return false; 7697 7698 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext 7699 // and isolate from other C++ specific checks. 7700 StructuralEquivalenceContext Ctx( 7701 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, 7702 StructuralEquivalenceKind::Default, 7703 false /*StrictTypeSpelling*/, true /*Complain*/, 7704 true /*ErrorOnTagTypeMismatch*/); 7705 return Ctx.IsEquivalent(D, Suggested); 7706 } 7707 7708 /// Determine whether there is any declaration of \p D that was ever a 7709 /// definition (perhaps before module merging) and is currently visible. 7710 /// \param D The definition of the entity. 7711 /// \param Suggested Filled in with the declaration that should be made visible 7712 /// in order to provide a definition of this entity. 7713 /// \param OnlyNeedComplete If \c true, we only need the type to be complete, 7714 /// not defined. This only matters for enums with a fixed underlying 7715 /// type, since in all other cases, a type is complete if and only if it 7716 /// is defined. 7717 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 7718 bool OnlyNeedComplete) { 7719 // Easy case: if we don't have modules, all declarations are visible. 7720 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) 7721 return true; 7722 7723 // If this definition was instantiated from a template, map back to the 7724 // pattern from which it was instantiated. 7725 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { 7726 // We're in the middle of defining it; this definition should be treated 7727 // as visible. 7728 return true; 7729 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 7730 if (auto *Pattern = RD->getTemplateInstantiationPattern()) 7731 RD = Pattern; 7732 D = RD->getDefinition(); 7733 } else if (auto *ED = dyn_cast<EnumDecl>(D)) { 7734 if (auto *Pattern = ED->getTemplateInstantiationPattern()) 7735 ED = Pattern; 7736 if (OnlyNeedComplete && ED->isFixed()) { 7737 // If the enum has a fixed underlying type, and we're only looking for a 7738 // complete type (not a definition), any visible declaration of it will 7739 // do. 7740 *Suggested = nullptr; 7741 for (auto *Redecl : ED->redecls()) { 7742 if (isVisible(Redecl)) 7743 return true; 7744 if (Redecl->isThisDeclarationADefinition() || 7745 (Redecl->isCanonicalDecl() && !*Suggested)) 7746 *Suggested = Redecl; 7747 } 7748 return false; 7749 } 7750 D = ED->getDefinition(); 7751 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { 7752 if (auto *Pattern = FD->getTemplateInstantiationPattern()) 7753 FD = Pattern; 7754 D = FD->getDefinition(); 7755 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 7756 if (auto *Pattern = VD->getTemplateInstantiationPattern()) 7757 VD = Pattern; 7758 D = VD->getDefinition(); 7759 } 7760 assert(D && "missing definition for pattern of instantiated definition"); 7761 7762 *Suggested = D; 7763 7764 auto DefinitionIsVisible = [&] { 7765 // The (primary) definition might be in a visible module. 7766 if (isVisible(D)) 7767 return true; 7768 7769 // A visible module might have a merged definition instead. 7770 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D) 7771 : hasVisibleMergedDefinition(D)) { 7772 if (CodeSynthesisContexts.empty() && 7773 !getLangOpts().ModulesLocalVisibility) { 7774 // Cache the fact that this definition is implicitly visible because 7775 // there is a visible merged definition. 7776 D->setVisibleDespiteOwningModule(); 7777 } 7778 return true; 7779 } 7780 7781 return false; 7782 }; 7783 7784 if (DefinitionIsVisible()) 7785 return true; 7786 7787 // The external source may have additional definitions of this entity that are 7788 // visible, so complete the redeclaration chain now and ask again. 7789 if (auto *Source = Context.getExternalSource()) { 7790 Source->CompleteRedeclChain(D); 7791 return DefinitionIsVisible(); 7792 } 7793 7794 return false; 7795 } 7796 7797 /// Locks in the inheritance model for the given class and all of its bases. 7798 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { 7799 RD = RD->getMostRecentNonInjectedDecl(); 7800 if (!RD->hasAttr<MSInheritanceAttr>()) { 7801 MSInheritanceAttr::Spelling IM; 7802 7803 switch (S.MSPointerToMemberRepresentationMethod) { 7804 case LangOptions::PPTMK_BestCase: 7805 IM = RD->calculateInheritanceModel(); 7806 break; 7807 case LangOptions::PPTMK_FullGeneralitySingleInheritance: 7808 IM = MSInheritanceAttr::Keyword_single_inheritance; 7809 break; 7810 case LangOptions::PPTMK_FullGeneralityMultipleInheritance: 7811 IM = MSInheritanceAttr::Keyword_multiple_inheritance; 7812 break; 7813 case LangOptions::PPTMK_FullGeneralityVirtualInheritance: 7814 IM = MSInheritanceAttr::Keyword_unspecified_inheritance; 7815 break; 7816 } 7817 7818 RD->addAttr(MSInheritanceAttr::CreateImplicit( 7819 S.getASTContext(), IM, 7820 /*BestCase=*/S.MSPointerToMemberRepresentationMethod == 7821 LangOptions::PPTMK_BestCase, 7822 S.ImplicitMSInheritanceAttrLoc.isValid() 7823 ? S.ImplicitMSInheritanceAttrLoc 7824 : RD->getSourceRange())); 7825 S.Consumer.AssignInheritanceModel(RD); 7826 } 7827 } 7828 7829 /// The implementation of RequireCompleteType 7830 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 7831 TypeDiagnoser *Diagnoser) { 7832 // FIXME: Add this assertion to make sure we always get instantiation points. 7833 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 7834 // FIXME: Add this assertion to help us flush out problems with 7835 // checking for dependent types and type-dependent expressions. 7836 // 7837 // assert(!T->isDependentType() && 7838 // "Can't ask whether a dependent type is complete"); 7839 7840 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { 7841 if (!MPTy->getClass()->isDependentType()) { 7842 if (getLangOpts().CompleteMemberPointers && 7843 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() && 7844 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), 7845 diag::err_memptr_incomplete)) 7846 return true; 7847 7848 // We lock in the inheritance model once somebody has asked us to ensure 7849 // that a pointer-to-member type is complete. 7850 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 7851 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); 7852 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); 7853 } 7854 } 7855 } 7856 7857 NamedDecl *Def = nullptr; 7858 bool Incomplete = T->isIncompleteType(&Def); 7859 7860 // Check that any necessary explicit specializations are visible. For an 7861 // enum, we just need the declaration, so don't check this. 7862 if (Def && !isa<EnumDecl>(Def)) 7863 checkSpecializationVisibility(Loc, Def); 7864 7865 // If we have a complete type, we're done. 7866 if (!Incomplete) { 7867 // If we know about the definition but it is not visible, complain. 7868 NamedDecl *SuggestedDef = nullptr; 7869 if (Def && 7870 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { 7871 // If the user is going to see an error here, recover by making the 7872 // definition visible. 7873 bool TreatAsComplete = Diagnoser && !isSFINAEContext(); 7874 if (Diagnoser && SuggestedDef) 7875 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition, 7876 /*Recover*/TreatAsComplete); 7877 return !TreatAsComplete; 7878 } else if (Def && !TemplateInstCallbacks.empty()) { 7879 CodeSynthesisContext TempInst; 7880 TempInst.Kind = CodeSynthesisContext::Memoization; 7881 TempInst.Template = Def; 7882 TempInst.Entity = Def; 7883 TempInst.PointOfInstantiation = Loc; 7884 atTemplateBegin(TemplateInstCallbacks, *this, TempInst); 7885 atTemplateEnd(TemplateInstCallbacks, *this, TempInst); 7886 } 7887 7888 return false; 7889 } 7890 7891 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def); 7892 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def); 7893 7894 // Give the external source a chance to provide a definition of the type. 7895 // This is kept separate from completing the redeclaration chain so that 7896 // external sources such as LLDB can avoid synthesizing a type definition 7897 // unless it's actually needed. 7898 if (Tag || IFace) { 7899 // Avoid diagnosing invalid decls as incomplete. 7900 if (Def->isInvalidDecl()) 7901 return true; 7902 7903 // Give the external AST source a chance to complete the type. 7904 if (auto *Source = Context.getExternalSource()) { 7905 if (Tag && Tag->hasExternalLexicalStorage()) 7906 Source->CompleteType(Tag); 7907 if (IFace && IFace->hasExternalLexicalStorage()) 7908 Source->CompleteType(IFace); 7909 // If the external source completed the type, go through the motions 7910 // again to ensure we're allowed to use the completed type. 7911 if (!T->isIncompleteType()) 7912 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 7913 } 7914 } 7915 7916 // If we have a class template specialization or a class member of a 7917 // class template specialization, or an array with known size of such, 7918 // try to instantiate it. 7919 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) { 7920 bool Instantiated = false; 7921 bool Diagnosed = false; 7922 if (RD->isDependentContext()) { 7923 // Don't try to instantiate a dependent class (eg, a member template of 7924 // an instantiated class template specialization). 7925 // FIXME: Can this ever happen? 7926 } else if (auto *ClassTemplateSpec = 7927 dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 7928 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 7929 Diagnosed = InstantiateClassTemplateSpecialization( 7930 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, 7931 /*Complain=*/Diagnoser); 7932 Instantiated = true; 7933 } 7934 } else { 7935 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass(); 7936 if (!RD->isBeingDefined() && Pattern) { 7937 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo(); 7938 assert(MSI && "Missing member specialization information?"); 7939 // This record was instantiated from a class within a template. 7940 if (MSI->getTemplateSpecializationKind() != 7941 TSK_ExplicitSpecialization) { 7942 Diagnosed = InstantiateClass(Loc, RD, Pattern, 7943 getTemplateInstantiationArgs(RD), 7944 TSK_ImplicitInstantiation, 7945 /*Complain=*/Diagnoser); 7946 Instantiated = true; 7947 } 7948 } 7949 } 7950 7951 if (Instantiated) { 7952 // Instantiate* might have already complained that the template is not 7953 // defined, if we asked it to. 7954 if (Diagnoser && Diagnosed) 7955 return true; 7956 // If we instantiated a definition, check that it's usable, even if 7957 // instantiation produced an error, so that repeated calls to this 7958 // function give consistent answers. 7959 if (!T->isIncompleteType()) 7960 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 7961 } 7962 } 7963 7964 // FIXME: If we didn't instantiate a definition because of an explicit 7965 // specialization declaration, check that it's visible. 7966 7967 if (!Diagnoser) 7968 return true; 7969 7970 Diagnoser->diagnose(*this, Loc, T); 7971 7972 // If the type was a forward declaration of a class/struct/union 7973 // type, produce a note. 7974 if (Tag && !Tag->isInvalidDecl()) 7975 Diag(Tag->getLocation(), 7976 Tag->isBeingDefined() ? diag::note_type_being_defined 7977 : diag::note_forward_declaration) 7978 << Context.getTagDeclType(Tag); 7979 7980 // If the Objective-C class was a forward declaration, produce a note. 7981 if (IFace && !IFace->isInvalidDecl()) 7982 Diag(IFace->getLocation(), diag::note_forward_class); 7983 7984 // If we have external information that we can use to suggest a fix, 7985 // produce a note. 7986 if (ExternalSource) 7987 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); 7988 7989 return true; 7990 } 7991 7992 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 7993 unsigned DiagID) { 7994 BoundTypeDiagnoser<> Diagnoser(DiagID); 7995 return RequireCompleteType(Loc, T, Diagnoser); 7996 } 7997 7998 /// Get diagnostic %select index for tag kind for 7999 /// literal type diagnostic message. 8000 /// WARNING: Indexes apply to particular diagnostics only! 8001 /// 8002 /// \returns diagnostic %select index. 8003 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 8004 switch (Tag) { 8005 case TTK_Struct: return 0; 8006 case TTK_Interface: return 1; 8007 case TTK_Class: return 2; 8008 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 8009 } 8010 } 8011 8012 /// Ensure that the type T is a literal type. 8013 /// 8014 /// This routine checks whether the type @p T is a literal type. If @p T is an 8015 /// incomplete type, an attempt is made to complete it. If @p T is a literal 8016 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 8017 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 8018 /// it the type @p T), along with notes explaining why the type is not a 8019 /// literal type, and returns true. 8020 /// 8021 /// @param Loc The location in the source that the non-literal type 8022 /// diagnostic should refer to. 8023 /// 8024 /// @param T The type that this routine is examining for literalness. 8025 /// 8026 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 8027 /// 8028 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 8029 /// @c false otherwise. 8030 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 8031 TypeDiagnoser &Diagnoser) { 8032 assert(!T->isDependentType() && "type should not be dependent"); 8033 8034 QualType ElemType = Context.getBaseElementType(T); 8035 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && 8036 T->isLiteralType(Context)) 8037 return false; 8038 8039 Diagnoser.diagnose(*this, Loc, T); 8040 8041 if (T->isVariableArrayType()) 8042 return true; 8043 8044 const RecordType *RT = ElemType->getAs<RecordType>(); 8045 if (!RT) 8046 return true; 8047 8048 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 8049 8050 // A partially-defined class type can't be a literal type, because a literal 8051 // class type must have a trivial destructor (which can't be checked until 8052 // the class definition is complete). 8053 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) 8054 return true; 8055 8056 // [expr.prim.lambda]p3: 8057 // This class type is [not] a literal type. 8058 if (RD->isLambda() && !getLangOpts().CPlusPlus17) { 8059 Diag(RD->getLocation(), diag::note_non_literal_lambda); 8060 return true; 8061 } 8062 8063 // If the class has virtual base classes, then it's not an aggregate, and 8064 // cannot have any constexpr constructors or a trivial default constructor, 8065 // so is non-literal. This is better to diagnose than the resulting absence 8066 // of constexpr constructors. 8067 if (RD->getNumVBases()) { 8068 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 8069 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 8070 for (const auto &I : RD->vbases()) 8071 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 8072 << I.getSourceRange(); 8073 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 8074 !RD->hasTrivialDefaultConstructor()) { 8075 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 8076 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 8077 for (const auto &I : RD->bases()) { 8078 if (!I.getType()->isLiteralType(Context)) { 8079 Diag(I.getBeginLoc(), diag::note_non_literal_base_class) 8080 << RD << I.getType() << I.getSourceRange(); 8081 return true; 8082 } 8083 } 8084 for (const auto *I : RD->fields()) { 8085 if (!I->getType()->isLiteralType(Context) || 8086 I->getType().isVolatileQualified()) { 8087 Diag(I->getLocation(), diag::note_non_literal_field) 8088 << RD << I << I->getType() 8089 << I->getType().isVolatileQualified(); 8090 return true; 8091 } 8092 } 8093 } else if (!RD->hasTrivialDestructor()) { 8094 // All fields and bases are of literal types, so have trivial destructors. 8095 // If this class's destructor is non-trivial it must be user-declared. 8096 CXXDestructorDecl *Dtor = RD->getDestructor(); 8097 assert(Dtor && "class has literal fields and bases but no dtor?"); 8098 if (!Dtor) 8099 return true; 8100 8101 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 8102 diag::note_non_literal_user_provided_dtor : 8103 diag::note_non_literal_nontrivial_dtor) << RD; 8104 if (!Dtor->isUserProvided()) 8105 SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI, 8106 /*Diagnose*/true); 8107 } 8108 8109 return true; 8110 } 8111 8112 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 8113 BoundTypeDiagnoser<> Diagnoser(DiagID); 8114 return RequireLiteralType(Loc, T, Diagnoser); 8115 } 8116 8117 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified 8118 /// by the nested-name-specifier contained in SS, and that is (re)declared by 8119 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration. 8120 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 8121 const CXXScopeSpec &SS, QualType T, 8122 TagDecl *OwnedTagDecl) { 8123 if (T.isNull()) 8124 return T; 8125 NestedNameSpecifier *NNS; 8126 if (SS.isValid()) 8127 NNS = SS.getScopeRep(); 8128 else { 8129 if (Keyword == ETK_None) 8130 return T; 8131 NNS = nullptr; 8132 } 8133 return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl); 8134 } 8135 8136 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 8137 assert(!E->hasPlaceholderType() && "unexpected placeholder"); 8138 8139 if (!getLangOpts().CPlusPlus && E->refersToBitField()) 8140 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; 8141 8142 if (!E->isTypeDependent()) { 8143 QualType T = E->getType(); 8144 if (const TagType *TT = T->getAs<TagType>()) 8145 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 8146 } 8147 return Context.getTypeOfExprType(E); 8148 } 8149 8150 /// getDecltypeForExpr - Given an expr, will return the decltype for 8151 /// that expression, according to the rules in C++11 8152 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 8153 static QualType getDecltypeForExpr(Sema &S, Expr *E) { 8154 if (E->isTypeDependent()) 8155 return S.Context.DependentTy; 8156 8157 // C++11 [dcl.type.simple]p4: 8158 // The type denoted by decltype(e) is defined as follows: 8159 // 8160 // - if e is an unparenthesized id-expression or an unparenthesized class 8161 // member access (5.2.5), decltype(e) is the type of the entity named 8162 // by e. If there is no such entity, or if e names a set of overloaded 8163 // functions, the program is ill-formed; 8164 // 8165 // We apply the same rules for Objective-C ivar and property references. 8166 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 8167 const ValueDecl *VD = DRE->getDecl(); 8168 return VD->getType(); 8169 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 8170 if (const ValueDecl *VD = ME->getMemberDecl()) 8171 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD)) 8172 return VD->getType(); 8173 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { 8174 return IR->getDecl()->getType(); 8175 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { 8176 if (PR->isExplicitProperty()) 8177 return PR->getExplicitProperty()->getType(); 8178 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { 8179 return PE->getType(); 8180 } 8181 8182 // C++11 [expr.lambda.prim]p18: 8183 // Every occurrence of decltype((x)) where x is a possibly 8184 // parenthesized id-expression that names an entity of automatic 8185 // storage duration is treated as if x were transformed into an 8186 // access to a corresponding data member of the closure type that 8187 // would have been declared if x were an odr-use of the denoted 8188 // entity. 8189 using namespace sema; 8190 if (S.getCurLambda()) { 8191 if (isa<ParenExpr>(E)) { 8192 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 8193 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 8194 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 8195 if (!T.isNull()) 8196 return S.Context.getLValueReferenceType(T); 8197 } 8198 } 8199 } 8200 } 8201 8202 8203 // C++11 [dcl.type.simple]p4: 8204 // [...] 8205 QualType T = E->getType(); 8206 switch (E->getValueKind()) { 8207 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 8208 // type of e; 8209 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 8210 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 8211 // type of e; 8212 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 8213 // - otherwise, decltype(e) is the type of e. 8214 case VK_RValue: break; 8215 } 8216 8217 return T; 8218 } 8219 8220 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc, 8221 bool AsUnevaluated) { 8222 assert(!E->hasPlaceholderType() && "unexpected placeholder"); 8223 8224 if (AsUnevaluated && CodeSynthesisContexts.empty() && 8225 E->HasSideEffects(Context, false)) { 8226 // The expression operand for decltype is in an unevaluated expression 8227 // context, so side effects could result in unintended consequences. 8228 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 8229 } 8230 8231 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 8232 } 8233 8234 QualType Sema::BuildUnaryTransformType(QualType BaseType, 8235 UnaryTransformType::UTTKind UKind, 8236 SourceLocation Loc) { 8237 switch (UKind) { 8238 case UnaryTransformType::EnumUnderlyingType: 8239 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 8240 Diag(Loc, diag::err_only_enums_have_underlying_types); 8241 return QualType(); 8242 } else { 8243 QualType Underlying = BaseType; 8244 if (!BaseType->isDependentType()) { 8245 // The enum could be incomplete if we're parsing its definition or 8246 // recovering from an error. 8247 NamedDecl *FwdDecl = nullptr; 8248 if (BaseType->isIncompleteType(&FwdDecl)) { 8249 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; 8250 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; 8251 return QualType(); 8252 } 8253 8254 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 8255 assert(ED && "EnumType has no EnumDecl"); 8256 8257 DiagnoseUseOfDecl(ED, Loc); 8258 8259 Underlying = ED->getIntegerType(); 8260 assert(!Underlying.isNull()); 8261 } 8262 return Context.getUnaryTransformType(BaseType, Underlying, 8263 UnaryTransformType::EnumUnderlyingType); 8264 } 8265 } 8266 llvm_unreachable("unknown unary transform type"); 8267 } 8268 8269 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 8270 if (!T->isDependentType()) { 8271 // FIXME: It isn't entirely clear whether incomplete atomic types 8272 // are allowed or not; for simplicity, ban them for the moment. 8273 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 8274 return QualType(); 8275 8276 int DisallowedKind = -1; 8277 if (T->isArrayType()) 8278 DisallowedKind = 1; 8279 else if (T->isFunctionType()) 8280 DisallowedKind = 2; 8281 else if (T->isReferenceType()) 8282 DisallowedKind = 3; 8283 else if (T->isAtomicType()) 8284 DisallowedKind = 4; 8285 else if (T.hasQualifiers()) 8286 DisallowedKind = 5; 8287 else if (!T.isTriviallyCopyableType(Context)) 8288 // Some other non-trivially-copyable type (probably a C++ class) 8289 DisallowedKind = 6; 8290 8291 if (DisallowedKind != -1) { 8292 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 8293 return QualType(); 8294 } 8295 8296 // FIXME: Do we need any handling for ARC here? 8297 } 8298 8299 // Build the pointer type. 8300 return Context.getAtomicType(T); 8301 } 8302