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