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