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