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